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/main/java/nl/siegmann/ehcachetag/CacheTag.java | // 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/main/java/nl/siegmann/ehcachetag/util/StringUtil.java
// public class StringUtil {
//
// /**
// * Finds and returns the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// *
// * @see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a>
// *
// * @param input
// * @param alternatives
// * @return the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// */
// public static String getClosestMatchingString(String input, Collection<String> alternatives) {
// if (input == null || alternatives == null || alternatives.isEmpty()) {
// return null;
// }
// String current = null;
// int minDistance = Integer.MAX_VALUE;
// for (String alternative: alternatives) {
// int currentDistance = StringUtils.getLevenshteinDistance(input, alternative);
// if ((current == null) || (currentDistance < minDistance)) {
// current = alternative;
// minDistance = currentDistance;
// }
// }
// return current;
// }
//
// }
| import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory;
import nl.siegmann.ehcachetag.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
// set cacheKey to null so that the endTag knows
// it does not have to store anything in the cache
key = null;
result = BodyTagSupport.SKIP_BODY;
}
return result;
}
/**
* Internal exception that is used in case a modifier is search for but not found.
*
* @author paul
*
*/
static final class ModifierNotFoundException extends Exception {
private static final long serialVersionUID = 4535024464306691589L;
public ModifierNotFoundException(String message) {
super(message);
}
}
/**
* This method is called before doing a lookup in the cache.
* Invoke the cacheTagInterceptor.beforeLookup.
*/
void doBeforeLookup() throws Exception { | // 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/main/java/nl/siegmann/ehcachetag/util/StringUtil.java
// public class StringUtil {
//
// /**
// * Finds and returns the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// *
// * @see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a>
// *
// * @param input
// * @param alternatives
// * @return the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// */
// public static String getClosestMatchingString(String input, Collection<String> alternatives) {
// if (input == null || alternatives == null || alternatives.isEmpty()) {
// return null;
// }
// String current = null;
// int minDistance = Integer.MAX_VALUE;
// for (String alternative: alternatives) {
// int currentDistance = StringUtils.getLevenshteinDistance(input, alternative);
// if ((current == null) || (currentDistance < minDistance)) {
// current = alternative;
// minDistance = currentDistance;
// }
// }
// return current;
// }
//
// }
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/CacheTag.java
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory;
import nl.siegmann.ehcachetag.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// set cacheKey to null so that the endTag knows
// it does not have to store anything in the cache
key = null;
result = BodyTagSupport.SKIP_BODY;
}
return result;
}
/**
* Internal exception that is used in case a modifier is search for but not found.
*
* @author paul
*
*/
static final class ModifierNotFoundException extends Exception {
private static final long serialVersionUID = 4535024464306691589L;
public ModifierNotFoundException(String message) {
super(message);
}
}
/**
* This method is called before doing a lookup in the cache.
* Invoke the cacheTagInterceptor.beforeLookup.
*/
void doBeforeLookup() throws Exception { | CacheTagModifierFactory cacheTagModifierFactory = getCacheTagModifierFactory(); |
psiegman/ehcachetag | ehcachetag/src/main/java/nl/siegmann/ehcachetag/CacheTag.java | // 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/main/java/nl/siegmann/ehcachetag/util/StringUtil.java
// public class StringUtil {
//
// /**
// * Finds and returns the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// *
// * @see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a>
// *
// * @param input
// * @param alternatives
// * @return the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// */
// public static String getClosestMatchingString(String input, Collection<String> alternatives) {
// if (input == null || alternatives == null || alternatives.isEmpty()) {
// return null;
// }
// String current = null;
// int minDistance = Integer.MAX_VALUE;
// for (String alternative: alternatives) {
// int currentDistance = StringUtils.getLevenshteinDistance(input, alternative);
// if ((current == null) || (currentDistance < minDistance)) {
// current = alternative;
// minDistance = currentDistance;
// }
// }
// return current;
// }
//
// }
| import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory;
import nl.siegmann.ehcachetag.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
return result;
}
/**
* Internal exception that is used in case a modifier is search for but not found.
*
* @author paul
*
*/
static final class ModifierNotFoundException extends Exception {
private static final long serialVersionUID = 4535024464306691589L;
public ModifierNotFoundException(String message) {
super(message);
}
}
/**
* This method is called before doing a lookup in the cache.
* Invoke the cacheTagInterceptor.beforeLookup.
*/
void doBeforeLookup() throws Exception {
CacheTagModifierFactory cacheTagModifierFactory = getCacheTagModifierFactory();
if (cacheTagModifierFactory == null) {
return;
}
for (String modifierName: modifiers) { | // 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/main/java/nl/siegmann/ehcachetag/util/StringUtil.java
// public class StringUtil {
//
// /**
// * Finds and returns the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// *
// * @see <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance</a>
// *
// * @param input
// * @param alternatives
// * @return the string from the alternatives that closest matches the input string based on the Levenshtein distance.
// */
// public static String getClosestMatchingString(String input, Collection<String> alternatives) {
// if (input == null || alternatives == null || alternatives.isEmpty()) {
// return null;
// }
// String current = null;
// int minDistance = Integer.MAX_VALUE;
// for (String alternative: alternatives) {
// int currentDistance = StringUtils.getLevenshteinDistance(input, alternative);
// if ((current == null) || (currentDistance < minDistance)) {
// current = alternative;
// minDistance = currentDistance;
// }
// }
// return current;
// }
//
// }
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/CacheTag.java
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier;
import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory;
import nl.siegmann.ehcachetag.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
return result;
}
/**
* Internal exception that is used in case a modifier is search for but not found.
*
* @author paul
*
*/
static final class ModifierNotFoundException extends Exception {
private static final long serialVersionUID = 4535024464306691589L;
public ModifierNotFoundException(String message) {
super(message);
}
}
/**
* This method is called before doing a lookup in the cache.
* Invoke the cacheTagInterceptor.beforeLookup.
*/
void doBeforeLookup() throws Exception {
CacheTagModifierFactory cacheTagModifierFactory = getCacheTagModifierFactory();
if (cacheTagModifierFactory == null) {
return;
}
for (String modifierName: modifiers) { | CacheTagModifier cacheTagModifier = getCacheTagModifier(cacheTagModifierFactory, modifierName); |
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; | package nl.siegmann.ehcachetag;
public class CacheTagTest {
@Mock
private PageContext pageContext;
@Mock
private ServletContext servletContext;
@Mock
private JspWriter jspWriter = Mockito.mock(JspWriter.class);
@Mock | // 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;
package nl.siegmann.ehcachetag;
public class CacheTagTest {
@Mock
private PageContext pageContext;
@Mock
private ServletContext servletContext;
@Mock
private JspWriter jspWriter = Mockito.mock(JspWriter.class);
@Mock | private CacheTagModifierFactory cacheTagModifierFactory; |
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; | package nl.siegmann.ehcachetag;
public class CacheTagTest {
@Mock
private PageContext pageContext;
@Mock
private ServletContext servletContext;
@Mock
private JspWriter jspWriter = Mockito.mock(JspWriter.class);
@Mock
private CacheTagModifierFactory cacheTagModifierFactory;
@Mock | // 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;
package nl.siegmann.ehcachetag;
public class CacheTagTest {
@Mock
private PageContext pageContext;
@Mock
private ServletContext servletContext;
@Mock
private JspWriter jspWriter = Mockito.mock(JspWriter.class);
@Mock
private CacheTagModifierFactory cacheTagModifierFactory;
@Mock | private CacheTagModifier cacheTagModifier; |
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); |
artiomchi/Dual-Battery-Widget | src/org/flexlabs/widgets/dualbattery/BatteryWidget.java | // Path: src/org/flexlabs/widgets/dualbattery/service/MonitorService.java
// public class MonitorService extends Service {
// private IntentReceiver batteryReceiver;
//
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// public void onCreate() {
// super.onCreate();
// batteryReceiver = new IntentReceiver(this);
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// }
//
// private void processStartIntent(Intent intent) {
// if (intent == null)
// return;
// final int[] widgetIds = intent.getIntArrayExtra(Constants.EXTRA_WIDGET_IDS);
// if (widgetIds != null) {
// // Update our widgets on the non UI thread
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// BatteryWidgetUpdater.updateAllWidgets(MonitorService.this, BatteryLevel.getCurrent(), widgetIds);
// } catch (Exception ignore) {}
// }
// }).start();
// }
// }
//
// @Override
// public void onStart(Intent intent, int startId) { // For compatibility with android 1.6
// processStartIntent(intent);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// processStartIntent(intent);
// return START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// unregisterReceiver(batteryReceiver);
// }
// }
| import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.*;
import org.flexlabs.widgets.dualbattery.service.MonitorService;
import java.io.File;
| /*
* Copyright 2011 Artiom Chilaru (http://flexlabs.org)
*
* 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.flexlabs.widgets.dualbattery;
public class BatteryWidget extends AppWidgetProvider {
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
| // Path: src/org/flexlabs/widgets/dualbattery/service/MonitorService.java
// public class MonitorService extends Service {
// private IntentReceiver batteryReceiver;
//
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// public void onCreate() {
// super.onCreate();
// batteryReceiver = new IntentReceiver(this);
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_DOCK_EVENT));
// registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// }
//
// private void processStartIntent(Intent intent) {
// if (intent == null)
// return;
// final int[] widgetIds = intent.getIntArrayExtra(Constants.EXTRA_WIDGET_IDS);
// if (widgetIds != null) {
// // Update our widgets on the non UI thread
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// BatteryWidgetUpdater.updateAllWidgets(MonitorService.this, BatteryLevel.getCurrent(), widgetIds);
// } catch (Exception ignore) {}
// }
// }).start();
// }
// }
//
// @Override
// public void onStart(Intent intent, int startId) { // For compatibility with android 1.6
// processStartIntent(intent);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// processStartIntent(intent);
// return START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// unregisterReceiver(batteryReceiver);
// }
// }
// Path: src/org/flexlabs/widgets/dualbattery/BatteryWidget.java
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.*;
import org.flexlabs.widgets.dualbattery.service.MonitorService;
import java.io.File;
/*
* Copyright 2011 Artiom Chilaru (http://flexlabs.org)
*
* 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.flexlabs.widgets.dualbattery;
public class BatteryWidget extends AppWidgetProvider {
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
| context.startService(new Intent(context, MonitorService.class));
|
artiomchi/Dual-Battery-Widget | src/org/flexlabs/widgets/dualbattery/app/SettingsContainer.java | // Path: src/org/flexlabs/widgets/dualbattery/Constants.java
// public class Constants {
// public static final String LOG = "FlexLabs.DBW";
// public static final boolean DEBUG = false;
// public static boolean HAS_GPLAY_BILLING = false;
// public static String VERSION;
//
// public static final String EXTRA_WIDGET_IDS = "widgetIds";
// public static final String SETTINGS_WIDGET_FILE = "widgetPref_";
// public static final String FeedbackDestination = "FlexLabs <android@flexlabs.org>";
//
// public static final int DOCK_STATE_UNKNOWN = 0;
// public static final int DOCK_STATE_UNDOCKED = 1;
// public static final int DOCK_STATE_CHARGING = 2;
// public static final int DOCK_STATE_DOCKED = 3;
// public static final int DOCK_STATE_DISCHARGING = 4;
//
// public static final String SETTING_VERSION = "version";
// public static final int SETTING_VERSION_CURRENT = 4;
// public static final String SETTING_ALWAYS_SHOW_DOCK = "alwaysShowDock";
// public static final boolean SETTING_ALWAYS_SHOW_DOCK_DEFAULT = true;
//
// public static final int TEXT_POS_INVISIBLE = 0;
// public static final int TEXT_POS_TOP = 1;
// public static final int TEXT_POS_MIDDLE = 2;
// public static final int TEXT_POS_BOTTOM = 3;
// public static final int TEXT_POS_ABOVE = 4;
// public static final int TEXT_POS_BELOW = 5;
// public static final String SETTING_TEXT_POS = "textPosition";
// public static final int SETTING_TEXT_POS_DEFAULT = TEXT_POS_MIDDLE;
//
// public static final String SETTING_TEXT_SIZE = "textSize";
// public static final int SETTING_TEXT_SIZE_DEFAULT = 14;
// public static final String SETTING_SHOW_NOT_DOCKED = "showNotDockedMessage";
// public static final boolean SETTING_SHOW_NOT_DOCKED_DEFAULT = true;
//
// public static final int BATTERY_SELECTION_BOTH = 3;
// public static final int BATTERY_SELECTION_MAIN = 1;
// public static final int BATTERY_SELECTION_DOCK = 2;
// public static final String SETTING_SHOW_SELECTION = "batterySelection";
// public static final int SETTING_SHOW_SELECTION_DEFAULT = BATTERY_SELECTION_BOTH;
//
// public static final int TEXT_COLOR_WHITE = 0;
// public static final int TEXT_COLOR_BLACK = 1;
// public static final String SETTING_TEXT_COLOR = "textColor";
// public static final int SETTING_TEXT_COLOR_DEFAULT = TEXT_COLOR_WHITE;
//
// public static final int MARGIN_NONE = 0;
// public static final int MARGIN_TOP = 1;
// public static final int MARGIN_BOTTOM = 2;
// public static final int MARGIN_BOTH = 3;
// public static final String SETTING_MARGIN = "marginLocation";
// public static final int SETTING_MARGIN_DEFAULT = MARGIN_NONE;
//
// public static final String SETTING_SHOW_LABEL = "showBatteryLabel";
// public static final boolean SETTING_SHOW_LABEL_DEFAULT = false;
// public static final String SETTING_SHOW_OLD_DOCK = "showOldDockStatus";
// public static final boolean SETTING_SHOW_OLD_DOCK_DEFAULT = true;
// public static final int TEMP_UNIT_CELSIUS = 0;
// public static final int TEMP_UNIT_FAHRENHEIT = 1;
// public static final String SETTING_TEMP_UNITS = "tempUnitsInt";
// public static final int SETTING_TEMP_UNITS_DEFAULT = TEMP_UNIT_CELSIUS;
//
// public static final String SETTING_SWAP_BATTERIES = "swapBatteries";
// public static final boolean SETTING_SWAP_BATTERIES_DEFAULT = false;
// public static final String SETTING_THEME = "theme";
// public static final String SETTING_THEME_DEFAULT = "Default";
// public static final String SETTING_JUST_SWAPPED = "justSwapped";
// public static final boolean SETTING_JUST_SWAPPED_DEFAULT = false;
//
// public static final String SETTINGS_FILE = "appSettings";
// public static final String SETTING_NOTIFICATION_ICON = "showNotificationIcon";
// public static final boolean SETTING_NOTIFICATION_ICON_DEFAULT = true;
// public static final String SETTING_DEFAULT_DAYS_TAB = "defaultDaysTab";
// public static final int SETTING_DEFAULT_DAYS_TAB_DEFAULT = 3;
//
// public static final String URI_PAYPAL = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=6UHRDDAPAMSTL&lc=GB&item_name=Donation%20for%20Artiom%20Chilaru¤cy_code=GBP&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted";
// }
| import android.content.Context;
import android.content.SharedPreferences;
import org.flexlabs.widgets.dualbattery.Constants; | /*
* Copyright 2012 Artiom Chilaru (http://flexlabs.org)
*
* 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.flexlabs.widgets.dualbattery.app;
public class SettingsContainer {
private int defaultDaysTab;
private boolean showNotificationIcon;
private static SharedPreferences getPreferences(Context context) { | // Path: src/org/flexlabs/widgets/dualbattery/Constants.java
// public class Constants {
// public static final String LOG = "FlexLabs.DBW";
// public static final boolean DEBUG = false;
// public static boolean HAS_GPLAY_BILLING = false;
// public static String VERSION;
//
// public static final String EXTRA_WIDGET_IDS = "widgetIds";
// public static final String SETTINGS_WIDGET_FILE = "widgetPref_";
// public static final String FeedbackDestination = "FlexLabs <android@flexlabs.org>";
//
// public static final int DOCK_STATE_UNKNOWN = 0;
// public static final int DOCK_STATE_UNDOCKED = 1;
// public static final int DOCK_STATE_CHARGING = 2;
// public static final int DOCK_STATE_DOCKED = 3;
// public static final int DOCK_STATE_DISCHARGING = 4;
//
// public static final String SETTING_VERSION = "version";
// public static final int SETTING_VERSION_CURRENT = 4;
// public static final String SETTING_ALWAYS_SHOW_DOCK = "alwaysShowDock";
// public static final boolean SETTING_ALWAYS_SHOW_DOCK_DEFAULT = true;
//
// public static final int TEXT_POS_INVISIBLE = 0;
// public static final int TEXT_POS_TOP = 1;
// public static final int TEXT_POS_MIDDLE = 2;
// public static final int TEXT_POS_BOTTOM = 3;
// public static final int TEXT_POS_ABOVE = 4;
// public static final int TEXT_POS_BELOW = 5;
// public static final String SETTING_TEXT_POS = "textPosition";
// public static final int SETTING_TEXT_POS_DEFAULT = TEXT_POS_MIDDLE;
//
// public static final String SETTING_TEXT_SIZE = "textSize";
// public static final int SETTING_TEXT_SIZE_DEFAULT = 14;
// public static final String SETTING_SHOW_NOT_DOCKED = "showNotDockedMessage";
// public static final boolean SETTING_SHOW_NOT_DOCKED_DEFAULT = true;
//
// public static final int BATTERY_SELECTION_BOTH = 3;
// public static final int BATTERY_SELECTION_MAIN = 1;
// public static final int BATTERY_SELECTION_DOCK = 2;
// public static final String SETTING_SHOW_SELECTION = "batterySelection";
// public static final int SETTING_SHOW_SELECTION_DEFAULT = BATTERY_SELECTION_BOTH;
//
// public static final int TEXT_COLOR_WHITE = 0;
// public static final int TEXT_COLOR_BLACK = 1;
// public static final String SETTING_TEXT_COLOR = "textColor";
// public static final int SETTING_TEXT_COLOR_DEFAULT = TEXT_COLOR_WHITE;
//
// public static final int MARGIN_NONE = 0;
// public static final int MARGIN_TOP = 1;
// public static final int MARGIN_BOTTOM = 2;
// public static final int MARGIN_BOTH = 3;
// public static final String SETTING_MARGIN = "marginLocation";
// public static final int SETTING_MARGIN_DEFAULT = MARGIN_NONE;
//
// public static final String SETTING_SHOW_LABEL = "showBatteryLabel";
// public static final boolean SETTING_SHOW_LABEL_DEFAULT = false;
// public static final String SETTING_SHOW_OLD_DOCK = "showOldDockStatus";
// public static final boolean SETTING_SHOW_OLD_DOCK_DEFAULT = true;
// public static final int TEMP_UNIT_CELSIUS = 0;
// public static final int TEMP_UNIT_FAHRENHEIT = 1;
// public static final String SETTING_TEMP_UNITS = "tempUnitsInt";
// public static final int SETTING_TEMP_UNITS_DEFAULT = TEMP_UNIT_CELSIUS;
//
// public static final String SETTING_SWAP_BATTERIES = "swapBatteries";
// public static final boolean SETTING_SWAP_BATTERIES_DEFAULT = false;
// public static final String SETTING_THEME = "theme";
// public static final String SETTING_THEME_DEFAULT = "Default";
// public static final String SETTING_JUST_SWAPPED = "justSwapped";
// public static final boolean SETTING_JUST_SWAPPED_DEFAULT = false;
//
// public static final String SETTINGS_FILE = "appSettings";
// public static final String SETTING_NOTIFICATION_ICON = "showNotificationIcon";
// public static final boolean SETTING_NOTIFICATION_ICON_DEFAULT = true;
// public static final String SETTING_DEFAULT_DAYS_TAB = "defaultDaysTab";
// public static final int SETTING_DEFAULT_DAYS_TAB_DEFAULT = 3;
//
// public static final String URI_PAYPAL = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=6UHRDDAPAMSTL&lc=GB&item_name=Donation%20for%20Artiom%20Chilaru¤cy_code=GBP&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted";
// }
// Path: src/org/flexlabs/widgets/dualbattery/app/SettingsContainer.java
import android.content.Context;
import android.content.SharedPreferences;
import org.flexlabs.widgets.dualbattery.Constants;
/*
* Copyright 2012 Artiom Chilaru (http://flexlabs.org)
*
* 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.flexlabs.widgets.dualbattery.app;
public class SettingsContainer {
private int defaultDaysTab;
private boolean showNotificationIcon;
private static SharedPreferences getPreferences(Context context) { | return context.getSharedPreferences(Constants.SETTINGS_FILE, Context.MODE_PRIVATE); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/tree/TreeRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
| import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Create a tree of routers
* <p>
* The tree must be constructed before passed into the constructor.
* TreeRouter and Node supports k-ary trees though some implementations may be binary only.
* If the router reaches a dead end (a node that is not a leaf and does not return a child),
* it returns an empty array.
*/
public class TreeRouter implements Router {
private Node root;
/**
* Create a tree router
*
* @param root Root node of the constructed tree
*/
public TreeRouter(Node root) {
this.root = root;
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/tree/TreeRouter.java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Create a tree of routers
* <p>
* The tree must be constructed before passed into the constructor.
* TreeRouter and Node supports k-ary trees though some implementations may be binary only.
* If the router reaches a dead end (a node that is not a leaf and does not return a child),
* it returns an empty array.
*/
public class TreeRouter implements Router {
private Node root;
/**
* Create a tree router
*
* @param root Root node of the constructed tree
*/
public TreeRouter(Node root) {
this.root = root;
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/tree/TreeRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
| import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Create a tree of routers
* <p>
* The tree must be constructed before passed into the constructor.
* TreeRouter and Node supports k-ary trees though some implementations may be binary only.
* If the router reaches a dead end (a node that is not a leaf and does not return a child),
* it returns an empty array.
*/
public class TreeRouter implements Router {
private Node root;
/**
* Create a tree router
*
* @param root Root node of the constructed tree
*/
public TreeRouter(Node root) {
this.root = root;
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/tree/TreeRouter.java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Create a tree of routers
* <p>
* The tree must be constructed before passed into the constructor.
* TreeRouter and Node supports k-ary trees though some implementations may be binary only.
* If the router reaches a dead end (a node that is not a leaf and does not return a child),
* it returns an empty array.
*/
public class TreeRouter implements Router {
private Node root;
/**
* Create a tree router
*
* @param root Root node of the constructed tree
*/
public TreeRouter(Node root) {
this.root = root;
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/TreeRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class TreeRouterTest {
protected Router createBinaryTreeRouter() {
// binary tree defined as so with keywords:
// root
// weather score
// historical current baseball football | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/TreeRouterTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class TreeRouterTest {
protected Router createBinaryTreeRouter() {
// binary tree defined as so with keywords:
// root
// weather score
// historical current baseball football | Agent a1 = mock(Agent.class); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/TreeRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class TreeRouterTest {
protected Router createBinaryTreeRouter() {
// binary tree defined as so with keywords:
// root
// weather score
// historical current baseball football
Agent a1 = mock(Agent.class);
when(a1.getName()).thenReturn("historical");
Agent a2 = mock(Agent.class);
when(a2.getName()).thenReturn("current");
Node weatherNode = new BinaryKeywordNode("historical", new LeafNode(a1), new LeafNode(a2));
Agent a3 = mock(Agent.class);
when(a3.getName()).thenReturn("baseball");
Agent a4 = mock(Agent.class);
when(a4.getName()).thenReturn("football");
Node scoreNode = new BinaryKeywordNode("baseball", new LeafNode(a3), new LeafNode(a4));
Node root = new BinaryKeywordNode("weather", weatherNode, scoreNode);
return new TreeRouter(root);
}
@Test
public void testRoutingWithBinaryTree() {
Router router = createBinaryTreeRouter(); | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/routing/Router.java
// public interface Router {
//
// /**
// * Get an array of agents to send the request to
// *
// * @param request the request object
// * @return array of agents (empty array if no agent found)
// */
// public Agent[] route(Request request);
//
// /**
// * Get an array of the agents for this router
// *
// * @return array of agents
// */
// public Agent[] getAgents();
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/TreeRouterTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.routing.Router;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class TreeRouterTest {
protected Router createBinaryTreeRouter() {
// binary tree defined as so with keywords:
// root
// weather score
// historical current baseball football
Agent a1 = mock(Agent.class);
when(a1.getName()).thenReturn("historical");
Agent a2 = mock(Agent.class);
when(a2.getName()).thenReturn("current");
Node weatherNode = new BinaryKeywordNode("historical", new LeafNode(a1), new LeafNode(a2));
Agent a3 = mock(Agent.class);
when(a3.getName()).thenReturn("baseball");
Agent a4 = mock(Agent.class);
when(a4.getName()).thenReturn("football");
Node scoreNode = new BinaryKeywordNode("baseball", new LeafNode(a3), new LeafNode(a4));
Node root = new BinaryKeywordNode("weather", weatherNode, scoreNode);
return new TreeRouter(root);
}
@Test
public void testRoutingWithBinaryTree() {
Router router = createBinaryTreeRouter(); | Request r1 = new Request("What is the historical weather for June"); |
DorsetProject/dorset-framework | api/src/main/java/edu/jhuapl/dorset/rest/WebResponseWithError.java | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
| import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response with an error
* <p>
* Extends the WebResponse with the optional error information
*/
@XmlRootElement
public class WebResponseWithError extends WebResponse {
protected final Error error;
/**
* Create a web response
*
* @param resp the response from the Dorset application
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
// Path: api/src/main/java/edu/jhuapl/dorset/rest/WebResponseWithError.java
import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response with an error
* <p>
* Extends the WebResponse with the optional error information
*/
@XmlRootElement
public class WebResponseWithError extends WebResponse {
protected final Error error;
/**
* Create a web response
*
* @param resp the response from the Dorset application
*/ | public WebResponseWithError(Response resp) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/agents/ResponseCodeJsonAdapterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import edu.jhuapl.dorset.ResponseStatus; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
public class ResponseCodeJsonAdapterTest {
private Gson getGson() {
GsonBuilder builder = new GsonBuilder(); | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
// Path: core/src/test/java/edu/jhuapl/dorset/agents/ResponseCodeJsonAdapterTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import edu.jhuapl.dorset.ResponseStatus;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
public class ResponseCodeJsonAdapterTest {
private Gson getGson() {
GsonBuilder builder = new GsonBuilder(); | builder.registerTypeAdapter(ResponseStatus.Code.class, new ResponseCodeJsonAdapter().nullSafe()); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/filters/AliasRequestFilterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import edu.jhuapl.dorset.Request; | package edu.jhuapl.dorset.filters;
public class AliasRequestFilterTest {
@Test
public void AliasRequestFilterOneAlias() {
String strRequest = "What is the runtime for the film Finding Nemo?";
String strFilteredRequest = "What is the runtime for the movie Finding Nemo?";
Map<String, String> aliasMap = new HashMap<String, String>();
aliasMap.put("film", "movie");
RequestFilter requestFilter = new AliasRequestFilter(aliasMap);
| // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
// Path: core/src/test/java/edu/jhuapl/dorset/filters/AliasRequestFilterTest.java
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
package edu.jhuapl.dorset.filters;
public class AliasRequestFilterTest {
@Test
public void AliasRequestFilterOneAlias() {
String strRequest = "What is the runtime for the film Finding Nemo?";
String strFilteredRequest = "What is the runtime for the movie Finding Nemo?";
Map<String, String> aliasMap = new HashMap<String, String>();
aliasMap.put("film", "movie");
RequestFilter requestFilter = new AliasRequestFilter(aliasMap);
| Request request = new Request(strRequest); |
DorsetProject/dorset-framework | components/user-service/src/main/java/edu/jhuapl/dorset/ldapuserservice/LdapUserService.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.ldapuserservice;
/**
* LdapUserService userservice
*
* LdapUserService is a UserService that pulls users' information from a LDAP server. The
* configuration information for the LDAP server, as well as the LDAP search controls, are stored in
* a configuration object. The LdapUserService uses the Typesafe configuration library.
*
* <p>
* The LDAP server configuration is used and should be passed in through the constructor:
*
* <pre>
* ldapServer = "ldaps://..."
* ldapSearchBase = "..."
* ldapPassword = "..."
* ldapBindDn = "..."
* ldapFilterAttribute = "..."
* </pre>
*
* <p>
* User attributes (e.g. name, email, etc.) pulled from LDAP needs to be specified in the
* configuration object to match the LDAP search controls:
*
* <pre>
* userAttributes = "firstName, lastName, email, phoneNumber, ..."
* </pre>
*/
public class LdapUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(LdapUserService.class);
| // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/main/java/edu/jhuapl/dorset/ldapuserservice/LdapUserService.java
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.ldapuserservice;
/**
* LdapUserService userservice
*
* LdapUserService is a UserService that pulls users' information from a LDAP server. The
* configuration information for the LDAP server, as well as the LDAP search controls, are stored in
* a configuration object. The LdapUserService uses the Typesafe configuration library.
*
* <p>
* The LDAP server configuration is used and should be passed in through the constructor:
*
* <pre>
* ldapServer = "ldaps://..."
* ldapSearchBase = "..."
* ldapPassword = "..."
* ldapBindDn = "..."
* ldapFilterAttribute = "..."
* </pre>
*
* <p>
* User attributes (e.g. name, email, etc.) pulled from LDAP needs to be specified in the
* configuration object to match the LDAP search controls:
*
* <pre>
* userAttributes = "firstName, lastName, email, phoneNumber, ..."
* </pre>
*/
public class LdapUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(LdapUserService.class);
| private Map<String, User> users; |
DorsetProject/dorset-framework | components/user-service/src/main/java/edu/jhuapl/dorset/ldapuserservice/LdapUserService.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService; | } catch (NamingException ex) {
throw new NamingException("Context could not be created. " + ex);
}
this.setContext(this.ctx);
}
/**
*
* LdapUserService
*
* @param context Context object that is instantiated with LDAP server information
* @param userAttributes String array containing User attributes that is used to generate LDAP
* search controls
*/
public LdapUserService(DirContext context, String[] userAttributes) {
this.ctx = context;
this.ldapServer = null;
this.ldapSearchBase = null;
this.ldapPassword = null;
this.ldapBindDn = null;
this.ldapFilterAttribute = null;
this.userAttributes = userAttributes;
this.users = new HashMap<String, User>();
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/main/java/edu/jhuapl/dorset/ldapuserservice/LdapUserService.java
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.typesafe.config.Config;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
} catch (NamingException ex) {
throw new NamingException("Context could not be created. " + ex);
}
this.setContext(this.ctx);
}
/**
*
* LdapUserService
*
* @param context Context object that is instantiated with LDAP server information
* @param userAttributes String array containing User attributes that is used to generate LDAP
* search controls
*/
public LdapUserService(DirContext context, String[] userAttributes) {
this.ctx = context;
this.ldapServer = null;
this.ldapSearchBase = null;
this.ldapPassword = null;
this.ldapBindDn = null;
this.ldapFilterAttribute = null;
this.userAttributes = userAttributes;
this.users = new HashMap<String, User>();
}
@Override | public String create(User user) throws UserException { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfigEntry.java | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
| import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class RouterAgentConfigEntry {
private Agent agent; | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfigEntry.java
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class RouterAgentConfigEntry {
private Agent agent; | private MultiValuedMap params; |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/ResponseTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.Response.Type; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
public class ResponseTest {
@Test
public void testFromValue() { | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// Path: core/src/test/java/edu/jhuapl/dorset/ResponseTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.Response.Type;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
public class ResponseTest {
@Test
public void testFromValue() { | assertEquals(Type.TEXT, Type.fromValue("text")); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/agents/DescriptionTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Description.java
// public class Description {
// private String name;
// private String summary;
// private String[] examples;
//
// /**
// * For java bean use only
// */
// public Description() {}
//
// /**
// * Create an agent description
// *
// * @param name Name of the agent
// * @param summary A user-facing description of the agent's capabilities
// * @param example An example question or command
// */
// public Description(String name, String summary, String example) {
// this(name, summary, new String[]{example});
// }
//
// /**
// * Create an agent description
// *
// * @param name Name of the agent
// * @param summary A user-facing description of the agent's capabilities
// * @param examples Array of example questions or commands
// */
// public Description(String name, String summary, String[] examples) {
// this.setName(name);
// this.setSummary(summary);
// this.setExamples(examples);
// }
//
// /**
// * Copy a description
// *
// * @param description agent description
// */
// public Description(Description description) {
// this(description.getName(), description.getSummary(), description.getExamples());
// }
//
// /**
// * Get the summary
// *
// * @return the summary
// */
// public String getSummary() {
// return summary;
// }
//
// /**
// * Set the summary
// *
// * @param summary A description of the agent's capabilities
// */
// public void setSummary(String summary) {
// this.summary = summary;
// }
//
// /**
// * Get the example requests for the agent
// *
// * @return examples of using the agent
// */
// public String[] getExamples() {
// return examples.clone();
// }
//
// /**
// * Set several examples of requests for the agent
// *
// * @param examples Array of example requests that the agent can handle
// */
// public void setExamples(String[] examples) {
// this.examples = Arrays.copyOf(examples, examples.length);
// }
//
// /**
// * Set a single example of a request for the agent
// *
// * @param example A single example request that the agent can handle
// */
// public void setExample(String example) {
// this.examples = new String[1];
// this.examples[0] = example;
// }
//
// /**
// * Get the name of the agent
// *
// * @return name of the agent
// */
// public String getName() {
// return name;
// }
//
// /**
// * Set the name of the agent
// *
// * @param name The name of the agent
// */
// public void setName(String name) {
// this.name = name.toLowerCase();
// }
//
// /**
// * Get a default description
// *
// * @param clazz The class of the agent
// * @return default description
// */
// public static Description getUninitializedDescription(Class<?> clazz) {
// String name = clazz.getCanonicalName();
// return new Description(name, "Summary is not set.", "Example is not set.");
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.agents.Description; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
public class DescriptionTest {
@Test
public void testSetName() { | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Description.java
// public class Description {
// private String name;
// private String summary;
// private String[] examples;
//
// /**
// * For java bean use only
// */
// public Description() {}
//
// /**
// * Create an agent description
// *
// * @param name Name of the agent
// * @param summary A user-facing description of the agent's capabilities
// * @param example An example question or command
// */
// public Description(String name, String summary, String example) {
// this(name, summary, new String[]{example});
// }
//
// /**
// * Create an agent description
// *
// * @param name Name of the agent
// * @param summary A user-facing description of the agent's capabilities
// * @param examples Array of example questions or commands
// */
// public Description(String name, String summary, String[] examples) {
// this.setName(name);
// this.setSummary(summary);
// this.setExamples(examples);
// }
//
// /**
// * Copy a description
// *
// * @param description agent description
// */
// public Description(Description description) {
// this(description.getName(), description.getSummary(), description.getExamples());
// }
//
// /**
// * Get the summary
// *
// * @return the summary
// */
// public String getSummary() {
// return summary;
// }
//
// /**
// * Set the summary
// *
// * @param summary A description of the agent's capabilities
// */
// public void setSummary(String summary) {
// this.summary = summary;
// }
//
// /**
// * Get the example requests for the agent
// *
// * @return examples of using the agent
// */
// public String[] getExamples() {
// return examples.clone();
// }
//
// /**
// * Set several examples of requests for the agent
// *
// * @param examples Array of example requests that the agent can handle
// */
// public void setExamples(String[] examples) {
// this.examples = Arrays.copyOf(examples, examples.length);
// }
//
// /**
// * Set a single example of a request for the agent
// *
// * @param example A single example request that the agent can handle
// */
// public void setExample(String example) {
// this.examples = new String[1];
// this.examples[0] = example;
// }
//
// /**
// * Get the name of the agent
// *
// * @return name of the agent
// */
// public String getName() {
// return name;
// }
//
// /**
// * Set the name of the agent
// *
// * @param name The name of the agent
// */
// public void setName(String name) {
// this.name = name.toLowerCase();
// }
//
// /**
// * Get a default description
// *
// * @param clazz The class of the agent
// * @return default description
// */
// public static Description getUninitializedDescription(Class<?> clazz) {
// String name = clazz.getCanonicalName();
// return new Description(name, "Summary is not set.", "Example is not set.");
// }
// }
// Path: core/src/test/java/edu/jhuapl/dorset/agents/DescriptionTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.agents.Description;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
public class DescriptionTest {
@Test
public void testSetName() { | Description d = new Description("Agent007", "test", "test"); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/SingleAgentRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Routes all requests to a single agent
*/
public class SingleAgentRouter implements Router {
private Agent agent;
/**
* Create the router
*
* @param agent the agent to route all requests to
*/
public SingleAgentRouter(Agent agent) {
this.agent = agent;
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/SingleAgentRouter.java
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Routes all requests to a single agent
*/
public class SingleAgentRouter implements Router {
private Agent agent;
/**
* Create the router
*
* @param agent the agent to route all requests to
*/
public SingleAgentRouter(Agent agent) {
this.agent = agent;
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | agents/web-api/src/main/java/edu/jhuapl/dorset/agents/TwitterAgent.java | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
| import edu.jhuapl.dorset.ResponseStatus;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.typesafe.config.Config; | apiKey = config.getString(API_KEY);
apiSecret = config.getString(API_SECRET);
accessToken = config.getString(ACCESS_TOKEN);
accessTokenSecret = config.getString(ACCESS_TOKEN_SECRET);
service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret)
.build(TwitterApi.instance());
oauthToken = new OAuth1AccessToken(accessToken, accessTokenSecret);
}
/**
* Create a Twitter Agent
*
* @param service The OAuth service
* @param oauth The OAuth token
*/
public TwitterAgent(OAuth10aService service, OAuth1AccessToken oauth) {
this.service = service;
this.oauthToken = oauth;
}
/**
* Process request
*
* @param agentRequest The user's request
* @return AgentResponse
*/
public AgentResponse process(AgentRequest agentRequest) {
try {
verfiyAccountCredentials();
} catch (TwitterException e) { | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
// Path: agents/web-api/src/main/java/edu/jhuapl/dorset/agents/TwitterAgent.java
import edu.jhuapl.dorset.ResponseStatus;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.scribejava.apis.TwitterApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.typesafe.config.Config;
apiKey = config.getString(API_KEY);
apiSecret = config.getString(API_SECRET);
accessToken = config.getString(ACCESS_TOKEN);
accessTokenSecret = config.getString(ACCESS_TOKEN_SECRET);
service = new ServiceBuilder().apiKey(apiKey).apiSecret(apiSecret)
.build(TwitterApi.instance());
oauthToken = new OAuth1AccessToken(accessToken, accessTokenSecret);
}
/**
* Create a Twitter Agent
*
* @param service The OAuth service
* @param oauth The OAuth token
*/
public TwitterAgent(OAuth10aService service, OAuth1AccessToken oauth) {
this.service = service;
this.oauthToken = oauth;
}
/**
* Process request
*
* @param agentRequest The user's request
* @return AgentResponse
*/
public AgentResponse process(AgentRequest agentRequest) {
try {
verfiyAccountCredentials();
} catch (TwitterException e) { | return new AgentResponse(new ResponseStatus(ResponseStatus.Code.AGENT_INTERNAL_ERROR, "Failed to authenticate with Twitter")); |
DorsetProject/dorset-framework | components/user-service/src/test/java/edu/jhuapl/dorset/ldapuserservice/LdapUserServiceTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.junit.Test;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.ldapuserservice;
public class LdapUserServiceTest {
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
private String[] mockUserAttributes() {
String [] userAttributes = new String[] {"first_name", "last_name", "email"};
return userAttributes;
}
@Test | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
// Path: components/user-service/src/test/java/edu/jhuapl/dorset/ldapuserservice/LdapUserServiceTest.java
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.junit.Test;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.ldapuserservice;
public class LdapUserServiceTest {
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
private String[] mockUserAttributes() {
String [] userAttributes = new String[] {"first_name", "last_name", "email"};
return userAttributes;
}
@Test | public void testGetUserSuccess() throws NamingException, UserException { |
DorsetProject/dorset-framework | api/src/main/java/edu/jhuapl/dorset/rest/Error.java | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
| import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.ResponseStatus; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
@XmlRootElement
public class Error {
private final int code;
private final String message;
/**
* Create an error
*
* @param code the error code
* @param message the error message
*/
public Error(int code, String message) {
this.code = code;
this.message = message;
}
/**
* Create an error from a response status
*
* @param status the response status with an error code
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public class ResponseStatus {
// private final Code code;
// private final String message;
//
// /**
// * Create a response status based on a code
// * <p>
// * This uses the default message for the code.
// *
// * @param code ResponseStatus.Code enum value
// */
// public ResponseStatus(Code code) {
// this.code = code;
// message = messageMap.get(code);
// }
//
// /**
// * Create a response status
// *
// * @param code ResponseStatus.Code enum value
// * @param message custom status message
// */
// public ResponseStatus(Code code, String message) {
// this.code = code;
// this.message = message;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return code == Code.SUCCESS;
// }
//
// /**
// * Get the status code
// *
// * @return ResponseStatus.Code enum value
// */
// public Code getCode() {
// return code;
// }
//
// /**
// * Get the status message
// *
// * @return the status message
// */
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof ResponseStatus && ((ResponseStatus) obj).getCode() == this.getCode()
// && ((ResponseStatus) obj).getMessage().equals(this.getMessage())) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public int hashCode() {
// // codes are 3 digits
// return 1000 * this.message.hashCode() + this.code.getValue();
// }
//
// /**
// * Factory method to create a default success status
// *
// * @return a success status
// */
// public static ResponseStatus createSuccess() {
// return new ResponseStatus(Code.SUCCESS);
// }
//
// /**
// * Response code enumeration
// */
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
//
// // default messages
// private static final Map<Code, String> messageMap = new HashMap<Code, String>();
// static {
// messageMap.put(Code.SUCCESS, "Success");
// messageMap.put(Code.INTERNAL_ERROR, "Something failed with this request.");
// messageMap.put(Code.NO_AVAILABLE_AGENT, "No agent was available to handle this request.");
// messageMap.put(Code.NO_RESPONSE_FROM_AGENT, "The agent did not provide a response.");
// messageMap.put(Code.INVALID_RESPONSE_FROM_AGENT, "An error occurred getting response from agent.");
// messageMap.put(Code.AGENT_DID_NOT_UNDERSTAND_REQUEST, "The agent did not understand the request.");
// messageMap.put(Code.AGENT_DID_NOT_KNOW_ANSWER, "The agent did not know the answer.");
// messageMap.put(Code.AGENT_CANNOT_COMPLETE_ACTION, "The agent could not complete the requested action.");
// messageMap.put(Code.AGENT_INTERNAL_ERROR, "Something failed when handling this request.");
// }
// }
// Path: api/src/main/java/edu/jhuapl/dorset/rest/Error.java
import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.ResponseStatus;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
@XmlRootElement
public class Error {
private final int code;
private final String message;
/**
* Create an error
*
* @param code the error code
* @param message the error message
*/
public Error(int code, String message) {
this.code = code;
this.message = message;
}
/**
* Create an error from a response status
*
* @param status the response status with an error code
*/ | public Error(ResponseStatus status) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/ChainedRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import java.util.Arrays;
import java.util.HashSet;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Chain routers together
* <p>
* The routing precedes in the order that the routers are passed to the
* constructor and stops with the first router to return agents.
*/
public class ChainedRouter implements Router {
private Router[] routers;
/**
* Create a chain router
*
* @param routers the routers to use
*/
public ChainedRouter(Router... routers) {
this.routers = Arrays.copyOf(routers, routers.length);
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/ChainedRouter.java
import java.util.Arrays;
import java.util.HashSet;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Chain routers together
* <p>
* The routing precedes in the order that the routers are passed to the
* constructor and stops with the first router to return agents.
*/
public class ChainedRouter implements Router {
private Router[] routers;
/**
* Create a chain router
*
* @param routers the routers to use
*/
public ChainedRouter(Router... routers) {
this.routers = Arrays.copyOf(routers, routers.length);
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/ChainedRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import java.util.Arrays;
import java.util.HashSet;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Chain routers together
* <p>
* The routing precedes in the order that the routers are passed to the
* constructor and stops with the first router to return agents.
*/
public class ChainedRouter implements Router {
private Router[] routers;
/**
* Create a chain router
*
* @param routers the routers to use
*/
public ChainedRouter(Router... routers) {
this.routers = Arrays.copyOf(routers, routers.length);
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/ChainedRouter.java
import java.util.Arrays;
import java.util.HashSet;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Chain routers together
* <p>
* The routing precedes in the order that the routers are passed to the
* constructor and stops with the first router to return agents.
*/
public class ChainedRouter implements Router {
private Router[] routers;
/**
* Create a chain router
*
* @param routers the routers to use
*/
public ChainedRouter(Router... routers) {
this.routers = Arrays.copyOf(routers, routers.length);
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfig.java | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
| import java.util.ArrayList;
import java.util.Iterator;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Configuration for a set of routers
*/
public class RouterAgentConfig implements Iterable<RouterAgentConfigEntry> {
private ArrayList<RouterAgentConfigEntry> list = new ArrayList<RouterAgentConfigEntry>();
/**
* Add an agent to the configuration
*
* @param agent the agent to add
* @param params the parameters for the router for that agent
* @return this
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfig.java
import java.util.ArrayList;
import java.util.Iterator;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Configuration for a set of routers
*/
public class RouterAgentConfig implements Iterable<RouterAgentConfigEntry> {
private ArrayList<RouterAgentConfigEntry> list = new ArrayList<RouterAgentConfigEntry>();
/**
* Add an agent to the configuration
*
* @param agent the agent to add
* @param params the parameters for the router for that agent
* @return this
*/ | public RouterAgentConfig add(Agent agent, MultiValuedMap params) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfig.java | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
| import java.util.ArrayList;
import java.util.Iterator;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Configuration for a set of routers
*/
public class RouterAgentConfig implements Iterable<RouterAgentConfigEntry> {
private ArrayList<RouterAgentConfigEntry> list = new ArrayList<RouterAgentConfigEntry>();
/**
* Add an agent to the configuration
*
* @param agent the agent to add
* @param params the parameters for the router for that agent
* @return this
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/config/MultiValuedMap.java
// public class MultiValuedMap {
// private HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
//
// /**
// * Add a string in the map replacing any strings at that key
// *
// * @param key the key
// * @param value the value
// */
// public void putString(String key, String value) {
// map.put(key, new HashSet<String>(Arrays.asList(value)));
// }
//
// /**
// * Add the array of strings to the map replacing any strings at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void putStrings(String key, String[] values) {
// if (values.length > 0) {
// map.put(key, new HashSet<String>(Arrays.asList(values)));
// }
// }
//
// /**
// * Add the string to those at that key
// *
// * @param key the key
// * @param value the value
// */
// public void addString(String key, String value) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).add(value);
// }
//
// /**
// * Add strings to those at that key
// *
// * @param key the key
// * @param values array of values
// */
// public void addStrings(String key, String[] values) {
// if (!containsKey(key)) {
// map.put(key, new HashSet<String>());
// }
// map.get(key).addAll(Arrays.asList(values));
// }
//
// /**
// * Get the string at the specified key
// *
// * @param key the key
// * @return the first value at the key or null if none
// */
// public String getString(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.iterator().next();
// }
//
// /**
// * Get the strings at the specified key
// *
// * @param key the key
// * @return array of values or null if none
// */
// public String[] getStrings(String key) {
// Set<String> values = map.get(key);
// if (values == null) {
// return null;
// }
// return values.toArray(new String[values.size()]);
// }
//
// /**
// * Does the map contain this key?
// *
// * @param key the key
// * @return true if it does
// */
// public boolean containsKey(String key) {
// return map.containsKey(key);
// }
//
// /**
// * How many keys does the map contain?
// *
// * @return the number of keys
// */
// public int size() {
// return map.size();
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/RouterAgentConfig.java
import java.util.ArrayList;
import java.util.Iterator;
import edu.jhuapl.dorset.agents.Agent;
import edu.jhuapl.dorset.config.MultiValuedMap;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* Configuration for a set of routers
*/
public class RouterAgentConfig implements Iterable<RouterAgentConfigEntry> {
private ArrayList<RouterAgentConfigEntry> list = new ArrayList<RouterAgentConfigEntry>();
/**
* Add an agent to the configuration
*
* @param agent the agent to add
* @param params the parameters for the router for that agent
* @return this
*/ | public RouterAgentConfig add(Agent agent, MultiValuedMap params) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/GenericKeywordNodeTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class GenericKeywordNodeTest {
private GenericKeywordNode node; | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/GenericKeywordNodeTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class GenericKeywordNodeTest {
private GenericKeywordNode node; | private Agent red = mock(Agent.class); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/GenericKeywordNodeTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class GenericKeywordNodeTest {
private GenericKeywordNode node;
private Agent red = mock(Agent.class);
private Agent green = mock(Agent.class);
private Agent blue = mock(Agent.class);
@Before
public void setupNodes() {
node = new GenericKeywordNode();
node.addChild("red", new LeafNode(red));
node.addChild("green", new LeafNode(green));
node.addChild("blue", new LeafNode(blue));
}
@Test
public void testSingleKeywordPerNode() { | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/GenericKeywordNodeTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.junit.Before;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class GenericKeywordNodeTest {
private GenericKeywordNode node;
private Agent red = mock(Agent.class);
private Agent green = mock(Agent.class);
private Agent blue = mock(Agent.class);
@Before
public void setupNodes() {
node = new GenericKeywordNode();
node.addChild("red", new LeafNode(red));
node.addChild("green", new LeafNode(green));
node.addChild("blue", new LeafNode(blue));
}
@Test
public void testSingleKeywordPerNode() { | Request request1 = new Request("Red roses"); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/filters/WakeupRequestFilter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
| import edu.jhuapl.dorset.Request; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
/**
* Wakeup Request Filter
*
* This filter removes a wake-up word from the Request text.
* A wake-up word is commonly used for speech to text systems that are always listening.
*/
public class WakeupRequestFilter implements RequestFilter {
private String wakeupWord;
public WakeupRequestFilter(String wakeupWord) {
this.wakeupWord = wakeupWord;
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
// Path: core/src/main/java/edu/jhuapl/dorset/filters/WakeupRequestFilter.java
import edu.jhuapl.dorset.Request;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
/**
* Wakeup Request Filter
*
* This filter removes a wake-up word from the Request text.
* A wake-up word is commonly used for speech to text systems that are always listening.
*/
public class WakeupRequestFilter implements RequestFilter {
private String wakeupWord;
public WakeupRequestFilter(String wakeupWord) {
this.wakeupWord = wakeupWord;
}
@Override | public Request filter(Request request) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/filters/WakeupRequestFilterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import edu.jhuapl.dorset.Request; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
public class WakeupRequestFilterTest {
@Test
public void wakeupFilter() {
String strRequest = "Dorset 2 + 2";
String strFilteredRequest = "2 + 2";
RequestFilter requestFilter = new WakeupRequestFilter("Dorset");
| // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
// Path: core/src/test/java/edu/jhuapl/dorset/filters/WakeupRequestFilterTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
public class WakeupRequestFilterTest {
@Test
public void wakeupFilter() {
String strRequest = "Dorset 2 + 2";
String strFilteredRequest = "2 + 2";
RequestFilter requestFilter = new WakeupRequestFilter("Dorset");
| Request request = new Request(strRequest); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/BinaryKeywordNodeTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class BinaryKeywordNodeTest {
@Test
public void testBothSides() { | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/BinaryKeywordNodeTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class BinaryKeywordNodeTest {
@Test
public void testBothSides() { | Request request1 = new Request("What is the weather like?"); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/tree/BinaryKeywordNodeTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class BinaryKeywordNodeTest {
@Test
public void testBothSides() {
Request request1 = new Request("What is the weather like?");
Request request2 = new Request("Where is the door?"); | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/tree/BinaryKeywordNodeTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
public class BinaryKeywordNodeTest {
@Test
public void testBothSides() {
Request request1 = new Request("What is the weather like?");
Request request2 = new Request("Where is the door?"); | Agent a1 = mock(Agent.class); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/RegexRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* This router uses regular expressions to direct requests.
* <p>
* Each agent can have one or more regular expressions associated with it.
* The regular expressions are treated as case insensitive.
*/
public class RegexRouter implements Router {
public static final String REGEX = "regex";
| // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/RegexRouter.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* This router uses regular expressions to direct requests.
* <p>
* Each agent can have one or more regular expressions associated with it.
* The regular expressions are treated as case insensitive.
*/
public class RegexRouter implements Router {
public static final String REGEX = "regex";
| private HashMap<Pattern, Agent> agentMap; |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/RegexRouter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* This router uses regular expressions to direct requests.
* <p>
* Each agent can have one or more regular expressions associated with it.
* The regular expressions are treated as case insensitive.
*/
public class RegexRouter implements Router {
public static final String REGEX = "regex";
private HashMap<Pattern, Agent> agentMap;
private HashSet<Agent> agents;
/**
* Create the router
*
* @param agentsConfig agents and routing configuration for those agents
*/
public RegexRouter(RouterAgentConfig agentsConfig) {
agentMap = new HashMap<Pattern, Agent>();
agents = new HashSet<Agent>();
for (RouterAgentConfigEntry entry : agentsConfig) {
String[] regexes = entry.getParams().getStrings(REGEX);
if (regexes == null) {
continue;
}
agents.add(entry.getAgent());
for (String regex : regexes) {
agentMap.put(Pattern.compile(regex, Pattern.CASE_INSENSITIVE), entry.getAgent());
}
}
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/RegexRouter.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
/**
* This router uses regular expressions to direct requests.
* <p>
* Each agent can have one or more regular expressions associated with it.
* The regular expressions are treated as case insensitive.
*/
public class RegexRouter implements Router {
public static final String REGEX = "regex";
private HashMap<Pattern, Agent> agentMap;
private HashSet<Agent> agents;
/**
* Create the router
*
* @param agentsConfig agents and routing configuration for those agents
*/
public RegexRouter(RouterAgentConfig agentsConfig) {
agentMap = new HashMap<Pattern, Agent>();
agents = new HashSet<Agent>();
for (RouterAgentConfigEntry entry : agentsConfig) {
String[] regexes = entry.getParams().getStrings(REGEX);
if (regexes == null) {
continue;
}
agents.add(entry.getAgent());
for (String regex : regexes) {
agentMap.put(Pattern.compile(regex, Pattern.CASE_INSENSITIVE), entry.getAgent());
}
}
}
@Override | public Agent[] route(Request request) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/tree/LeafNode.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Terminal node in a tree. It returns an agent.
*/
public class LeafNode implements Node {
private Agent agent;
/**
* Create a leaf node
*
* @param agent Agent returned from routing a request
*/
public LeafNode(Agent agent) {
this.agent = agent;
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/tree/LeafNode.java
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Terminal node in a tree. It returns an agent.
*/
public class LeafNode implements Node {
private Agent agent;
/**
* Create a leaf node
*
* @param agent Agent returned from routing a request
*/
public LeafNode(Agent agent) {
this.agent = agent;
}
@Override | public Node selectChild(Request request) { |
DorsetProject/dorset-framework | api/src/main/java/edu/jhuapl/dorset/rest/WebResponse.java | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
| import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response to a request
* <p>
* This class defines the json object returned by the web services
*/
@XmlRootElement
public class WebResponse {
protected final String type;
// see Response.Type for the supported type strings
protected final String text;
/**
* Create a web response
*
* @param resp the response from the Dorset application
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
// Path: api/src/main/java/edu/jhuapl/dorset/rest/WebResponse.java
import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response to a request
* <p>
* This class defines the json object returned by the web services
*/
@XmlRootElement
public class WebResponse {
protected final String type;
// see Response.Type for the supported type strings
protected final String text;
/**
* Create a web response
*
* @param resp the response from the Dorset application
*/ | public WebResponse(Response resp) { |
DorsetProject/dorset-framework | api/src/main/java/edu/jhuapl/dorset/rest/WebResponseWithPayload.java | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
| import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response with payload data
* <p>
* Extends the WebResponse with the optional payload information
*/
@XmlRootElement
public class WebResponseWithPayload extends WebResponse {
private final String payload;
/**
* Create a web response with a payload
*
* @param resp the response from the Dorset application
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/Response.java
// public class Response {
// private final Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create a response
// *
// * @param text the text of the response
// */
// public Response(String text) {
// this.type = Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response with a payload
// *
// * @param type the type of the response
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public Response(Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create a response
// *
// * @param response response from an agent
// */
// public Response(AgentResponse response) {
// this.type = response.getType();
// this.text = response.getText();
// this.payload = response.getPayload();
// this.status = response.getStatus();
// }
//
// /**
// * Create a response
// *
// * @param text the text of the response
// * @param status the response status
// */
// public Response(String text, ResponseStatus status) {
// if (status.isSuccess()) {
// this.type = Type.TEXT;
// } else {
// this.type = Type.ERROR;
// }
// this.text = text;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Create a response
// *
// * @param status the response status (an error)
// */
// public Response(ResponseStatus status) {
// this.type = Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return the text of the response or null if error
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the response status
// *
// * @return the status
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response to the request?
// *
// * @return true for success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a simple text response?
// *
// * @return true if text response
// */
// public boolean isTextResponse() {
// return type == Type.TEXT;
// }
//
// /**
// * Does this response have a payload?
// *
// * @return true if there is a payload
// */
// public boolean hasPayload() {
// return Type.usesPayload(type);
// }
//
// /**
// * Enumeration for response types
// * <p>
// * The response types are
// * <ul>
// * <li>ERROR - an error occurred
// * <li>TEXT - a simple text response
// * <li>IMAGE_EMBED - base64 encoded image
// * <li>IMAGE_URL - URL to an image
// * <li>JSON - JSON data
// * </ul>
// */
// public enum Type {
// ERROR("error"),
// TEXT("text"),
// IMAGE_EMBED("image_embed"),
// IMAGE_URL("image_url"),
// JSON("json");
//
// private final String type;
// private Type(String type) {
// this.type = type;
// }
//
// /**
// * Get the value of the type
// *
// * @return the value
// */
// public String getValue() {
// return type;
// }
//
// /**
// * Get a Type enum member from a string
// *
// * @param value the type as a string
// * @return a Type enum member or null if no match
// */
// public static Type fromValue(String value) {
// for (Type type : Type.values()) {
// if (type.getValue().equals(value)) {
// return type;
// }
// }
// return null;
// }
//
// /**
// * Does this response type use the payload field?
// *
// * @param type the response type
// * @return true if it uses the payload field
// */
// public static boolean usesPayload(Type type) {
// if (type == ERROR || type == TEXT) {
// return false;
// }
// return true;
// }
// }
// }
// Path: api/src/main/java/edu/jhuapl/dorset/rest/WebResponseWithPayload.java
import javax.xml.bind.annotation.XmlRootElement;
import edu.jhuapl.dorset.Response;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.rest;
/**
* Web response with payload data
* <p>
* Extends the WebResponse with the optional payload information
*/
@XmlRootElement
public class WebResponseWithPayload extends WebResponse {
private final String payload;
/**
* Create a web response with a payload
*
* @param resp the response from the Dorset application
*/ | public WebResponseWithPayload(Response resp) { |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/Response.java | // Path: core/src/main/java/edu/jhuapl/dorset/agents/AgentResponse.java
// public class AgentResponse {
// private final Response.Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create an agent response
// *
// * @param text the text of the response
// */
// public AgentResponse(String text) {
// this.type = Response.Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create an agent response with payload
// *
// * @param type the response type
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public AgentResponse(Response.Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create an agent response for an error
// *
// * @param code the status code
// */
// public AgentResponse(ResponseStatus.Code code) {
// this.type = Response.Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = new ResponseStatus(code);
// }
//
// /**
// * Create an agent response for an error with custom message
// *
// * @param status the status of the response
// */
// public AgentResponse(ResponseStatus status) {
// this.type = Response.Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Response.Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return text of the response
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the status
// *
// * @return the status code
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a valid response?
// *
// * @return true if valid
// */
// public boolean isValid() {
// if (type == null || status == null) {
// return false;
// }
// if (Response.Type.usesPayload(type) && payload == null) {
// return false;
// }
// return !(isSuccess() && text == null);
// }
// }
| import edu.jhuapl.dorset.agents.AgentResponse; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
/**
* Dorset Response
* <p>
* Represents the response to a request to the application.
* The type field determines what fields are used.
* The text field can be null if an error occurred.
*/
public class Response {
private final Type type;
private final String text;
private final String payload;
private final ResponseStatus status;
/**
* Create a response
*
* @param text the text of the response
*/
public Response(String text) {
this.type = Type.TEXT;
this.text = text;
this.payload = null;
this.status = ResponseStatus.createSuccess();
}
/**
* Create a response with a payload
*
* @param type the type of the response
* @param text the text of the response
* @param payload the payload of the response
*/
public Response(Type type, String text, String payload) {
this.type = type;
this.text = text;
this.payload = payload;
this.status = ResponseStatus.createSuccess();
}
/**
* Create a response
*
* @param response response from an agent
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/agents/AgentResponse.java
// public class AgentResponse {
// private final Response.Type type;
// private final String text;
// private final String payload;
// private final ResponseStatus status;
//
// /**
// * Create an agent response
// *
// * @param text the text of the response
// */
// public AgentResponse(String text) {
// this.type = Response.Type.TEXT;
// this.text = text;
// this.payload = null;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create an agent response with payload
// *
// * @param type the response type
// * @param text the text of the response
// * @param payload the payload of the response
// */
// public AgentResponse(Response.Type type, String text, String payload) {
// this.type = type;
// this.text = text;
// this.payload = payload;
// this.status = ResponseStatus.createSuccess();
// }
//
// /**
// * Create an agent response for an error
// *
// * @param code the status code
// */
// public AgentResponse(ResponseStatus.Code code) {
// this.type = Response.Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = new ResponseStatus(code);
// }
//
// /**
// * Create an agent response for an error with custom message
// *
// * @param status the status of the response
// */
// public AgentResponse(ResponseStatus status) {
// this.type = Response.Type.ERROR;
// this.text = null;
// this.payload = null;
// this.status = status;
// }
//
// /**
// * Get the response type
// *
// * @return the response type
// */
// public Response.Type getType() {
// return type;
// }
//
// /**
// * Get the text of the response
// *
// * @return text of the response
// */
// public String getText() {
// return text;
// }
//
// /**
// * Get the payload of the response
// * <p>
// * The payload data varies according to the response type
// *
// * @return payload string or null if no payload
// */
// public String getPayload() {
// return payload;
// }
//
// /**
// * Get the status
// *
// * @return the status code
// */
// public ResponseStatus getStatus() {
// return status;
// }
//
// /**
// * Is this a successful response?
// *
// * @return true if success
// */
// public boolean isSuccess() {
// return status.isSuccess();
// }
//
// /**
// * Is this a valid response?
// *
// * @return true if valid
// */
// public boolean isValid() {
// if (type == null || status == null) {
// return false;
// }
// if (Response.Type.usesPayload(type) && payload == null) {
// return false;
// }
// return !(isSuccess() && text == null);
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/Response.java
import edu.jhuapl.dorset.agents.AgentResponse;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
/**
* Dorset Response
* <p>
* Represents the response to a request to the application.
* The type field determines what fields are used.
* The text field can be null if an error occurred.
*/
public class Response {
private final Type type;
private final String text;
private final String payload;
private final ResponseStatus status;
/**
* Create a response
*
* @param text the text of the response
*/
public Response(String text) {
this.type = Type.TEXT;
this.text = text;
this.payload = null;
this.status = ResponseStatus.createSuccess();
}
/**
* Create a response with a payload
*
* @param type the type of the response
* @param text the text of the response
* @param payload the payload of the response
*/
public Response(Type type, String text, String payload) {
this.type = type;
this.text = text;
this.payload = payload;
this.status = ResponseStatus.createSuccess();
}
/**
* Create a response
*
* @param response response from an agent
*/ | public Response(AgentResponse response) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/ChainedRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class ChainedRouterTest {
@Test
public void testRouteWithFirstEmptyResponse() {
Router r1 = mock(Router.class);
Router r2 = mock(Router.class); | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/ChainedRouterTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class ChainedRouterTest {
@Test
public void testRouteWithFirstEmptyResponse() {
Router r1 = mock(Router.class);
Router r2 = mock(Router.class); | Agent a = mock(Agent.class); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/ChainedRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class ChainedRouterTest {
@Test
public void testRouteWithFirstEmptyResponse() {
Router r1 = mock(Router.class);
Router r2 = mock(Router.class);
Agent a = mock(Agent.class);
Agent[] resp = {a}; | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/ChainedRouterTest.java
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class ChainedRouterTest {
@Test
public void testRouteWithFirstEmptyResponse() {
Router r1 = mock(Router.class);
Router r2 = mock(Router.class);
Agent a = mock(Agent.class);
Agent[] resp = {a}; | Request request = mock(Request.class); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/filters/AliasRequestFilter.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
/**
* Replace words or phrases in a request with another string
*
* For example, when the string "jhu" is in the request, we may want to expand it
* to "Johns Hopkins University".
*/
public class AliasRequestFilter implements RequestFilter {
private Map<String, String> aliasMap;
private Map<Pattern, String> patternAliasMap;
/**
* Alias Request Filter
*
* Each map key will be replaced by its corresponding value.
* This value will act as an alias in the Request text.
*
* @param aliasMap Map of aliases
*/
public AliasRequestFilter(Map<String, String> aliasMap) {
this.aliasMap = aliasMap;
if (this.aliasMap != null) {
this.patternAliasMap = new HashMap<Pattern, String>();
for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {
String regex = "\\b" + entry.getKey() + "\\b";
this.patternAliasMap.put(Pattern.compile(regex, Pattern.CASE_INSENSITIVE), entry.getValue());
}
}
}
@Override | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
// Path: core/src/main/java/edu/jhuapl/dorset/filters/AliasRequestFilter.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import edu.jhuapl.dorset.Request;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.filters;
/**
* Replace words or phrases in a request with another string
*
* For example, when the string "jhu" is in the request, we may want to expand it
* to "Johns Hopkins University".
*/
public class AliasRequestFilter implements RequestFilter {
private Map<String, String> aliasMap;
private Map<Pattern, String> patternAliasMap;
/**
* Alias Request Filter
*
* Each map key will be replaced by its corresponding value.
* This value will act as an alias in the Request text.
*
* @param aliasMap Map of aliases
*/
public AliasRequestFilter(Map<String, String> aliasMap) {
this.aliasMap = aliasMap;
if (this.aliasMap != null) {
this.patternAliasMap = new HashMap<Pattern, String>();
for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {
String regex = "\\b" + entry.getKey() + "\\b";
this.patternAliasMap.put(Pattern.compile(regex, Pattern.CASE_INSENSITIVE), entry.getValue());
}
}
}
@Override | public Request filter(Request request) { |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/SingleAgentRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class SingleAgentRouterTest {
@Test
public void testRoute() { | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/SingleAgentRouterTest.java
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class SingleAgentRouterTest {
@Test
public void testRoute() { | Agent agent = mock(Agent.class); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/routing/SingleAgentRouterTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class SingleAgentRouterTest {
@Test
public void testRoute() {
Agent agent = mock(Agent.class);
Router router = new SingleAgentRouter(agent);
| // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/test/java/edu/jhuapl/dorset/routing/SingleAgentRouterTest.java
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing;
public class SingleAgentRouterTest {
@Test
public void testRoute() {
Agent agent = mock(Agent.class);
Router router = new SingleAgentRouter(agent);
| Agent agents[] = router.route(new Request("hello world")); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/agents/AgentRequest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
| import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.users.User; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
/**
* Request sent to an agent
* <p>
* This class is part of the public API for remote agent web services.
*/
public class AgentRequest {
private String text; | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/agents/AgentRequest.java
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.users.User;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
/**
* Request sent to an agent
* <p>
* This class is part of the public API for remote agent web services.
*/
public class AgentRequest {
private String text; | private User user; |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/agents/AgentRequest.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
| import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.users.User; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
/**
* Request sent to an agent
* <p>
* This class is part of the public API for remote agent web services.
*/
public class AgentRequest {
private String text;
private User user;
public AgentRequest() {}
/**
* Create an agent request
*
* @param request the request
*
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
// Path: core/src/main/java/edu/jhuapl/dorset/agents/AgentRequest.java
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.users.User;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.agents;
/**
* Request sent to an agent
* <p>
* This class is part of the public API for remote agent web services.
*/
public class AgentRequest {
private String text;
private User user;
public AgentRequest() {}
/**
* Create an agent request
*
* @param request the request
*
*/ | public AgentRequest(Request request) { |
DorsetProject/dorset-framework | components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService; | package edu.jhuapl.dorset.fileuserservice;
public class FileUserServiceTest {
protected String fileBaseName;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
public FileUserServiceTest() {
this.fileBaseName = "MockUserFile";
}
private String getTempFilePath() {
File tmpFolder = testFolder.getRoot();
return tmpFolder.getAbsolutePath();
}
private String createTempUserFile() throws FileNotFoundException, IOException {
String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
| // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
package edu.jhuapl.dorset.fileuserservice;
public class FileUserServiceTest {
protected String fileBaseName;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
public FileUserServiceTest() {
this.fileBaseName = "MockUserFile";
}
private String getTempFilePath() {
File tmpFolder = testFolder.getRoot();
return tmpFolder.getAbsolutePath();
}
private String createTempUserFile() throws FileNotFoundException, IOException {
String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
| public User mockUser() { |
DorsetProject/dorset-framework | components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService; | return tmpFolder.getAbsolutePath();
}
private String createTempUserFile() throws FileNotFoundException, IOException {
String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
@Test | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
return tmpFolder.getAbsolutePath();
}
private String createTempUserFile() throws FileNotFoundException, IOException {
String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
@Test | public void testCreateUser() throws UserException { |
DorsetProject/dorset-framework | components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService; | String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
@Test
public void testCreateUser() throws UserException {
String tempFilePath = getTempFilePath();
User new_user = mockUser();
| // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/test/java/edu/jhuapl/dorset/fileuserservice/FileUserServiceTest.java
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
String userName = "Mock-UserName";
String filePath = getTempFilePath();
File file = new File(filePath, fileBaseName + "-" + userName + ".properties");
OutputStream output = new FileOutputStream(file);
Properties prop = new Properties();
prop.setProperty("Dorset-firstName", "Mock-FirstName");
prop.setProperty("Dorset-lastName", "Mock-LastName");
prop.setProperty("Dorset-userName", userName);
prop.store(output, null);
return userName;
}
public User mockUser() {
User user = new User();
user.setFirstName("mock_FirstName");
user.setLastName("mock_LastName");
user.setUserName("mock_UserName");
user.setEmail("mock_Email");
user.setDob("mock_Dob");
user.setLocation("mock_Location");
return user;
}
@Test
public void testCreateUser() throws UserException {
String tempFilePath = getTempFilePath();
User new_user = mockUser();
| UserService user_service = new FileUserService(tempFilePath, fileBaseName); |
DorsetProject/dorset-framework | core/src/test/java/edu/jhuapl/dorset/ResponseStatusTest.java | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.ResponseStatus.Code; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
public class ResponseStatusTest {
@Test
public void testEquals() { | // Path: core/src/main/java/edu/jhuapl/dorset/ResponseStatus.java
// public enum Code {
// SUCCESS(0),
// INTERNAL_ERROR(100),
// NO_AVAILABLE_AGENT(101),
// NO_RESPONSE_FROM_AGENT(102),
// INVALID_RESPONSE_FROM_AGENT(103),
// AGENT_DID_NOT_UNDERSTAND_REQUEST(200),
// AGENT_DID_NOT_KNOW_ANSWER(201),
// AGENT_CANNOT_COMPLETE_ACTION(202),
// AGENT_INTERNAL_ERROR(203);
//
// private final int code;
// private Code(int code) {
// this.code = code;
// }
//
// /**
// * Get the value of the code
// *
// * @return the value
// */
// public int getValue() {
// return code;
// }
//
// /**
// * Get a Code enum member from an integer value
// *
// * @param value the integer value
// * @return Code enum member
// */
// public static Code fromValue(int value) {
// for (Code code : Code.values()) {
// if (code.getValue() == value) {
// return code;
// }
// }
// return null;
// }
// }
// Path: core/src/test/java/edu/jhuapl/dorset/ResponseStatusTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import edu.jhuapl.dorset.ResponseStatus.Code;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset;
public class ResponseStatusTest {
@Test
public void testEquals() { | ResponseStatus status1 = new ResponseStatus(Code.AGENT_INTERNAL_ERROR, "this is a test"); |
DorsetProject/dorset-framework | core/src/main/java/edu/jhuapl/dorset/routing/tree/Node.java | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
| import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent; | /*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Node for a tree router.
* <p>
* Parent nodes return child nodes based on a request.
* Leaf nodes return an array of agents to be returned by TreeRouter.
*/
public interface Node {
/**
* Get the child node that matches the request
*
* @param request Request object
* @return routing node
*/
public Node selectChild(Request request);
/**
* Get children of this node
*
* @return Node array
*/
public Node[] getChildren();
/**
* Is this node a leaf?
*
* @return boolean
*/
public boolean isLeaf();
/**
* Get the agents for this leaf node
*
* @return Agent array
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/Request.java
// public class Request {
// /** Maximum length of the identifier string ({@value #MAX_ID_LENGTH}) */
// public static final int MAX_ID_LENGTH = 36;
//
// private String text;
// private final String id;
// private final User user;
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// */
// public Request(String text) {
// this(text, null, "");
// }
//
// /**
// * Create a request
// * <p>
// * Automatically sets the identifier of the request
// *
// * @param text the text of the request
// * @param user the user of the request
// * */
// public Request(String text, User user) {
// this(text, user, "");
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, String id) {
// this(text, null, id);
// }
//
// /**
// * Create a request
// *
// * @param text the text of the request
// * @param user the user of the request
// * @param id the identifier of the request (cannot be longer then MAX_ID_LENGTH)
// * The identifier must be unique.
// */
// public Request(String text, User user, String id) {
// if (id.length() > MAX_ID_LENGTH) {
// throw new IllegalArgumentException(
// "Request id cannot be longer than " + String.valueOf(MAX_ID_LENGTH));
// }
//
// if (id.length() == 0) {
// this.id = UUID.randomUUID().toString();
// } else {
// this.id = id;
// }
//
// this.text = text;
// this.user = user;
// }
//
// /**
// * Get the text of the request
// *
// * @return the text of the request
// */
// public String getText() {
// return text;
// }
//
// /**
// * Set the text of the request
// *
// * @param text the text of the request
// */
// public void setText(String text) {
// this.text = text;
// }
//
// /**
// * Get the identifier of the request
// *
// * @return identifier
// */
// public String getId() {
// return id;
// }
//
// /**
// * Get the User of the request
// *
// * @return user
// */
// public User getUser() {
// return user;
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/agents/Agent.java
// public interface Agent {
//
// /**
// * Get the name of the agent
// *
// * @return name
// */
// public String getName();
//
// /**
// * Override the default name of the agent
// *
// * @param name New name for the agent
// */
// public void setName(String name);
//
// /**
// * Get the description of the agent for human consumption
// *
// * @return Description of the agent
// */
// public Description getDescription();
//
// /**
// * Override the default description
// *
// * @param description Description of the agent
// * @see Description
// */
// public void setDescription(Description description);
//
// /**
// * Process a request
// *
// * @param request Request object
// * @return response to the request
// */
// public AgentResponse process(AgentRequest request);
// }
// Path: core/src/main/java/edu/jhuapl/dorset/routing/tree/Node.java
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.agents.Agent;
/*
* Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.routing.tree;
/**
* Node for a tree router.
* <p>
* Parent nodes return child nodes based on a request.
* Leaf nodes return an array of agents to be returned by TreeRouter.
*/
public interface Node {
/**
* Get the child node that matches the request
*
* @param request Request object
* @return routing node
*/
public Node selectChild(Request request);
/**
* Get children of this node
*
* @return Node array
*/
public Node[] getChildren();
/**
* Is this node a leaf?
*
* @return boolean
*/
public boolean isLeaf();
/**
* Get the agents for this leaf node
*
* @return Agent array
*/ | public Agent[] getValue(); |
DorsetProject/dorset-framework | components/user-service/src/main/java/edu/jhuapl/dorset/fileuserservice/FileUserService.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.fileuserservice;
/**
* FileUserService userservice
*
* FileUserService is a file-based UserService that leverages property files to maintain a set of
* Users. All User files are stored in a single directory and each User has a single User file. The
* naming convention for the set of files includes a base name that is uniform across all users then
* a dash followed by the corresponding Username. Example:
* "path/to/user/files/example-jdoe.properties."
*/
public class FileUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(FileUserService.class);
| // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/main/java/edu/jhuapl/dorset/fileuserservice/FileUserService.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.fileuserservice;
/**
* FileUserService userservice
*
* FileUserService is a file-based UserService that leverages property files to maintain a set of
* Users. All User files are stored in a single directory and each User has a single User file. The
* naming convention for the set of files includes a base name that is uniform across all users then
* a dash followed by the corresponding Username. Example:
* "path/to/user/files/example-jdoe.properties."
*/
public class FileUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(FileUserService.class);
| private Map<String, User> users; |
DorsetProject/dorset-framework | components/user-service/src/main/java/edu/jhuapl/dorset/fileuserservice/FileUserService.java | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set; | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.fileuserservice;
/**
* FileUserService userservice
*
* FileUserService is a file-based UserService that leverages property files to maintain a set of
* Users. All User files are stored in a single directory and each User has a single User file. The
* naming convention for the set of files includes a base name that is uniform across all users then
* a dash followed by the corresponding Username. Example:
* "path/to/user/files/example-jdoe.properties."
*/
public class FileUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(FileUserService.class);
private Map<String, User> users;
protected String userDirPath;
protected String fileBaseName;
/**
*
* FileUserService
*
* @param userDirectoryPath Path to directory that contains User files
* @param fileBaseName Base string of User file names
*
*/ | // Path: core/src/main/java/edu/jhuapl/dorset/users/User.java
// public class User {
//
// public static String ID = "Dorset-id";
// public static String USERNAME = "Dorset-userName";
// public static String FIRSTNAME = "Dorset-firstName";
// public static String LASTNAME = "Dorset-lastName";
// public static String LOCATION = "Dorset-location";
// public static String EMAIL = "Dorset-email";
// public static String DOB = "Dorset-dob";
//
// protected Map<String, String> userInformation = new HashMap<String, String>();
//
// public String getId() {
// return userInformation.get(ID);
// }
//
// public void setId(String id) {
// this.setUserInformation(ID, id);
// }
//
// public String getUserName() {
// return userInformation.get(USERNAME);
// }
//
// public void setUserName(String userName) {
// this.setUserInformation(USERNAME, userName);
// }
//
// public String getFirstName() {
// return userInformation.get(FIRSTNAME);
// }
//
// public void setFirstName(String firstName) {
// this.setUserInformation(FIRSTNAME, firstName);
// }
//
// public String getLastName() {
// return userInformation.get(LASTNAME);
// }
//
// public void setLastName(String lastName) {
// this.setUserInformation(LASTNAME, lastName);
// }
//
// public String getLocation() {
// return userInformation.get(LOCATION);
// }
//
// public void setLocation(String location) {
// this.setUserInformation(LOCATION, location);
// }
//
// public String getEmail() {
// return userInformation.get(EMAIL);
// }
//
// public void setEmail(String email) {
// this.setUserInformation(EMAIL, email);
// }
//
// public String getDob() {
// return userInformation.get(DOB);
// }
//
// public void setDob(String dob) {
// this.setUserInformation(DOB, dob);
// }
//
// public void setUserInformation(String key, String value) {
// userInformation.put(key, value);
// }
//
// public String getUserInformation(String key) {
// return userInformation.get(key);
// }
//
// public Set<String> getUserInformationKeys() {
// return userInformation.keySet();
// }
//
// public void removeUserInformation(String key) {
// userInformation.remove(key);
// }
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserException.java
// public class UserException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserException(String errorMessage) {
// super(errorMessage);
// }
//
// }
//
// Path: core/src/main/java/edu/jhuapl/dorset/users/UserService.java
// public interface UserService {
//
// public String create(User user) throws UserException;
//
// public String retrieve(Properties properties) throws UserException;
//
// public void update(String id, User user) throws UserException;
//
// public void delete(String id);
//
// public User getUser(String id);
//
// }
// Path: components/user-service/src/main/java/edu/jhuapl/dorset/fileuserservice/FileUserService.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.jhuapl.dorset.users.User;
import edu.jhuapl.dorset.users.UserException;
import edu.jhuapl.dorset.users.UserService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* All rights reserved.
*
* 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 edu.jhuapl.dorset.fileuserservice;
/**
* FileUserService userservice
*
* FileUserService is a file-based UserService that leverages property files to maintain a set of
* Users. All User files are stored in a single directory and each User has a single User file. The
* naming convention for the set of files includes a base name that is uniform across all users then
* a dash followed by the corresponding Username. Example:
* "path/to/user/files/example-jdoe.properties."
*/
public class FileUserService implements UserService {
private static final Logger logger = LoggerFactory.getLogger(FileUserService.class);
private Map<String, User> users;
protected String userDirPath;
protected String fileBaseName;
/**
*
* FileUserService
*
* @param userDirectoryPath Path to directory that contains User files
* @param fileBaseName Base string of User file names
*
*/ | public FileUserService(String userDirectoryPath, String fileBaseName) throws UserException { |
mzlogin/AndroidPractices | android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/MainActivity.java | // Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextHookActivity.java
// public class ContextHookActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_context_hook);
// }
// }
//
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextStartActivityHook.java
// public class ContextStartActivityHook {
//
// public static boolean processed = false;
//
// public static void process() throws Exception {
// Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
// Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
// currentActivityThreadMethod.setAccessible(true);
// Object currentActivityThread = currentActivityThreadMethod.invoke(null);
//
// Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
// mInstrumentationField.setAccessible(true);
// Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
//
// Instrumentation fakeInstrumentation = new FakeInstrumentation(mInstrumentation);
//
// mInstrumentationField.set(currentActivityThread, fakeInstrumentation);
//
// processed = true;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import org.mazhuang.hookdemo.plugin.ContextHookActivity;
import org.mazhuang.hookdemo.plugin.ContextStartActivityHook; | package org.mazhuang.hookdemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mContextHookButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
findViewById(R.id.context_hook).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.context_hook:
try { | // Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextHookActivity.java
// public class ContextHookActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_context_hook);
// }
// }
//
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextStartActivityHook.java
// public class ContextStartActivityHook {
//
// public static boolean processed = false;
//
// public static void process() throws Exception {
// Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
// Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
// currentActivityThreadMethod.setAccessible(true);
// Object currentActivityThread = currentActivityThreadMethod.invoke(null);
//
// Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
// mInstrumentationField.setAccessible(true);
// Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
//
// Instrumentation fakeInstrumentation = new FakeInstrumentation(mInstrumentation);
//
// mInstrumentationField.set(currentActivityThread, fakeInstrumentation);
//
// processed = true;
// }
// }
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import org.mazhuang.hookdemo.plugin.ContextHookActivity;
import org.mazhuang.hookdemo.plugin.ContextStartActivityHook;
package org.mazhuang.hookdemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mContextHookButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
findViewById(R.id.context_hook).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.context_hook:
try { | if (!ContextStartActivityHook.processed) { |
mzlogin/AndroidPractices | android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/MainActivity.java | // Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextHookActivity.java
// public class ContextHookActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_context_hook);
// }
// }
//
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextStartActivityHook.java
// public class ContextStartActivityHook {
//
// public static boolean processed = false;
//
// public static void process() throws Exception {
// Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
// Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
// currentActivityThreadMethod.setAccessible(true);
// Object currentActivityThread = currentActivityThreadMethod.invoke(null);
//
// Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
// mInstrumentationField.setAccessible(true);
// Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
//
// Instrumentation fakeInstrumentation = new FakeInstrumentation(mInstrumentation);
//
// mInstrumentationField.set(currentActivityThread, fakeInstrumentation);
//
// processed = true;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import org.mazhuang.hookdemo.plugin.ContextHookActivity;
import org.mazhuang.hookdemo.plugin.ContextStartActivityHook; | package org.mazhuang.hookdemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mContextHookButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
findViewById(R.id.context_hook).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.context_hook:
try {
if (!ContextStartActivityHook.processed) {
ContextStartActivityHook.process();
}
Context context = this.getApplicationContext(); | // Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextHookActivity.java
// public class ContextHookActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_context_hook);
// }
// }
//
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/plugin/ContextStartActivityHook.java
// public class ContextStartActivityHook {
//
// public static boolean processed = false;
//
// public static void process() throws Exception {
// Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
// Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
// currentActivityThreadMethod.setAccessible(true);
// Object currentActivityThread = currentActivityThreadMethod.invoke(null);
//
// Field mInstrumentationField = activityThreadClass.getDeclaredField("mInstrumentation");
// mInstrumentationField.setAccessible(true);
// Instrumentation mInstrumentation = (Instrumentation) mInstrumentationField.get(currentActivityThread);
//
// Instrumentation fakeInstrumentation = new FakeInstrumentation(mInstrumentation);
//
// mInstrumentationField.set(currentActivityThread, fakeInstrumentation);
//
// processed = true;
// }
// }
// Path: android-studio/HookDemo/app/src/main/java/org/mazhuang/hookdemo/MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import org.mazhuang.hookdemo.plugin.ContextHookActivity;
import org.mazhuang.hookdemo.plugin.ContextStartActivityHook;
package org.mazhuang.hookdemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mContextHookButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
findViewById(R.id.context_hook).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.context_hook:
try {
if (!ContextStartActivityHook.processed) {
ContextStartActivityHook.process();
}
Context context = this.getApplicationContext(); | Intent intent = new Intent(context, ContextHookActivity.class); |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/deserializer/OrderTypeDeserializer.java | // Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException; | package cc.bitbank.deserializer;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderTypeDeserializer extends JsonDeserializer<Object> {
@Override | // Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/deserializer/OrderTypeDeserializer.java
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
package cc.bitbank.deserializer;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderTypeDeserializer extends JsonDeserializer<Object> {
@Override | public OrderType deserialize(JsonParser jp, DeserializationContext dc) throws IOException { |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/Order.java | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date; | package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends Data {
@JsonProperty("order_id")
public long orderId;
public String pair; | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/entity/Order.java
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;
package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends Data {
@JsonProperty("order_id")
public long orderId;
public String pair; | public OrderSide side; |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/Order.java | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date; | package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends Data {
@JsonProperty("order_id")
public long orderId;
public String pair;
public OrderSide side; | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/entity/Order.java
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;
package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order extends Data {
@JsonProperty("order_id")
public long orderId;
public String pair;
public OrderSide side; | public OrderType type; |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/request/OrderBody.java | // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal; | package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/entity/request/OrderBody.java
import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| public OrderBody(CurrencyPair pair, BigDecimal amount, BigDecimal price, OrderSide side, OrderType type, |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/request/OrderBody.java | // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal; | package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/entity/request/OrderBody.java
import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| public OrderBody(CurrencyPair pair, BigDecimal amount, BigDecimal price, OrderSide side, OrderType type, |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/request/OrderBody.java | // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
| import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal; | package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
//
// Path: src/main/java/cc/bitbank/entity/enums/OrderType.java
// @JsonDeserialize(using = OrderTypeDeserializer.class)
// public enum OrderType {
// LIMIT("limit"),
// MARKET("market"),
// STOP("stop"),
// STOP_LIMIT("stop_limit");
//
// private final String type;
//
// OrderType(final String type) {
// this.type = type;
// }
//
// public String getCode() {
// return this.type;
// }
// }
// Path: src/main/java/cc/bitbank/entity/request/OrderBody.java
import cc.bitbank.entity.enums.CurrencyPair;
import cc.bitbank.entity.enums.OrderSide;
import cc.bitbank.entity.enums.OrderType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderBody {
public String pair;
public String amount;
public BigDecimal price;
public String side;
public String type;
@JsonProperty("post_only")
public boolean postOnly;
@JsonProperty("trigger_price")
public BigDecimal triggerPrice;
| public OrderBody(CurrencyPair pair, BigDecimal amount, BigDecimal price, OrderSide side, OrderType type, |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/request/CancelBody.java | // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
| import cc.bitbank.entity.enums.CurrencyPair;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; | package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class CancelBody {
public String pair;
@JsonProperty("order_id")
public long orderId;
| // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
// Path: src/main/java/cc/bitbank/entity/request/CancelBody.java
import cc.bitbank.entity.enums.CurrencyPair;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class CancelBody {
public String pair;
@JsonProperty("order_id")
public long orderId;
| public CancelBody(CurrencyPair pair, long orderId) { |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/Transactions.java | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
| import cc.bitbank.entity.enums.OrderSide;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date; | package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
public class Transactions extends Data {
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Transaction {
@JsonProperty("transaction_id")
private long transactionId;
| // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
// Path: src/main/java/cc/bitbank/entity/Transactions.java
import cc.bitbank.entity.enums.OrderSide;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date;
package cc.bitbank.entity;
/**
* Created by tanaka on 2017/04/12.
*/
public class Transactions extends Data {
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Transaction {
@JsonProperty("transaction_id")
private long transactionId;
| private OrderSide side; |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/deserializer/OrderSideDeserializer.java | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
| import cc.bitbank.entity.enums.OrderSide;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException; | package cc.bitbank.deserializer;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderSideDeserializer extends JsonDeserializer<Object> {
@Override | // Path: src/main/java/cc/bitbank/entity/enums/OrderSide.java
// @JsonDeserialize(using = OrderSideDeserializer.class)
// public enum OrderSide {
// BUY("buy"),
// SELL("sell");
//
// private final String side;
//
// OrderSide(final String side) {
// this.side = side;
// }
//
// public String getCode() {
// return this.side;
// }
// }
// Path: src/main/java/cc/bitbank/deserializer/OrderSideDeserializer.java
import cc.bitbank.entity.enums.OrderSide;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
package cc.bitbank.deserializer;
/**
* Created by tanaka on 2017/04/12.
*/
public class OrderSideDeserializer extends JsonDeserializer<Object> {
@Override | public OrderSide deserialize(JsonParser jp, DeserializationContext dc) throws IOException { |
bitbankinc/java-bitbankcc | src/main/java/cc/bitbank/entity/request/CancelsBody.java | // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
| import cc.bitbank.entity.enums.CurrencyPair;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; | package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class CancelsBody {
public String pair;
@JsonProperty("order_ids")
public long[] orderIds;
| // Path: src/main/java/cc/bitbank/entity/enums/CurrencyPair.java
// public enum CurrencyPair {
// BTC_JPY("btc_jpy"),
// LTC_JPY("ltc_jpy"),
// LTC_BTC("ltc_btc"),
// XRP_JPY("xrp_jpy"),
// XRP_BTC("xrp_btc"),
// ETH_JPY("eth_jpy"),
// ETH_BTC("eth_btc"),
// MONA_JPY("mona_jpy"),
// MONA_BTC("mona_btc"),
// BCC_JPY("bcc_jpy"),
// BCC_BTC("bcc_btc"),
// XLM_JPY("xlm_jpy"),
// XLM_BTC("xlm_btc"),
// QTUM_JPY("qtum_jpy"),
// QTUM_BTC("qtum_btc"),
// BAT_JPY("bat_jpy"),
// BAT_BTC("bat_btc"),
// OMG_JPY("omg_jpy"),
// OMG_BTC("omg_btc"),
// XYM_JPY("xym_jpy"),
// XYM_BTC("xym_btc"),
// LINK_JPY("link_jpy"),
// LINK_BTC("link_btc"),
// MKR_JPY("mkr_jpy"),
// MKR_BTC("mkr_btc");
//
//
// private final String pair;
//
// CurrencyPair(final String pair) {
// this.pair = pair;
// }
//
// public String getCode() {
// return this.pair;
// }
// }
// Path: src/main/java/cc/bitbank/entity/request/CancelsBody.java
import cc.bitbank.entity.enums.CurrencyPair;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
package cc.bitbank.entity.request;
/**
* Created by tanaka on 2017/04/12.
*/
public class CancelsBody {
public String pair;
@JsonProperty("order_ids")
public long[] orderIds;
| public CancelsBody(CurrencyPair pair, long[] orderIds) { |
jkazama/sample-boot-micro | micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java | // Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
| import java.util.List;
import org.springframework.http.ResponseEntity;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList; | package sample.api.admin;
/**
* システムドメインに対する社内ユースケース API を表現します。
*/
public interface SystemAdminFacade {
String Path = "/api/admin/system";
String PathFindAudiActor = "/audit/actor/";
String PathFindAudiEvent = "/audit/event/";
String PathFindAppSetting = "/setting/";
String PathChangeAppSetting = "/setting/{id}?value={value}";
String PathProcessDay = "/processDay";
/** 利用者監査ログを検索します。 */ | // Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
// Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
import java.util.List;
import org.springframework.http.ResponseEntity;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
package sample.api.admin;
/**
* システムドメインに対する社内ユースケース API を表現します。
*/
public interface SystemAdminFacade {
String Path = "/api/admin/system";
String PathFindAudiActor = "/audit/actor/";
String PathFindAudiEvent = "/audit/event/";
String PathFindAppSetting = "/setting/";
String PathChangeAppSetting = "/setting/{id}?value={value}";
String PathProcessDay = "/processDay";
/** 利用者監査ログを検索します。 */ | PagingList<AuditActor> findAuditActor(FindAuditActor p); |
jkazama/sample-boot-micro | micro-web/src/main/java/sample/controller/system/JobController.java | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/api/admin/AssetAdminFacade.java
// public interface AssetAdminFacade {
//
// String Path = "/api/admin/asset";
//
// String PathFindCashInOut = "/cio/";
// String PathClosingCashOut = "/cio/closingCashOut";
// String PathRealizeCashflow = "/cf/realizeCashflow";
//
// /** 未処理の振込依頼情報を検索します。 */
// List<CashInOut> findCashInOut(FindCashInOut p);
//
// /**
// * 振込出金依頼を締めます。
// */
// ResponseEntity<Void> closingCashOut();
//
// /**
// * キャッシュフローを実現します。
// * <p>受渡日を迎えたキャッシュフローを残高に反映します。
// */
// ResponseEntity<Void> realizeCashflow();
//
// }
| import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.microasset.api.admin.AssetAdminFacade; | package sample.controller.system;
/**
* システムジョブのUI要求を処理します。
* low: 通常はバッチプロセス(または社内プロセスに内包)を別途作成して、ジョブスケジューラから実行される方式になります。
* ジョブの負荷がオンライン側へ影響を与えないよう事前段階の設計が重要になります。
* low: 社内/バッチプロセス切り出す場合はVM分散時の情報/排他同期を意識する必要があります。(DB同期/メッセージング同期/分散製品の利用 等)
*/
@RestController
@RequestMapping("/api/system/job")
public class JobController {
| // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/api/admin/AssetAdminFacade.java
// public interface AssetAdminFacade {
//
// String Path = "/api/admin/asset";
//
// String PathFindCashInOut = "/cio/";
// String PathClosingCashOut = "/cio/closingCashOut";
// String PathRealizeCashflow = "/cf/realizeCashflow";
//
// /** 未処理の振込依頼情報を検索します。 */
// List<CashInOut> findCashInOut(FindCashInOut p);
//
// /**
// * 振込出金依頼を締めます。
// */
// ResponseEntity<Void> closingCashOut();
//
// /**
// * キャッシュフローを実現します。
// * <p>受渡日を迎えたキャッシュフローを残高に反映します。
// */
// ResponseEntity<Void> realizeCashflow();
//
// }
// Path: micro-web/src/main/java/sample/controller/system/JobController.java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.microasset.api.admin.AssetAdminFacade;
package sample.controller.system;
/**
* システムジョブのUI要求を処理します。
* low: 通常はバッチプロセス(または社内プロセスに内包)を別途作成して、ジョブスケジューラから実行される方式になります。
* ジョブの負荷がオンライン側へ影響を与えないよう事前段階の設計が重要になります。
* low: 社内/バッチプロセス切り出す場合はVM分散時の情報/排他同期を意識する必要があります。(DB同期/メッセージング同期/分散製品の利用 等)
*/
@RestController
@RequestMapping("/api/system/job")
public class JobController {
| private final AssetAdminFacade asset; |
jkazama/sample-boot-micro | micro-web/src/main/java/sample/controller/system/JobController.java | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/api/admin/AssetAdminFacade.java
// public interface AssetAdminFacade {
//
// String Path = "/api/admin/asset";
//
// String PathFindCashInOut = "/cio/";
// String PathClosingCashOut = "/cio/closingCashOut";
// String PathRealizeCashflow = "/cf/realizeCashflow";
//
// /** 未処理の振込依頼情報を検索します。 */
// List<CashInOut> findCashInOut(FindCashInOut p);
//
// /**
// * 振込出金依頼を締めます。
// */
// ResponseEntity<Void> closingCashOut();
//
// /**
// * キャッシュフローを実現します。
// * <p>受渡日を迎えたキャッシュフローを残高に反映します。
// */
// ResponseEntity<Void> realizeCashflow();
//
// }
| import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.microasset.api.admin.AssetAdminFacade; | package sample.controller.system;
/**
* システムジョブのUI要求を処理します。
* low: 通常はバッチプロセス(または社内プロセスに内包)を別途作成して、ジョブスケジューラから実行される方式になります。
* ジョブの負荷がオンライン側へ影響を与えないよう事前段階の設計が重要になります。
* low: 社内/バッチプロセス切り出す場合はVM分散時の情報/排他同期を意識する必要があります。(DB同期/メッセージング同期/分散製品の利用 等)
*/
@RestController
@RequestMapping("/api/system/job")
public class JobController {
private final AssetAdminFacade asset; | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/api/admin/AssetAdminFacade.java
// public interface AssetAdminFacade {
//
// String Path = "/api/admin/asset";
//
// String PathFindCashInOut = "/cio/";
// String PathClosingCashOut = "/cio/closingCashOut";
// String PathRealizeCashflow = "/cf/realizeCashflow";
//
// /** 未処理の振込依頼情報を検索します。 */
// List<CashInOut> findCashInOut(FindCashInOut p);
//
// /**
// * 振込出金依頼を締めます。
// */
// ResponseEntity<Void> closingCashOut();
//
// /**
// * キャッシュフローを実現します。
// * <p>受渡日を迎えたキャッシュフローを残高に反映します。
// */
// ResponseEntity<Void> realizeCashflow();
//
// }
// Path: micro-web/src/main/java/sample/controller/system/JobController.java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.microasset.api.admin.AssetAdminFacade;
package sample.controller.system;
/**
* システムジョブのUI要求を処理します。
* low: 通常はバッチプロセス(または社内プロセスに内包)を別途作成して、ジョブスケジューラから実行される方式になります。
* ジョブの負荷がオンライン側へ影響を与えないよう事前段階の設計が重要になります。
* low: 社内/バッチプロセス切り出す場合はVM分散時の情報/排他同期を意識する必要があります。(DB同期/メッセージング同期/分散製品の利用 等)
*/
@RestController
@RequestMapping("/api/system/job")
public class JobController {
private final AssetAdminFacade asset; | private final SystemAdminFacade system; |
jkazama/sample-boot-micro | micro-core/src/main/java/sample/context/orm/OrmCriteria.java | // Path: micro-core/src/main/java/sample/context/orm/Sort.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class SortOrder implements Serializable {
// private static final long serialVersionUID = 1L;
// private String property;
// private boolean ascending;
//
// public static SortOrder asc(String property) {
// return new SortOrder(property, true);
// }
//
// public static SortOrder desc(String property) {
// return new SortOrder(property, false);
// }
// }
| import java.time.*;
import java.util.*;
import java.util.function.Function;
import javax.persistence.EntityManager;
import javax.persistence.criteria.*;
import javax.persistence.metamodel.Metamodel;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.MatchMode;
import sample.context.orm.Sort.SortOrder; | public <Y extends Comparable<? super Y>> OrmCriteria<T> gt(String field, final Y value) {
if (isValid(value)) {
add(builder.greaterThan(root.get(field), value));
}
return this;
}
/** [フィールド]<=[値] 条件を付与します。 */
public <Y extends Comparable<? super Y>> OrmCriteria<T> lte(String field, final Y value) {
if (isValid(value)) {
add(builder.lessThanOrEqualTo(root.get(field), value));
}
return this;
}
/** [フィールド]<[値] 条件を付与します。 */
public <Y extends Comparable<? super Y>> OrmCriteria<T> lt(String field, final Y value) {
if (isValid(value)) {
add(builder.lessThan(root.get(field), value));
}
return this;
}
/** ソート条件を加えます。 */
public OrmCriteria<T> sort(Sort sort) {
sort.getOrders().forEach(this::sort);
return this;
}
/** ソート条件を加えます。 */ | // Path: micro-core/src/main/java/sample/context/orm/Sort.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class SortOrder implements Serializable {
// private static final long serialVersionUID = 1L;
// private String property;
// private boolean ascending;
//
// public static SortOrder asc(String property) {
// return new SortOrder(property, true);
// }
//
// public static SortOrder desc(String property) {
// return new SortOrder(property, false);
// }
// }
// Path: micro-core/src/main/java/sample/context/orm/OrmCriteria.java
import java.time.*;
import java.util.*;
import java.util.function.Function;
import javax.persistence.EntityManager;
import javax.persistence.criteria.*;
import javax.persistence.metamodel.Metamodel;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.MatchMode;
import sample.context.orm.Sort.SortOrder;
public <Y extends Comparable<? super Y>> OrmCriteria<T> gt(String field, final Y value) {
if (isValid(value)) {
add(builder.greaterThan(root.get(field), value));
}
return this;
}
/** [フィールド]<=[値] 条件を付与します。 */
public <Y extends Comparable<? super Y>> OrmCriteria<T> lte(String field, final Y value) {
if (isValid(value)) {
add(builder.lessThanOrEqualTo(root.get(field), value));
}
return this;
}
/** [フィールド]<[値] 条件を付与します。 */
public <Y extends Comparable<? super Y>> OrmCriteria<T> lt(String field, final Y value) {
if (isValid(value)) {
add(builder.lessThan(root.get(field), value));
}
return this;
}
/** ソート条件を加えます。 */
public OrmCriteria<T> sort(Sort sort) {
sort.getOrders().forEach(this::sort);
return this;
}
/** ソート条件を加えます。 */ | public OrmCriteria<T> sort(SortOrder order) { |
jkazama/sample-boot-micro | micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java | // Path: micro-core/src/main/java/sample/context/rest/RestActorSessionInterceptor.java
// public static class RestActorSessionConverter {
// private static final Logger logger = LoggerFactory.getLogger(RestActorSessionConverter.class);
// public static String convert(Actor actor) {
// return String.join("_", actor.getId(), actor.getName(), actor.getRoleType().name(),
// actor.getLocale().getLanguage(),
// Optional.ofNullable(actor.getChannel()).orElse("none"),
// Optional.ofNullable(actor.getSource()).orElse("none"));
// }
// public static Actor convert(String actorStr) {
// String[] params = actorStr.split("_");
// if (params.length != 6) {
// logger.warn("Actor への変換に失敗しました。");
// return Actor.Anonymous;
// }
// return new Actor(params[0], params[1], ActorRoleType.valueOf(params[2]),
// new Locale(params[3]), params[4], params[5]);
// }
// }
| import java.io.IOException;
import java.util.Optional;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.filter.GenericFilterBean;
import sample.context.actor.ActorSession;
import sample.context.rest.RestActorSessionInterceptor.RestActorSessionConverter; | package sample.context.rest;
/**
* プロセス間で ActorSession を引き継ぎさせる Filter。 (受付側)
* <p>あらかじめ要求元プロセスに RestActorSessionInterceptor を適用しておく必要があります。
* <p>非同期 Servlet を利用する場合は利用できません。( 別途同様の仕組みを作成してください )
*/
public class RestActorSessionBindFilter extends GenericFilterBean {
private final ActorSession session;
public RestActorSessionBindFilter(ActorSession session) {
this.session = session;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
Optional.ofNullable(actorStr).ifPresent((str) -> | // Path: micro-core/src/main/java/sample/context/rest/RestActorSessionInterceptor.java
// public static class RestActorSessionConverter {
// private static final Logger logger = LoggerFactory.getLogger(RestActorSessionConverter.class);
// public static String convert(Actor actor) {
// return String.join("_", actor.getId(), actor.getName(), actor.getRoleType().name(),
// actor.getLocale().getLanguage(),
// Optional.ofNullable(actor.getChannel()).orElse("none"),
// Optional.ofNullable(actor.getSource()).orElse("none"));
// }
// public static Actor convert(String actorStr) {
// String[] params = actorStr.split("_");
// if (params.length != 6) {
// logger.warn("Actor への変換に失敗しました。");
// return Actor.Anonymous;
// }
// return new Actor(params[0], params[1], ActorRoleType.valueOf(params[2]),
// new Locale(params[3]), params[4], params[5]);
// }
// }
// Path: micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java
import java.io.IOException;
import java.util.Optional;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.filter.GenericFilterBean;
import sample.context.actor.ActorSession;
import sample.context.rest.RestActorSessionInterceptor.RestActorSessionConverter;
package sample.context.rest;
/**
* プロセス間で ActorSession を引き継ぎさせる Filter。 (受付側)
* <p>あらかじめ要求元プロセスに RestActorSessionInterceptor を適用しておく必要があります。
* <p>非同期 Servlet を利用する場合は利用できません。( 別途同様の仕組みを作成してください )
*/
public class RestActorSessionBindFilter extends GenericFilterBean {
private final ActorSession session;
public RestActorSessionBindFilter(ActorSession session) {
this.session = session;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
Optional.ofNullable(actorStr).ifPresent((str) -> | session.bind(RestActorSessionConverter.convert(str))); |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/MicroAppConfig.java | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java
// public class RestActorSessionBindFilter extends GenericFilterBean {
//
// private final ActorSession session;
//
// public RestActorSessionBindFilter(ActorSession session) {
// this.session = session;
// }
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
// throws IOException, ServletException {
// try {
// String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
// Optional.ofNullable(actorStr).ifPresent((str) ->
// session.bind(RestActorSessionConverter.convert(str)));
// chain.doFilter(request, response);
// } finally {
// session.unbind();
// }
// }
//
// }
| import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.health.*;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import sample.context.Timestamper;
import sample.context.actor.ActorSession;
import sample.context.orm.DefaultRepository;
import sample.context.rest.RestActorSessionBindFilter;
import sample.model.*;
import sample.model.BusinessDayHandler.HolidayAccessor; | package sample;
/**
* アプリケーションドメインのコンポーネント定義を表現します。
*/
@Configuration
@Import({ApplicationConfig.class})
public class MicroAppConfig {
/** Domain 層のコンテナ管理を表現します。 */
@Configuration
static class DomainAutoConfig {
/** データ生成ユーティリティ */
@Bean
@ConditionalOnProperty(prefix = DataFixtures.Prefix, name = "enabled", matchIfMissing = false)
DataFixtures fixtures() {
return new DataFixtures();
}
/** 休日情報アクセサ */
@Bean
HolidayAccessor holidayAccessor(
DefaultRepository rep,
@Qualifier(DefaultRepository.BeanNameTx)
PlatformTransactionManager txm) {
return new HolidayAccessor(txm, rep); //low: 定義側にスキーマ指定を委ねるときは外部から設定するアプローチで
}
/** 営業日ユーティリティ */
@Bean | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java
// public class RestActorSessionBindFilter extends GenericFilterBean {
//
// private final ActorSession session;
//
// public RestActorSessionBindFilter(ActorSession session) {
// this.session = session;
// }
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
// throws IOException, ServletException {
// try {
// String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
// Optional.ofNullable(actorStr).ifPresent((str) ->
// session.bind(RestActorSessionConverter.convert(str)));
// chain.doFilter(request, response);
// } finally {
// session.unbind();
// }
// }
//
// }
// Path: micro-app/src/main/java/sample/MicroAppConfig.java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.health.*;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import sample.context.Timestamper;
import sample.context.actor.ActorSession;
import sample.context.orm.DefaultRepository;
import sample.context.rest.RestActorSessionBindFilter;
import sample.model.*;
import sample.model.BusinessDayHandler.HolidayAccessor;
package sample;
/**
* アプリケーションドメインのコンポーネント定義を表現します。
*/
@Configuration
@Import({ApplicationConfig.class})
public class MicroAppConfig {
/** Domain 層のコンテナ管理を表現します。 */
@Configuration
static class DomainAutoConfig {
/** データ生成ユーティリティ */
@Bean
@ConditionalOnProperty(prefix = DataFixtures.Prefix, name = "enabled", matchIfMissing = false)
DataFixtures fixtures() {
return new DataFixtures();
}
/** 休日情報アクセサ */
@Bean
HolidayAccessor holidayAccessor(
DefaultRepository rep,
@Qualifier(DefaultRepository.BeanNameTx)
PlatformTransactionManager txm) {
return new HolidayAccessor(txm, rep); //low: 定義側にスキーマ指定を委ねるときは外部から設定するアプローチで
}
/** 営業日ユーティリティ */
@Bean | BusinessDayHandler businessDayHandler(Timestamper time, HolidayAccessor holiday) { |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/MicroAppConfig.java | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java
// public class RestActorSessionBindFilter extends GenericFilterBean {
//
// private final ActorSession session;
//
// public RestActorSessionBindFilter(ActorSession session) {
// this.session = session;
// }
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
// throws IOException, ServletException {
// try {
// String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
// Optional.ofNullable(actorStr).ifPresent((str) ->
// session.bind(RestActorSessionConverter.convert(str)));
// chain.doFilter(request, response);
// } finally {
// session.unbind();
// }
// }
//
// }
| import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.health.*;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import sample.context.Timestamper;
import sample.context.actor.ActorSession;
import sample.context.orm.DefaultRepository;
import sample.context.rest.RestActorSessionBindFilter;
import sample.model.*;
import sample.model.BusinessDayHandler.HolidayAccessor; | package sample;
/**
* アプリケーションドメインのコンポーネント定義を表現します。
*/
@Configuration
@Import({ApplicationConfig.class})
public class MicroAppConfig {
/** Domain 層のコンテナ管理を表現します。 */
@Configuration
static class DomainAutoConfig {
/** データ生成ユーティリティ */
@Bean
@ConditionalOnProperty(prefix = DataFixtures.Prefix, name = "enabled", matchIfMissing = false)
DataFixtures fixtures() {
return new DataFixtures();
}
/** 休日情報アクセサ */
@Bean
HolidayAccessor holidayAccessor(
DefaultRepository rep,
@Qualifier(DefaultRepository.BeanNameTx)
PlatformTransactionManager txm) {
return new HolidayAccessor(txm, rep); //low: 定義側にスキーマ指定を委ねるときは外部から設定するアプローチで
}
/** 営業日ユーティリティ */
@Bean
BusinessDayHandler businessDayHandler(Timestamper time, HolidayAccessor holiday) {
return BusinessDayHandler.of(time, holiday);
}
}
/** プロセススコープの拡張定義を表現します。 */
@Configuration
static class ProcessAutoConfig {
/**
* リクエストに利用者情報が設定されていた時はそのままスレッドローカルへ紐づけます。
* <p>同期Servletでのみ適切に動きます。
*/
@Bean | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/rest/RestActorSessionBindFilter.java
// public class RestActorSessionBindFilter extends GenericFilterBean {
//
// private final ActorSession session;
//
// public RestActorSessionBindFilter(ActorSession session) {
// this.session = session;
// }
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
// throws IOException, ServletException {
// try {
// String actorStr = ((HttpServletRequest)request).getHeader(RestActorSessionInterceptor.AttrActorSession);
// Optional.ofNullable(actorStr).ifPresent((str) ->
// session.bind(RestActorSessionConverter.convert(str)));
// chain.doFilter(request, response);
// } finally {
// session.unbind();
// }
// }
//
// }
// Path: micro-app/src/main/java/sample/MicroAppConfig.java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.health.*;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import sample.context.Timestamper;
import sample.context.actor.ActorSession;
import sample.context.orm.DefaultRepository;
import sample.context.rest.RestActorSessionBindFilter;
import sample.model.*;
import sample.model.BusinessDayHandler.HolidayAccessor;
package sample;
/**
* アプリケーションドメインのコンポーネント定義を表現します。
*/
@Configuration
@Import({ApplicationConfig.class})
public class MicroAppConfig {
/** Domain 層のコンテナ管理を表現します。 */
@Configuration
static class DomainAutoConfig {
/** データ生成ユーティリティ */
@Bean
@ConditionalOnProperty(prefix = DataFixtures.Prefix, name = "enabled", matchIfMissing = false)
DataFixtures fixtures() {
return new DataFixtures();
}
/** 休日情報アクセサ */
@Bean
HolidayAccessor holidayAccessor(
DefaultRepository rep,
@Qualifier(DefaultRepository.BeanNameTx)
PlatformTransactionManager txm) {
return new HolidayAccessor(txm, rep); //low: 定義側にスキーマ指定を委ねるときは外部から設定するアプローチで
}
/** 営業日ユーティリティ */
@Bean
BusinessDayHandler businessDayHandler(Timestamper time, HolidayAccessor holiday) {
return BusinessDayHandler.of(time, holiday);
}
}
/** プロセススコープの拡張定義を表現します。 */
@Configuration
static class ProcessAutoConfig {
/**
* リクエストに利用者情報が設定されていた時はそのままスレッドローカルへ紐づけます。
* <p>同期Servletでのみ適切に動きます。
*/
@Bean | public RestActorSessionBindFilter restActorSessionBindFilter(ActorSession session) { |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/MicroAssetDbConfig.java | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
| import static sample.microasset.context.orm.AssetRepository.*;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.orm.jpa.*;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.context.orm.AssetRepository.AssetDataSourceProperties; | package sample.microasset;
/**
* 資産ドメインのデータベース接続定義を表現します。
*/
@Configuration
@EnableConfigurationProperties({AssetDataSourceProperties.class})
public class MicroAssetDbConfig {
@Bean
@DependsOn(BeanNameEmf) | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
// Path: micro-asset/src/main/java/sample/microasset/MicroAssetDbConfig.java
import static sample.microasset.context.orm.AssetRepository.*;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.orm.jpa.*;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.context.orm.AssetRepository.AssetDataSourceProperties;
package sample.microasset;
/**
* 資産ドメインのデータベース接続定義を表現します。
*/
@Configuration
@EnableConfigurationProperties({AssetDataSourceProperties.class})
public class MicroAssetDbConfig {
@Bean
@DependsOn(BeanNameEmf) | AssetRepository assetRepository() { |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
| import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService; | package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
| // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
// Path: micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java
import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService;
package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
| private final SystemAdminService service; |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
| import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService; | package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
private final SystemAdminService service;
public SystemAdminFacadeExporter(SystemAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiActor) | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
// Path: micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java
import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService;
package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
private final SystemAdminService service;
public SystemAdminFacadeExporter(SystemAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiActor) | public PagingList<AuditActor> findAuditActor(@Valid FindAuditActor p) { |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
| import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService; | package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
private final SystemAdminService service;
public SystemAdminFacadeExporter(SystemAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiActor)
public PagingList<AuditActor> findAuditActor(@Valid FindAuditActor p) {
return service.findAuditActor(p);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiEvent)
public PagingList<AuditEvent> findAuditEvent(@Valid FindAuditEvent p) {
return service.findAuditEvent(p);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAppSetting)
public List<AppSetting> findAppSetting(@Valid FindAppSetting p) {
return service.findAppSetting(p);
}
/** {@inheritDoc} */
@Override
@PostMapping(PathChangeAppSetting)
public ResponseEntity<Void> changeAppSetting(String id, String value) { | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
//
// Path: micro-app/src/main/java/sample/usecase/SystemAdminService.java
// @Service
// public class SystemAdminService {
//
// private final SystemRepository rep;
// private final PlatformTransactionManager txm;
// private final AuditHandler audit;
// private final BusinessDayHandler businessDay;
//
// public SystemAdminService(
// SystemRepository rep,
// @Qualifier(SystemRepository.BeanNameTx)
// PlatformTransactionManager txm,
// AuditHandler audit,
// BusinessDayHandler businessDay) {
// this.rep = rep;
// this.txm = txm;
// this.audit = audit;
// this.businessDay = businessDay;
// }
//
// /** 利用者監査ログを検索します。 */
// public PagingList<AuditActor> findAuditActor(FindAuditActor p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditActor.find(rep, p));
// }
//
// /** イベント監査ログを検索します。 */
// public PagingList<AuditEvent> findAuditEvent(FindAuditEvent p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AuditEvent.find(rep, p));
// }
//
// /** アプリケーション設定一覧を検索します。 */
// public List<AppSetting> findAppSetting(FindAppSetting p) {
// return TxTemplate.of(txm).readOnly().tx(() -> AppSetting.find(rep, p));
// }
//
// public void changeAppSetting(String id, String value) {
// audit.audit("アプリケーション設定情報を変更する", () -> rep.dh().settingSet(id, value));
// }
//
// public void processDay() {
// audit.audit("営業日を進める", () -> rep.dh().time().proceedDay(businessDay.day(1)));
// }
//
// }
// Path: micro-app/src/main/java/sample/api/admin/SystemAdminFacadeExporter.java
import static sample.api.admin.SystemAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
import sample.usecase.SystemAdminService;
package sample.api.admin;
/**
* システム系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminFacadeExporter implements SystemAdminFacade {
private final SystemAdminService service;
public SystemAdminFacadeExporter(SystemAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiActor)
public PagingList<AuditActor> findAuditActor(@Valid FindAuditActor p) {
return service.findAuditActor(p);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAudiEvent)
public PagingList<AuditEvent> findAuditEvent(@Valid FindAuditEvent p) {
return service.findAuditEvent(p);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindAppSetting)
public List<AppSetting> findAppSetting(@Valid FindAppSetting p) {
return service.findAppSetting(p);
}
/** {@inheritDoc} */
@Override
@PostMapping(PathChangeAppSetting)
public ResponseEntity<Void> changeAppSetting(String id, String value) { | return ApiUtils.resultEmpty(() -> service.changeAppSetting(id, value)); |
jkazama/sample-boot-micro | micro-core/src/main/java/sample/ApplicationConfig.java | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/report/ReportHandler.java
// public class ReportHandler {
//
// }
| import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.audit.AuditHandler;
import sample.context.audit.AuditHandler.AuditPersister;
import sample.context.lock.IdLockHandler;
import sample.context.mail.MailHandler;
import sample.context.report.ReportHandler;
import sample.controller.*; | package sample;
/**
* アプリケーションにおける汎用 Bean 定義を表現します。
* <p>クラス側でコンポーネント定義していない時はこちらで明示的に記載してください。
*/
@Configuration
@Import({ApplicationDbConfig.class, ApplicationSecurityConfig.class})
public class ApplicationConfig {
/** SpringMvcの拡張コンフィギュレーション */
@Configuration
static class WebMvcConfig {
/** HibernateのLazyLoading回避対応。 see JacksonAutoConfiguration */
@Bean
Hibernate5Module jsonHibernate5Module() {
return new Hibernate5Module();
}
/** BeanValidationメッセージのUTF-8に対応したValidator。 */
@Bean
LocalValidatorFactoryBean defaultValidator(MessageSource message) {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setValidationMessageSource(message);
return factory;
}
}
/** インフラ層 ( context 配下) のコンポーネント定義を表現します */
@Configuration
static class PlainConfig {
@Bean
Timestamper timestamper() {
return new Timestamper();
}
@Bean
ActorSession actorSession() {
return new ActorSession();
}
@Bean
ResourceBundleHandler resourceBundleHandler() {
return new ResourceBundleHandler();
}
@Bean
AppSettingHandler appSettingHandler() {
return new AppSettingHandler();
}
@Bean
AuditHandler auditHandler() {
return new AuditHandler();
}
@Bean
AuditPersister auditPersister() {
return new AuditPersister();
}
@Bean | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/report/ReportHandler.java
// public class ReportHandler {
//
// }
// Path: micro-core/src/main/java/sample/ApplicationConfig.java
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.audit.AuditHandler;
import sample.context.audit.AuditHandler.AuditPersister;
import sample.context.lock.IdLockHandler;
import sample.context.mail.MailHandler;
import sample.context.report.ReportHandler;
import sample.controller.*;
package sample;
/**
* アプリケーションにおける汎用 Bean 定義を表現します。
* <p>クラス側でコンポーネント定義していない時はこちらで明示的に記載してください。
*/
@Configuration
@Import({ApplicationDbConfig.class, ApplicationSecurityConfig.class})
public class ApplicationConfig {
/** SpringMvcの拡張コンフィギュレーション */
@Configuration
static class WebMvcConfig {
/** HibernateのLazyLoading回避対応。 see JacksonAutoConfiguration */
@Bean
Hibernate5Module jsonHibernate5Module() {
return new Hibernate5Module();
}
/** BeanValidationメッセージのUTF-8に対応したValidator。 */
@Bean
LocalValidatorFactoryBean defaultValidator(MessageSource message) {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setValidationMessageSource(message);
return factory;
}
}
/** インフラ層 ( context 配下) のコンポーネント定義を表現します */
@Configuration
static class PlainConfig {
@Bean
Timestamper timestamper() {
return new Timestamper();
}
@Bean
ActorSession actorSession() {
return new ActorSession();
}
@Bean
ResourceBundleHandler resourceBundleHandler() {
return new ResourceBundleHandler();
}
@Bean
AppSettingHandler appSettingHandler() {
return new AppSettingHandler();
}
@Bean
AuditHandler auditHandler() {
return new AuditHandler();
}
@Bean
AuditPersister auditPersister() {
return new AuditPersister();
}
@Bean | IdLockHandler idLockHandler() { |
jkazama/sample-boot-micro | micro-core/src/main/java/sample/ApplicationConfig.java | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/report/ReportHandler.java
// public class ReportHandler {
//
// }
| import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.audit.AuditHandler;
import sample.context.audit.AuditHandler.AuditPersister;
import sample.context.lock.IdLockHandler;
import sample.context.mail.MailHandler;
import sample.context.report.ReportHandler;
import sample.controller.*; | package sample;
/**
* アプリケーションにおける汎用 Bean 定義を表現します。
* <p>クラス側でコンポーネント定義していない時はこちらで明示的に記載してください。
*/
@Configuration
@Import({ApplicationDbConfig.class, ApplicationSecurityConfig.class})
public class ApplicationConfig {
/** SpringMvcの拡張コンフィギュレーション */
@Configuration
static class WebMvcConfig {
/** HibernateのLazyLoading回避対応。 see JacksonAutoConfiguration */
@Bean
Hibernate5Module jsonHibernate5Module() {
return new Hibernate5Module();
}
/** BeanValidationメッセージのUTF-8に対応したValidator。 */
@Bean
LocalValidatorFactoryBean defaultValidator(MessageSource message) {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setValidationMessageSource(message);
return factory;
}
}
/** インフラ層 ( context 配下) のコンポーネント定義を表現します */
@Configuration
static class PlainConfig {
@Bean
Timestamper timestamper() {
return new Timestamper();
}
@Bean
ActorSession actorSession() {
return new ActorSession();
}
@Bean
ResourceBundleHandler resourceBundleHandler() {
return new ResourceBundleHandler();
}
@Bean
AppSettingHandler appSettingHandler() {
return new AppSettingHandler();
}
@Bean
AuditHandler auditHandler() {
return new AuditHandler();
}
@Bean
AuditPersister auditPersister() {
return new AuditPersister();
}
@Bean
IdLockHandler idLockHandler() {
return new IdLockHandler();
}
@Bean
MailHandler mailHandler() {
return new MailHandler();
}
@Bean | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/report/ReportHandler.java
// public class ReportHandler {
//
// }
// Path: micro-core/src/main/java/sample/ApplicationConfig.java
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.audit.AuditHandler;
import sample.context.audit.AuditHandler.AuditPersister;
import sample.context.lock.IdLockHandler;
import sample.context.mail.MailHandler;
import sample.context.report.ReportHandler;
import sample.controller.*;
package sample;
/**
* アプリケーションにおける汎用 Bean 定義を表現します。
* <p>クラス側でコンポーネント定義していない時はこちらで明示的に記載してください。
*/
@Configuration
@Import({ApplicationDbConfig.class, ApplicationSecurityConfig.class})
public class ApplicationConfig {
/** SpringMvcの拡張コンフィギュレーション */
@Configuration
static class WebMvcConfig {
/** HibernateのLazyLoading回避対応。 see JacksonAutoConfiguration */
@Bean
Hibernate5Module jsonHibernate5Module() {
return new Hibernate5Module();
}
/** BeanValidationメッセージのUTF-8に対応したValidator。 */
@Bean
LocalValidatorFactoryBean defaultValidator(MessageSource message) {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setValidationMessageSource(message);
return factory;
}
}
/** インフラ層 ( context 配下) のコンポーネント定義を表現します */
@Configuration
static class PlainConfig {
@Bean
Timestamper timestamper() {
return new Timestamper();
}
@Bean
ActorSession actorSession() {
return new ActorSession();
}
@Bean
ResourceBundleHandler resourceBundleHandler() {
return new ResourceBundleHandler();
}
@Bean
AppSettingHandler appSettingHandler() {
return new AppSettingHandler();
}
@Bean
AuditHandler auditHandler() {
return new AuditHandler();
}
@Bean
AuditPersister auditPersister() {
return new AuditPersister();
}
@Bean
IdLockHandler idLockHandler() {
return new IdLockHandler();
}
@Bean
MailHandler mailHandler() {
return new MailHandler();
}
@Bean | ReportHandler reportHandler() { |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java | // Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
| import java.math.BigDecimal;
import java.time.*;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import lombok.*;
import sample.ActionStatusType;
import sample.ValidationException.ErrorKeys;
import sample.context.Dto;
import sample.context.orm.*;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.constraints.*;
import sample.util.*; | package sample.microasset.model.asset;
/**
* 入出金キャッシュフローを表現します。
* キャッシュフローは振込/振替といったキャッシュフローアクションから生成される確定状態(依頼取消等の無い)の入出金情報です。
* low: 概念を伝えるだけなので必要最低限の項目で表現しています。
* low: 検索関連は主に経理確認や帳票等での利用を想定します
*/
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
public class Cashflow extends OrmActiveMetaRecord<Cashflow> {
private static final long serialVersionUID = 1L;
/** ID */
@Id
@GeneratedValue
private Long id;
/** 口座ID */
@IdStr
private String accountId;
/** 通貨 */
@Currency
private String currency;
/** 金額 */
@Amount
private BigDecimal amount;
/** 入出金 */
@NotNull
@Enumerated(EnumType.STRING) | // Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
// Path: micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java
import java.math.BigDecimal;
import java.time.*;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import lombok.*;
import sample.ActionStatusType;
import sample.ValidationException.ErrorKeys;
import sample.context.Dto;
import sample.context.orm.*;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.constraints.*;
import sample.util.*;
package sample.microasset.model.asset;
/**
* 入出金キャッシュフローを表現します。
* キャッシュフローは振込/振替といったキャッシュフローアクションから生成される確定状態(依頼取消等の無い)の入出金情報です。
* low: 概念を伝えるだけなので必要最低限の項目で表現しています。
* low: 検索関連は主に経理確認や帳票等での利用を想定します
*/
@Entity
@Data
@EqualsAndHashCode(callSuper = false)
public class Cashflow extends OrmActiveMetaRecord<Cashflow> {
private static final long serialVersionUID = 1L;
/** ID */
@Id
@GeneratedValue
private Long id;
/** 口座ID */
@IdStr
private String accountId;
/** 通貨 */
@Currency
private String currency;
/** 金額 */
@Amount
private BigDecimal amount;
/** 入出金 */
@NotNull
@Enumerated(EnumType.STRING) | private CashflowType cashflowType; |
jkazama/sample-boot-micro | micro-asset/src/test/java/sample/EntityTestSupport.java | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
// @Setter
// public class AssetDataFixtures {
//
// @Autowired
// private Timestamper time;
// @Autowired
// private BusinessDayHandler businessDay;
// @Autowired
// private AssetRepository rep;
// @Autowired
// @Qualifier(AssetRepository.BeanNameTx)
// private PlatformTransactionManager tx;
//
// @PostConstruct
// public void initialize() {
// new TransactionTemplate(tx).execute((status) -> {
// initializeInTx();
// return true;
// });
// }
//
// public void initializeInTx() {
// String ccy = "JPY";
// LocalDate baseDay = businessDay.day();
//
// // 口座資産: sample
// cb("sample", baseDay, ccy, "1000000").save(rep);
// }
//
// // asset
//
// /** 口座残高の簡易生成 */
// public CashBalance cb(String accountId, LocalDate baseDay, String currency, String amount) {
// return new CashBalance(null, accountId, baseDay, currency, new BigDecimal(amount), LocalDateTime.now());
// }
//
// /** キャッシュフローの簡易生成 */
// public Cashflow cf(String accountId, String amount, LocalDate eventDay, LocalDate valueDay) {
// return cfReg(accountId, amount, valueDay).create(TimePoint.of(eventDay));
// }
//
// /** キャッシュフロー登録パラメタの簡易生成 */
// public RegCashflow cfReg(String accountId, String amount, LocalDate valueDay) {
// return new RegCashflow(accountId, "JPY", new BigDecimal(amount), CashflowType.CashIn, "cashIn", null, valueDay);
// }
//
// /** 振込入出金依頼の簡易生成 [発生日(T+1)/受渡日(T+3)] */
// public CashInOut cio(String accountId, String absAmount, boolean withdrawal) {
// TimePoint now = time.tp();
// CashInOut m = new CashInOut();
// m.setAccountId(accountId);
// m.setCurrency("JPY");
// m.setAbsAmount(new BigDecimal(absAmount));
// m.setWithdrawal(withdrawal);
// m.setRequestDay(now.getDay());
// m.setRequestDate(now.getDate());
// m.setEventDay(businessDay.day(1));
// m.setValueDay(businessDay.day(3));
// m.setTargetFiCode("tFiCode");
// m.setTargetFiAccountId("tFiAccId");
// m.setSelfFiCode("sFiCode");
// m.setSelfFiAccountId("sFiAccId");
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
//
// }
| import java.time.Clock;
import java.util.*;
import java.util.function.Supplier;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.junit.*;
import org.springframework.orm.jpa.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.orm.*;
import sample.context.orm.DefaultRepository.DefaultDataSourceProperties;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.AssetDataFixtures;
import sample.model.*;
import sample.support.MockDomainHelper; | package sample;
/**
* Spring コンテナを用いない JPA のみに特化した検証用途。
* <p>model パッケージでのみ利用してください。
*/
public class EntityTestSupport {
protected Clock clock = Clock.systemDefaultZone();
protected Timestamper time;
protected BusinessDayHandler businessDay;
protected PasswordEncoder encoder;
protected ActorSession session;
protected MockDomainHelper dh;
protected EntityManagerFactory emf; | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
// @Setter
// public class AssetDataFixtures {
//
// @Autowired
// private Timestamper time;
// @Autowired
// private BusinessDayHandler businessDay;
// @Autowired
// private AssetRepository rep;
// @Autowired
// @Qualifier(AssetRepository.BeanNameTx)
// private PlatformTransactionManager tx;
//
// @PostConstruct
// public void initialize() {
// new TransactionTemplate(tx).execute((status) -> {
// initializeInTx();
// return true;
// });
// }
//
// public void initializeInTx() {
// String ccy = "JPY";
// LocalDate baseDay = businessDay.day();
//
// // 口座資産: sample
// cb("sample", baseDay, ccy, "1000000").save(rep);
// }
//
// // asset
//
// /** 口座残高の簡易生成 */
// public CashBalance cb(String accountId, LocalDate baseDay, String currency, String amount) {
// return new CashBalance(null, accountId, baseDay, currency, new BigDecimal(amount), LocalDateTime.now());
// }
//
// /** キャッシュフローの簡易生成 */
// public Cashflow cf(String accountId, String amount, LocalDate eventDay, LocalDate valueDay) {
// return cfReg(accountId, amount, valueDay).create(TimePoint.of(eventDay));
// }
//
// /** キャッシュフロー登録パラメタの簡易生成 */
// public RegCashflow cfReg(String accountId, String amount, LocalDate valueDay) {
// return new RegCashflow(accountId, "JPY", new BigDecimal(amount), CashflowType.CashIn, "cashIn", null, valueDay);
// }
//
// /** 振込入出金依頼の簡易生成 [発生日(T+1)/受渡日(T+3)] */
// public CashInOut cio(String accountId, String absAmount, boolean withdrawal) {
// TimePoint now = time.tp();
// CashInOut m = new CashInOut();
// m.setAccountId(accountId);
// m.setCurrency("JPY");
// m.setAbsAmount(new BigDecimal(absAmount));
// m.setWithdrawal(withdrawal);
// m.setRequestDay(now.getDay());
// m.setRequestDate(now.getDate());
// m.setEventDay(businessDay.day(1));
// m.setValueDay(businessDay.day(3));
// m.setTargetFiCode("tFiCode");
// m.setTargetFiAccountId("tFiAccId");
// m.setSelfFiCode("sFiCode");
// m.setSelfFiAccountId("sFiAccId");
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
//
// }
// Path: micro-asset/src/test/java/sample/EntityTestSupport.java
import java.time.Clock;
import java.util.*;
import java.util.function.Supplier;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.junit.*;
import org.springframework.orm.jpa.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.orm.*;
import sample.context.orm.DefaultRepository.DefaultDataSourceProperties;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.AssetDataFixtures;
import sample.model.*;
import sample.support.MockDomainHelper;
package sample;
/**
* Spring コンテナを用いない JPA のみに特化した検証用途。
* <p>model パッケージでのみ利用してください。
*/
public class EntityTestSupport {
protected Clock clock = Clock.systemDefaultZone();
protected Timestamper time;
protected BusinessDayHandler businessDay;
protected PasswordEncoder encoder;
protected ActorSession session;
protected MockDomainHelper dh;
protected EntityManagerFactory emf; | protected AssetRepository rep; |
jkazama/sample-boot-micro | micro-asset/src/test/java/sample/EntityTestSupport.java | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
// @Setter
// public class AssetDataFixtures {
//
// @Autowired
// private Timestamper time;
// @Autowired
// private BusinessDayHandler businessDay;
// @Autowired
// private AssetRepository rep;
// @Autowired
// @Qualifier(AssetRepository.BeanNameTx)
// private PlatformTransactionManager tx;
//
// @PostConstruct
// public void initialize() {
// new TransactionTemplate(tx).execute((status) -> {
// initializeInTx();
// return true;
// });
// }
//
// public void initializeInTx() {
// String ccy = "JPY";
// LocalDate baseDay = businessDay.day();
//
// // 口座資産: sample
// cb("sample", baseDay, ccy, "1000000").save(rep);
// }
//
// // asset
//
// /** 口座残高の簡易生成 */
// public CashBalance cb(String accountId, LocalDate baseDay, String currency, String amount) {
// return new CashBalance(null, accountId, baseDay, currency, new BigDecimal(amount), LocalDateTime.now());
// }
//
// /** キャッシュフローの簡易生成 */
// public Cashflow cf(String accountId, String amount, LocalDate eventDay, LocalDate valueDay) {
// return cfReg(accountId, amount, valueDay).create(TimePoint.of(eventDay));
// }
//
// /** キャッシュフロー登録パラメタの簡易生成 */
// public RegCashflow cfReg(String accountId, String amount, LocalDate valueDay) {
// return new RegCashflow(accountId, "JPY", new BigDecimal(amount), CashflowType.CashIn, "cashIn", null, valueDay);
// }
//
// /** 振込入出金依頼の簡易生成 [発生日(T+1)/受渡日(T+3)] */
// public CashInOut cio(String accountId, String absAmount, boolean withdrawal) {
// TimePoint now = time.tp();
// CashInOut m = new CashInOut();
// m.setAccountId(accountId);
// m.setCurrency("JPY");
// m.setAbsAmount(new BigDecimal(absAmount));
// m.setWithdrawal(withdrawal);
// m.setRequestDay(now.getDay());
// m.setRequestDate(now.getDate());
// m.setEventDay(businessDay.day(1));
// m.setValueDay(businessDay.day(3));
// m.setTargetFiCode("tFiCode");
// m.setTargetFiAccountId("tFiAccId");
// m.setSelfFiCode("sFiCode");
// m.setSelfFiAccountId("sFiAccId");
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
//
// }
| import java.time.Clock;
import java.util.*;
import java.util.function.Supplier;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.junit.*;
import org.springframework.orm.jpa.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.orm.*;
import sample.context.orm.DefaultRepository.DefaultDataSourceProperties;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.AssetDataFixtures;
import sample.model.*;
import sample.support.MockDomainHelper; | package sample;
/**
* Spring コンテナを用いない JPA のみに特化した検証用途。
* <p>model パッケージでのみ利用してください。
*/
public class EntityTestSupport {
protected Clock clock = Clock.systemDefaultZone();
protected Timestamper time;
protected BusinessDayHandler businessDay;
protected PasswordEncoder encoder;
protected ActorSession session;
protected MockDomainHelper dh;
protected EntityManagerFactory emf;
protected AssetRepository rep;
protected DefaultRepository repDefault;
protected PlatformTransactionManager txm;
protected DataFixtures fixtures; | // Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
// @Setter
// public class AssetDataFixtures {
//
// @Autowired
// private Timestamper time;
// @Autowired
// private BusinessDayHandler businessDay;
// @Autowired
// private AssetRepository rep;
// @Autowired
// @Qualifier(AssetRepository.BeanNameTx)
// private PlatformTransactionManager tx;
//
// @PostConstruct
// public void initialize() {
// new TransactionTemplate(tx).execute((status) -> {
// initializeInTx();
// return true;
// });
// }
//
// public void initializeInTx() {
// String ccy = "JPY";
// LocalDate baseDay = businessDay.day();
//
// // 口座資産: sample
// cb("sample", baseDay, ccy, "1000000").save(rep);
// }
//
// // asset
//
// /** 口座残高の簡易生成 */
// public CashBalance cb(String accountId, LocalDate baseDay, String currency, String amount) {
// return new CashBalance(null, accountId, baseDay, currency, new BigDecimal(amount), LocalDateTime.now());
// }
//
// /** キャッシュフローの簡易生成 */
// public Cashflow cf(String accountId, String amount, LocalDate eventDay, LocalDate valueDay) {
// return cfReg(accountId, amount, valueDay).create(TimePoint.of(eventDay));
// }
//
// /** キャッシュフロー登録パラメタの簡易生成 */
// public RegCashflow cfReg(String accountId, String amount, LocalDate valueDay) {
// return new RegCashflow(accountId, "JPY", new BigDecimal(amount), CashflowType.CashIn, "cashIn", null, valueDay);
// }
//
// /** 振込入出金依頼の簡易生成 [発生日(T+1)/受渡日(T+3)] */
// public CashInOut cio(String accountId, String absAmount, boolean withdrawal) {
// TimePoint now = time.tp();
// CashInOut m = new CashInOut();
// m.setAccountId(accountId);
// m.setCurrency("JPY");
// m.setAbsAmount(new BigDecimal(absAmount));
// m.setWithdrawal(withdrawal);
// m.setRequestDay(now.getDay());
// m.setRequestDate(now.getDate());
// m.setEventDay(businessDay.day(1));
// m.setValueDay(businessDay.day(3));
// m.setTargetFiCode("tFiCode");
// m.setTargetFiAccountId("tFiAccId");
// m.setSelfFiCode("sFiCode");
// m.setSelfFiAccountId("sFiAccId");
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
//
// }
// Path: micro-asset/src/test/java/sample/EntityTestSupport.java
import java.time.Clock;
import java.util.*;
import java.util.function.Supplier;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.junit.*;
import org.springframework.orm.jpa.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import sample.context.*;
import sample.context.actor.ActorSession;
import sample.context.orm.*;
import sample.context.orm.DefaultRepository.DefaultDataSourceProperties;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.AssetDataFixtures;
import sample.model.*;
import sample.support.MockDomainHelper;
package sample;
/**
* Spring コンテナを用いない JPA のみに特化した検証用途。
* <p>model パッケージでのみ利用してください。
*/
public class EntityTestSupport {
protected Clock clock = Clock.systemDefaultZone();
protected Timestamper time;
protected BusinessDayHandler businessDay;
protected PasswordEncoder encoder;
protected ActorSession session;
protected MockDomainHelper dh;
protected EntityManagerFactory emf;
protected AssetRepository rep;
protected DefaultRepository repDefault;
protected PlatformTransactionManager txm;
protected DataFixtures fixtures; | protected AssetDataFixtures fixturesAsset; |
jkazama/sample-boot-micro | micro-core/src/test/java/sample/model/account/AccountTest.java | // Path: micro-core/src/main/java/sample/model/account/Account.java
// @Entity
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends OrmActiveRecord<Account> {
// private static final long serialVersionUID = 1L;
//
// /** 口座ID */
// @Id
// @IdStr
// private String id;
// /** 口座名義 */
// @Name
// private String name;
// /** メールアドレス */
// @Email
// private String mail;
// /** 口座状態 */
// @NotNull
// @Enumerated(EnumType.STRING)
// private AccountStatusType statusType;
//
// public Actor actor() {
// return new Actor(id, name, ActorRoleType.User);
// }
//
// /** 口座に紐付くログイン情報を取得します。 */
// public Login loadLogin(final OrmRepository rep) {
// return Login.load(rep, id);
// }
//
// /** 口座を変更します。 */
// public Account change(final OrmRepository rep, final ChgAccount p) {
// return p.bind(this).update(rep);
// }
//
// /** 口座を取得します。 */
// public static Optional<Account> get(final OrmRepository rep, String id) {
// return rep.get(Account.class, id);
// }
//
// /** 有効な口座を取得します。 */
// public static Optional<Account> getValid(final OrmRepository rep, String id) {
// return get(rep, id).filter((acc) -> acc.getStatusType().valid());
// }
//
// /** 口座を取得します。(例外付) */
// public static Account load(final OrmRepository rep, String id) {
// return rep.load(Account.class, id);
// }
//
// /** 有効な口座を取得します。(例外付) */
// public static Account loadValid(final OrmRepository rep, String id) {
// return getValid(rep, id).orElseThrow(() -> new ValidationException("error.Account.loadValid"));
// }
//
// /**
// * 口座の登録を行います。
// * <p>ログイン情報も同時に登録されます。
// */
// public static Account register(final OrmRepository rep, final PasswordEncoder encoder, RegAccount p) {
// Validator.validate((v) -> v.checkField(!get(rep, p.id).isPresent(), "id", ErrorKeys.DuplicateId));
// p.createLogin(encoder.encode(p.plainPassword)).save(rep);
// return p.create().save(rep);
// }
//
// /** 登録パラメタ */
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegAccount implements Dto {
// private static final long serialVersionUID = 1l;
//
// @IdStr
// private String id;
// @Name
// private String name;
// @Email
// private String mail;
// /** パスワード(未ハッシュ) */
// @Password
// private String plainPassword;
//
// public Account create() {
// Account m = new Account();
// m.setId(id);
// m.setName(name);
// m.setMail(mail);
// m.setStatusType(AccountStatusType.Normal);
// return m;
// }
//
// public Login createLogin(String password) {
// Login m = new Login();
// m.setId(id);
// m.setLoginId(id);
// m.setPassword(password);
// return m;
// }
// }
//
// /** 変更パラメタ */
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class ChgAccount implements Dto {
// private static final long serialVersionUID = 1l;
// @Name
// private String name;
// @Email
// private String mail;
//
// public Account bind(final Account m) {
// m.setName(name);
// m.setMail(mail);
// return m;
// }
// }
//
// }
| import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import sample.*;
import sample.ValidationException.ErrorKeys;
import sample.model.account.Account.*;
import sample.model.account.type.AccountStatusType; | package sample.model.account;
public class AccountTest extends EntityTestSupport {
@Override
protected void setupPreset() { | // Path: micro-core/src/main/java/sample/model/account/Account.java
// @Entity
// @Data
// @EqualsAndHashCode(callSuper = false)
// public class Account extends OrmActiveRecord<Account> {
// private static final long serialVersionUID = 1L;
//
// /** 口座ID */
// @Id
// @IdStr
// private String id;
// /** 口座名義 */
// @Name
// private String name;
// /** メールアドレス */
// @Email
// private String mail;
// /** 口座状態 */
// @NotNull
// @Enumerated(EnumType.STRING)
// private AccountStatusType statusType;
//
// public Actor actor() {
// return new Actor(id, name, ActorRoleType.User);
// }
//
// /** 口座に紐付くログイン情報を取得します。 */
// public Login loadLogin(final OrmRepository rep) {
// return Login.load(rep, id);
// }
//
// /** 口座を変更します。 */
// public Account change(final OrmRepository rep, final ChgAccount p) {
// return p.bind(this).update(rep);
// }
//
// /** 口座を取得します。 */
// public static Optional<Account> get(final OrmRepository rep, String id) {
// return rep.get(Account.class, id);
// }
//
// /** 有効な口座を取得します。 */
// public static Optional<Account> getValid(final OrmRepository rep, String id) {
// return get(rep, id).filter((acc) -> acc.getStatusType().valid());
// }
//
// /** 口座を取得します。(例外付) */
// public static Account load(final OrmRepository rep, String id) {
// return rep.load(Account.class, id);
// }
//
// /** 有効な口座を取得します。(例外付) */
// public static Account loadValid(final OrmRepository rep, String id) {
// return getValid(rep, id).orElseThrow(() -> new ValidationException("error.Account.loadValid"));
// }
//
// /**
// * 口座の登録を行います。
// * <p>ログイン情報も同時に登録されます。
// */
// public static Account register(final OrmRepository rep, final PasswordEncoder encoder, RegAccount p) {
// Validator.validate((v) -> v.checkField(!get(rep, p.id).isPresent(), "id", ErrorKeys.DuplicateId));
// p.createLogin(encoder.encode(p.plainPassword)).save(rep);
// return p.create().save(rep);
// }
//
// /** 登録パラメタ */
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegAccount implements Dto {
// private static final long serialVersionUID = 1l;
//
// @IdStr
// private String id;
// @Name
// private String name;
// @Email
// private String mail;
// /** パスワード(未ハッシュ) */
// @Password
// private String plainPassword;
//
// public Account create() {
// Account m = new Account();
// m.setId(id);
// m.setName(name);
// m.setMail(mail);
// m.setStatusType(AccountStatusType.Normal);
// return m;
// }
//
// public Login createLogin(String password) {
// Login m = new Login();
// m.setId(id);
// m.setLoginId(id);
// m.setPassword(password);
// return m;
// }
// }
//
// /** 変更パラメタ */
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class ChgAccount implements Dto {
// private static final long serialVersionUID = 1l;
// @Name
// private String name;
// @Email
// private String mail;
//
// public Account bind(final Account m) {
// m.setName(name);
// m.setMail(mail);
// return m;
// }
// }
//
// }
// Path: micro-core/src/test/java/sample/model/account/AccountTest.java
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import sample.*;
import sample.ValidationException.ErrorKeys;
import sample.model.account.Account.*;
import sample.model.account.type.AccountStatusType;
package sample.model.account;
public class AccountTest extends EntityTestSupport {
@Override
protected void setupPreset() { | targetEntities(Account.class, Login.class); |
jkazama/sample-boot-micro | micro-web/src/main/java/sample/controller/admin/MasterAdminController.java | // Path: micro-core/src/main/java/sample/api/admin/MasterAdminFacade.java
// public interface MasterAdminFacade {
//
// String Path = "/api/admin/master";
//
// String PathGetStaff = "/staff/{staffId}/";
// String PathFindStaffAuthority = "/staff/{staffId}/authority";
// String PathRegisterHoliday = "/holiday";
//
// /** 社員を取得します。 */
// Staff getStaff(String staffId);
//
// /** 社員権限を取得します。 */
// List<StaffAuthority> findStaffAuthority(String staffId);
//
// /** 休日を登録します。 */
// ResponseEntity<Void> registerHoliday(final RegHoliday p);
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/MasterAdminFacade.java
// public interface MasterAdminFacade {
//
// String Path = "/api/admin/master";
//
// String PathGetStaff = "/staff/{staffId}/";
// String PathFindStaffAuthority = "/staff/{staffId}/authority";
// String PathRegisterHoliday = "/holiday";
//
// /** 社員を取得します。 */
// Staff getStaff(String staffId);
//
// /** 社員権限を取得します。 */
// List<StaffAuthority> findStaffAuthority(String staffId);
//
// /** 休日を登録します。 */
// ResponseEntity<Void> registerHoliday(final RegHoliday p);
//
// }
| import static sample.api.admin.MasterAdminFacade.*;
import java.util.*;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.*;
import sample.ValidationException;
import sample.ValidationException.ErrorKeys;
import sample.api.admin.MasterAdminFacade;
import sample.context.actor.Actor;
import sample.context.security.*;
import sample.context.security.SecurityActorFinder.ActorDetails;
import sample.model.master.Holiday.RegHoliday; | package sample.controller.admin;
/**
* マスタに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class MasterAdminController {
private final SecurityProperties securityProps; | // Path: micro-core/src/main/java/sample/api/admin/MasterAdminFacade.java
// public interface MasterAdminFacade {
//
// String Path = "/api/admin/master";
//
// String PathGetStaff = "/staff/{staffId}/";
// String PathFindStaffAuthority = "/staff/{staffId}/authority";
// String PathRegisterHoliday = "/holiday";
//
// /** 社員を取得します。 */
// Staff getStaff(String staffId);
//
// /** 社員権限を取得します。 */
// List<StaffAuthority> findStaffAuthority(String staffId);
//
// /** 休日を登録します。 */
// ResponseEntity<Void> registerHoliday(final RegHoliday p);
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/MasterAdminFacade.java
// public interface MasterAdminFacade {
//
// String Path = "/api/admin/master";
//
// String PathGetStaff = "/staff/{staffId}/";
// String PathFindStaffAuthority = "/staff/{staffId}/authority";
// String PathRegisterHoliday = "/holiday";
//
// /** 社員を取得します。 */
// Staff getStaff(String staffId);
//
// /** 社員権限を取得します。 */
// List<StaffAuthority> findStaffAuthority(String staffId);
//
// /** 休日を登録します。 */
// ResponseEntity<Void> registerHoliday(final RegHoliday p);
//
// }
// Path: micro-web/src/main/java/sample/controller/admin/MasterAdminController.java
import static sample.api.admin.MasterAdminFacade.*;
import java.util.*;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.*;
import sample.ValidationException;
import sample.ValidationException.ErrorKeys;
import sample.api.admin.MasterAdminFacade;
import sample.context.actor.Actor;
import sample.context.security.*;
import sample.context.security.SecurityActorFinder.ActorDetails;
import sample.model.master.Holiday.RegHoliday;
package sample.controller.admin;
/**
* マスタに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class MasterAdminController {
private final SecurityProperties securityProps; | private final MasterAdminFacade facade; |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/usecase/AssetAdminService.java | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/CashInOut.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class FindCashInOut implements Dto {
// private static final long serialVersionUID = 1L;
// @CurrencyEmpty
// private String currency;
// private ActionStatusType[] statusTypes;
// @ISODate
// private LocalDate updFromDay;
// @ISODate
// private LocalDate updToDay;
// }
| import java.time.LocalDate;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import lombok.extern.slf4j.Slf4j;
import sample.context.audit.AuditHandler;
import sample.context.lock.IdLockHandler;
import sample.context.lock.IdLockHandler.LockType;
import sample.context.orm.TxTemplate;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.CashInOut.FindCashInOut; | package sample.microasset.usecase;
/**
* 資産ドメインに対する社内ユースケース処理。
*/
@Service
@Slf4j
public class AssetAdminService {
| // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/CashInOut.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class FindCashInOut implements Dto {
// private static final long serialVersionUID = 1L;
// @CurrencyEmpty
// private String currency;
// private ActionStatusType[] statusTypes;
// @ISODate
// private LocalDate updFromDay;
// @ISODate
// private LocalDate updToDay;
// }
// Path: micro-asset/src/main/java/sample/microasset/usecase/AssetAdminService.java
import java.time.LocalDate;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import lombok.extern.slf4j.Slf4j;
import sample.context.audit.AuditHandler;
import sample.context.lock.IdLockHandler;
import sample.context.lock.IdLockHandler.LockType;
import sample.context.orm.TxTemplate;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.CashInOut.FindCashInOut;
package sample.microasset.usecase;
/**
* 資産ドメインに対する社内ユースケース処理。
*/
@Service
@Slf4j
public class AssetAdminService {
| private final AssetRepository rep; |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/usecase/AssetAdminService.java | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/CashInOut.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class FindCashInOut implements Dto {
// private static final long serialVersionUID = 1L;
// @CurrencyEmpty
// private String currency;
// private ActionStatusType[] statusTypes;
// @ISODate
// private LocalDate updFromDay;
// @ISODate
// private LocalDate updToDay;
// }
| import java.time.LocalDate;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import lombok.extern.slf4j.Slf4j;
import sample.context.audit.AuditHandler;
import sample.context.lock.IdLockHandler;
import sample.context.lock.IdLockHandler.LockType;
import sample.context.orm.TxTemplate;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.CashInOut.FindCashInOut; | package sample.microasset.usecase;
/**
* 資産ドメインに対する社内ユースケース処理。
*/
@Service
@Slf4j
public class AssetAdminService {
private final AssetRepository rep;
private final PlatformTransactionManager txm;
private final AuditHandler audit; | // Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public class IdLockHandler {
//
// private ConcurrentMap<Serializable, ReentrantReadWriteLock> lockMap = new ConcurrentHashMap<>();
//
// /** IDロック上で処理を実行します。 */
// public void call(Serializable id, LockType lockType, final Runnable command) {
// call(id, lockType, () -> {
// command.run();
// return true;
// });
// }
//
// public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
// if (lockType.isWrite()) {
// writeLock(id);
// } else {
// readLock(id);
// }
// try {
// return callable.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new InvocationException("error.Exception", e);
// } finally {
// unlock(id);
// }
// }
//
// public void writeLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).writeLock().lock();
// });
// }
//
// private ReentrantReadWriteLock idLock(final Serializable id) {
// return lockMap.computeIfAbsent(id, v -> new ReentrantReadWriteLock());
// }
//
// public void readLock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// idLock(v).readLock().lock();
// });
// }
//
// public void unlock(final Serializable id) {
// Optional.of(id).ifPresent((v) -> {
// ReentrantReadWriteLock idLock = idLock(v);
// if (idLock.isWriteLockedByCurrentThread()) {
// idLock.writeLock().unlock();
// } else {
// idLock.readLock().unlock();
// }
// });
// }
//
// /**
// * ロック種別を表現するEnum。
// */
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// /** IdLock の対象と種別のペアを表現します。 */
// @Value
// public static class IdLockPair {
// private Serializable id;
// private LockType lockType;
// }
//
// }
//
// Path: micro-core/src/main/java/sample/context/lock/IdLockHandler.java
// public static enum LockType {
// /** 読み取り専用ロック */
// Read,
// /** 読み書き専用ロック */
// Write;
//
// public boolean isRead() {
// return !isWrite();
// }
//
// public boolean isWrite() {
// return this == Write;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/CashInOut.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class FindCashInOut implements Dto {
// private static final long serialVersionUID = 1L;
// @CurrencyEmpty
// private String currency;
// private ActionStatusType[] statusTypes;
// @ISODate
// private LocalDate updFromDay;
// @ISODate
// private LocalDate updToDay;
// }
// Path: micro-asset/src/main/java/sample/microasset/usecase/AssetAdminService.java
import java.time.LocalDate;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import lombok.extern.slf4j.Slf4j;
import sample.context.audit.AuditHandler;
import sample.context.lock.IdLockHandler;
import sample.context.lock.IdLockHandler.LockType;
import sample.context.orm.TxTemplate;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.CashInOut.FindCashInOut;
package sample.microasset.usecase;
/**
* 資産ドメインに対する社内ユースケース処理。
*/
@Service
@Slf4j
public class AssetAdminService {
private final AssetRepository rep;
private final PlatformTransactionManager txm;
private final AuditHandler audit; | private final IdLockHandler idLock; |
jkazama/sample-boot-micro | micro-app/src/main/java/sample/api/admin/MasterAdminFacadeExporter.java | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
| import static sample.api.admin.MasterAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.model.master.*;
import sample.model.master.Holiday.RegHoliday;
import sample.usecase.MasterAdminService; | package sample.api.admin;
/**
* マスタ系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class MasterAdminFacadeExporter implements MasterAdminFacade {
private final MasterAdminService service;
public MasterAdminFacadeExporter(MasterAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathGetStaff)
public Staff getStaff(@PathVariable String staffId) {
return service.getStaff(staffId).orElse(null);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindStaffAuthority)
public List<StaffAuthority> findStaffAuthority(@PathVariable String staffId) {
return service.findStaffAuthority(staffId);
}
/** {@inheritDoc} */
@Override
@PostMapping(PathRegisterHoliday)
public ResponseEntity<Void> registerHoliday(@RequestBody @Valid RegHoliday p) { | // Path: micro-core/src/main/java/sample/api/ApiUtils.java
// public abstract class ApiUtils {
//
// /** 戻り値を生成して返します。(戻り値がプリミティブまたはnullを許容する時はこちらを利用してください) */
// public static <T> ResponseEntity<T> result(Supplier<T> command) {
// return ResponseEntity.status(HttpStatus.OK).body(command.get());
// }
//
// /** 空の戻り値を生成して返します。 */
// public static ResponseEntity<Void> resultEmpty(Runnable command) {
// command.run();
// return ResponseEntity.status(HttpStatus.OK).build();
// }
//
// }
// Path: micro-app/src/main/java/sample/api/admin/MasterAdminFacadeExporter.java
import static sample.api.admin.MasterAdminFacade.Path;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.ApiUtils;
import sample.model.master.*;
import sample.model.master.Holiday.RegHoliday;
import sample.usecase.MasterAdminService;
package sample.api.admin;
/**
* マスタ系社内ユースケースの外部公開処理を表現します。
*/
@RestController
@RequestMapping(Path)
public class MasterAdminFacadeExporter implements MasterAdminFacade {
private final MasterAdminService service;
public MasterAdminFacadeExporter(MasterAdminService service) {
this.service = service;
}
/** {@inheritDoc} */
@Override
@GetMapping(PathGetStaff)
public Staff getStaff(@PathVariable String staffId) {
return service.getStaff(staffId).orElse(null);
}
/** {@inheritDoc} */
@Override
@GetMapping(PathFindStaffAuthority)
public List<StaffAuthority> findStaffAuthority(@PathVariable String staffId) {
return service.findStaffAuthority(staffId);
}
/** {@inheritDoc} */
@Override
@PostMapping(PathRegisterHoliday)
public ResponseEntity<Void> registerHoliday(@RequestBody @Valid RegHoliday p) { | return ApiUtils.resultEmpty(() -> service.registerHoliday(p)); |
jkazama/sample-boot-micro | micro-web/src/main/java/sample/controller/admin/SystemAdminController.java | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
| import static sample.api.admin.SystemAdminFacade.*;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList; | package sample.controller.admin;
/**
* システムに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminController {
| // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
// Path: micro-web/src/main/java/sample/controller/admin/SystemAdminController.java
import static sample.api.admin.SystemAdminFacade.*;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
package sample.controller.admin;
/**
* システムに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminController {
| private final SystemAdminFacade facade; |
jkazama/sample-boot-micro | micro-web/src/main/java/sample/controller/admin/SystemAdminController.java | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
| import static sample.api.admin.SystemAdminFacade.*;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList; | package sample.controller.admin;
/**
* システムに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminController {
private final SystemAdminFacade facade;
public SystemAdminController(SystemAdminFacade facade) {
this.facade = facade;
}
/** 利用者監査ログを検索します。 */
@GetMapping(PathFindAudiActor) | // Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/api/admin/SystemAdminFacade.java
// public interface SystemAdminFacade {
//
// String Path = "/api/admin/system";
//
// String PathFindAudiActor = "/audit/actor/";
// String PathFindAudiEvent = "/audit/event/";
// String PathFindAppSetting = "/setting/";
// String PathChangeAppSetting = "/setting/{id}?value={value}";
// String PathProcessDay = "/processDay";
//
// /** 利用者監査ログを検索します。 */
// PagingList<AuditActor> findAuditActor(FindAuditActor p);
//
// /** イベント監査ログを検索します。 */
// PagingList<AuditEvent> findAuditEvent(FindAuditEvent p);
//
// /** アプリケーション設定一覧を検索します。 */
// List<AppSetting> findAppSetting(FindAppSetting p);
//
// /** アプリケーション設定情報を変更します。 */
// ResponseEntity<Void> changeAppSetting(String id, String value);
//
// /** 営業日を進めます。 */
// ResponseEntity<Void> processDay();
//
// }
//
// Path: micro-core/src/main/java/sample/context/orm/PagingList.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class PagingList<T> implements Dto {
// private static final long serialVersionUID = 1L;
//
// private List<T> list;
// private Pagination page;
//
// }
// Path: micro-web/src/main/java/sample/controller/admin/SystemAdminController.java
import static sample.api.admin.SystemAdminFacade.*;
import java.util.List;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sample.api.admin.SystemAdminFacade;
import sample.context.AppSetting;
import sample.context.AppSetting.FindAppSetting;
import sample.context.audit.*;
import sample.context.audit.AuditActor.FindAuditActor;
import sample.context.audit.AuditEvent.FindAuditEvent;
import sample.context.orm.PagingList;
package sample.controller.admin;
/**
* システムに関わる社内のUI要求を処理します。
*/
@RestController
@RequestMapping(Path)
public class SystemAdminController {
private final SystemAdminFacade facade;
public SystemAdminController(SystemAdminFacade facade) {
this.facade = facade;
}
/** 利用者監査ログを検索します。 */
@GetMapping(PathFindAudiActor) | public PagingList<AuditActor> findAuditActor(@Valid FindAuditActor p) { |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegCashflow implements Dto {
// private static final long serialVersionUID = 1L;
// @IdStr
// private String accountId;
// @Currency
// private String currency;
// @Amount
// private BigDecimal amount;
// @NotNull
// private CashflowType cashflowType;
// @Category
// private String remark;
// /** 未設定時は営業日を設定 */
// @ISODateEmpty
// private LocalDate eventDay;
// @ISODate
// private LocalDate valueDay;
//
// public Cashflow create(final TimePoint now) {
// TimePoint eventDate = eventDay == null ? now : new TimePoint(eventDay, now.getDate());
// Cashflow m = new Cashflow();
// m.setAccountId(accountId);
// m.setCurrency(currency);
// m.setAmount(amount);
// m.setCashflowType(cashflowType);
// m.setRemark(remark);
// m.setEventDay(eventDate.getDay());
// m.setEventDate(eventDate.getDate());
// m.setValueDay(valueDay);
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
| import java.math.BigDecimal;
import java.time.*;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import lombok.Setter;
import sample.ActionStatusType;
import sample.context.Timestamper;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.Cashflow.RegCashflow;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.BusinessDayHandler;
import sample.util.TimePoint; | package sample.microasset.model;
@Setter
public class AssetDataFixtures {
@Autowired | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegCashflow implements Dto {
// private static final long serialVersionUID = 1L;
// @IdStr
// private String accountId;
// @Currency
// private String currency;
// @Amount
// private BigDecimal amount;
// @NotNull
// private CashflowType cashflowType;
// @Category
// private String remark;
// /** 未設定時は営業日を設定 */
// @ISODateEmpty
// private LocalDate eventDay;
// @ISODate
// private LocalDate valueDay;
//
// public Cashflow create(final TimePoint now) {
// TimePoint eventDate = eventDay == null ? now : new TimePoint(eventDay, now.getDate());
// Cashflow m = new Cashflow();
// m.setAccountId(accountId);
// m.setCurrency(currency);
// m.setAmount(amount);
// m.setCashflowType(cashflowType);
// m.setRemark(remark);
// m.setEventDay(eventDate.getDay());
// m.setEventDate(eventDate.getDate());
// m.setValueDay(valueDay);
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
import java.math.BigDecimal;
import java.time.*;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import lombok.Setter;
import sample.ActionStatusType;
import sample.context.Timestamper;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.Cashflow.RegCashflow;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.BusinessDayHandler;
import sample.util.TimePoint;
package sample.microasset.model;
@Setter
public class AssetDataFixtures {
@Autowired | private Timestamper time; |
jkazama/sample-boot-micro | micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegCashflow implements Dto {
// private static final long serialVersionUID = 1L;
// @IdStr
// private String accountId;
// @Currency
// private String currency;
// @Amount
// private BigDecimal amount;
// @NotNull
// private CashflowType cashflowType;
// @Category
// private String remark;
// /** 未設定時は営業日を設定 */
// @ISODateEmpty
// private LocalDate eventDay;
// @ISODate
// private LocalDate valueDay;
//
// public Cashflow create(final TimePoint now) {
// TimePoint eventDate = eventDay == null ? now : new TimePoint(eventDay, now.getDate());
// Cashflow m = new Cashflow();
// m.setAccountId(accountId);
// m.setCurrency(currency);
// m.setAmount(amount);
// m.setCashflowType(cashflowType);
// m.setRemark(remark);
// m.setEventDay(eventDate.getDay());
// m.setEventDate(eventDate.getDate());
// m.setValueDay(valueDay);
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
| import java.math.BigDecimal;
import java.time.*;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import lombok.Setter;
import sample.ActionStatusType;
import sample.context.Timestamper;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.Cashflow.RegCashflow;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.BusinessDayHandler;
import sample.util.TimePoint; | package sample.microasset.model;
@Setter
public class AssetDataFixtures {
@Autowired
private Timestamper time;
@Autowired
private BusinessDayHandler businessDay;
@Autowired | // Path: micro-core/src/main/java/sample/context/Timestamper.java
// public class Timestamper {
// public static final String KeyDay = "system.businessDay.day";
//
// @Autowired(required = false)
// private AppSettingHandler setting;
//
// private final Clock clock;
//
// public Timestamper() {
// clock = Clock.systemDefaultZone();
// }
//
// public Timestamper(final Clock clock) {
// this.clock = clock;
// }
//
// /** 営業日を返します。 */
// public LocalDate day() {
// return setting == null ? LocalDate.now(clock) : DateUtils.day(setting.setting(KeyDay).str());
// }
//
// /** 日時を返します。 */
// public LocalDateTime date() {
// return LocalDateTime.now(clock);
// }
//
// /** 営業日/日時を返します。 */
// public TimePoint tp() {
// return TimePoint.of(day(), date());
// }
//
// /**
// * 営業日を指定日へ進めます。
// * <p>AppSettingHandlerを設定時のみ有効です。
// * @param day 更新営業日
// */
// public Timestamper proceedDay(LocalDate day) {
// if (setting != null)
// setting.update(KeyDay, DateUtils.dayFormat(day));
// return this;
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/context/orm/AssetRepository.java
// @Setter
// public class AssetRepository extends OrmRepository {
// public static final String BeanNameDs = "assetDataSource";
// public static final String BeanNameEmf = "assetEntityManagerFactory";
// public static final String BeanNameTx = "assetTransactionManager";
//
// @PersistenceContext(unitName = BeanNameEmf)
// private EntityManager em;
//
// @Override
// public EntityManager em() {
// return em;
// }
//
// /** 資産スキーマのHibernateコンポーネントを生成します。 */
// @ConfigurationProperties(prefix = "extension.datasource.asset")
// @Data
// @EqualsAndHashCode(callSuper = false)
// public static class AssetDataSourceProperties extends OrmDataSourceProperties {
// private OrmRepositoryProperties jpa = new OrmRepositoryProperties();
//
// public DataSource dataSource() {
// return super.dataSource();
// }
//
// public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
// final DataSource dataSource) {
// return jpa.entityManagerFactoryBean(BeanNameEmf, dataSource);
// }
//
// public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
// return jpa.transactionManager(emf);
// }
// }
//
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/Cashflow.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public static class RegCashflow implements Dto {
// private static final long serialVersionUID = 1L;
// @IdStr
// private String accountId;
// @Currency
// private String currency;
// @Amount
// private BigDecimal amount;
// @NotNull
// private CashflowType cashflowType;
// @Category
// private String remark;
// /** 未設定時は営業日を設定 */
// @ISODateEmpty
// private LocalDate eventDay;
// @ISODate
// private LocalDate valueDay;
//
// public Cashflow create(final TimePoint now) {
// TimePoint eventDate = eventDay == null ? now : new TimePoint(eventDay, now.getDate());
// Cashflow m = new Cashflow();
// m.setAccountId(accountId);
// m.setCurrency(currency);
// m.setAmount(amount);
// m.setCashflowType(cashflowType);
// m.setRemark(remark);
// m.setEventDay(eventDate.getDay());
// m.setEventDate(eventDate.getDate());
// m.setValueDay(valueDay);
// m.setStatusType(ActionStatusType.Unprocessed);
// return m;
// }
// }
//
// Path: micro-asset/src/main/java/sample/microasset/model/asset/type/CashflowType.java
// public enum CashflowType {
// /** 振込入金 */
// CashIn,
// /** 振込出金 */
// CashOut,
// /** 振替入金 */
// CashTransferIn,
// /** 振替出金 */
// CashTransferOut
// }
// Path: micro-asset/src/main/java/sample/microasset/model/AssetDataFixtures.java
import java.math.BigDecimal;
import java.time.*;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.*;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import lombok.Setter;
import sample.ActionStatusType;
import sample.context.Timestamper;
import sample.microasset.context.orm.AssetRepository;
import sample.microasset.model.asset.*;
import sample.microasset.model.asset.Cashflow.RegCashflow;
import sample.microasset.model.asset.type.CashflowType;
import sample.model.BusinessDayHandler;
import sample.util.TimePoint;
package sample.microasset.model;
@Setter
public class AssetDataFixtures {
@Autowired
private Timestamper time;
@Autowired
private BusinessDayHandler businessDay;
@Autowired | private AssetRepository rep; |
terzerm/hover-raft | src/test/java/org/tools4j/hoverraft/message/direct/DirectTimeoutNowTest.java | // Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
| import org.agrona.ExpandableArrayBuffer;
import org.junit.Before;
import org.junit.Test;
import org.tools4j.hoverraft.message.MessageType;
import static org.assertj.core.api.Assertions.assertThat; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message.direct;
public class DirectTimeoutNowTest {
private final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(DirectTimeoutNow.BYTE_LENGTH);
private final DirectTimeoutNow directTimeoutNow = new DirectTimeoutNow();
@Before
public void init() {
directTimeoutNow.wrap(buffer, 0);
}
@Test
public void should_get_the_data_that_has_been_set() throws Exception {
//given
final int term = 9;
final int candidateId = 5;
//when
directTimeoutNow.term(term).candidateId(candidateId);
//then | // Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
// Path: src/test/java/org/tools4j/hoverraft/message/direct/DirectTimeoutNowTest.java
import org.agrona.ExpandableArrayBuffer;
import org.junit.Before;
import org.junit.Test;
import org.tools4j.hoverraft.message.MessageType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message.direct;
public class DirectTimeoutNowTest {
private final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer(DirectTimeoutNow.BYTE_LENGTH);
private final DirectTimeoutNow directTimeoutNow = new DirectTimeoutNow();
@Before
public void init() {
directTimeoutNow.wrap(buffer, 0);
}
@Test
public void should_get_the_data_that_has_been_set() throws Exception {
//given
final int term = 9;
final int candidateId = 5;
//when
directTimeoutNow.term(term).candidateId(candidateId);
//then | assertThat(directTimeoutNow.type()).isEqualTo(MessageType.TIMEOUT_NOW); |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/message/direct/DirectVoteResponse.java | // Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteResponse.java
// public interface VoteResponse extends Message {
//
// int term();
//
// VoteResponse term(int term);
//
// boolean voteGranted();
//
// VoteResponse voteGranted(boolean granted);
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteResponse(serverContext, this);
// }
// }
| import org.tools4j.hoverraft.message.MessageType;
import org.tools4j.hoverraft.message.VoteResponse; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message.direct;
public final class DirectVoteResponse extends AbstractDirectMessage implements VoteResponse {
private static final byte GRANTED = 1;
private static final byte DENIED = 0;
private static final int TERM_OFF = TYPE_OFF + TYPE_LEN;
private static final int TERM_LEN = 4;
private static final int GRANTED_OFF = TERM_OFF + TERM_LEN;
private static final int GRANTED_LEN = 1;
public static final int BYTE_LENGTH = GRANTED_OFF + GRANTED_LEN;
@Override | // Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteResponse.java
// public interface VoteResponse extends Message {
//
// int term();
//
// VoteResponse term(int term);
//
// boolean voteGranted();
//
// VoteResponse voteGranted(boolean granted);
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteResponse(serverContext, this);
// }
// }
// Path: src/main/java/org/tools4j/hoverraft/message/direct/DirectVoteResponse.java
import org.tools4j.hoverraft.message.MessageType;
import org.tools4j.hoverraft.message.VoteResponse;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message.direct;
public final class DirectVoteResponse extends AbstractDirectMessage implements VoteResponse {
private static final byte GRANTED = 1;
private static final byte DENIED = 0;
private static final int TERM_OFF = TYPE_OFF + TYPE_LEN;
private static final int TERM_LEN = 4;
private static final int GRANTED_OFF = TERM_OFF + TERM_LEN;
private static final int GRANTED_LEN = 1;
public static final int BYTE_LENGTH = GRANTED_OFF + GRANTED_LEN;
@Override | public MessageType type() { |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/message/MessageType.java | // Path: src/main/java/org/tools4j/hoverraft/direct/DirectFactory.java
// public interface DirectFactory {
//
// AppendRequest appendRequest();
//
// AppendResponse appendResponse();
//
// VoteRequest voteRequest();
//
// VoteResponse voteResponse();
//
// TimeoutNow timeoutNow();
//
// CommandKey commandKey();
//
// Command command();
//
// LogEntry logEntry();
// }
| import org.agrona.DirectBuffer;
import org.tools4j.hoverraft.direct.DirectFactory; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message;
public enum MessageType {
VOTE_REQUEST {
@Override | // Path: src/main/java/org/tools4j/hoverraft/direct/DirectFactory.java
// public interface DirectFactory {
//
// AppendRequest appendRequest();
//
// AppendResponse appendResponse();
//
// VoteRequest voteRequest();
//
// VoteResponse voteResponse();
//
// TimeoutNow timeoutNow();
//
// CommandKey commandKey();
//
// Command command();
//
// LogEntry logEntry();
// }
// Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
import org.agrona.DirectBuffer;
import org.tools4j.hoverraft.direct.DirectFactory;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.message;
public enum MessageType {
VOTE_REQUEST {
@Override | public Message create(final DirectFactory factory) { |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/transport/chronicle/ChronicleReceiver.java | // Path: src/main/java/org/tools4j/hoverraft/direct/DirectFactory.java
// public interface DirectFactory {
//
// AppendRequest appendRequest();
//
// AppendResponse appendResponse();
//
// VoteRequest voteRequest();
//
// VoteResponse voteResponse();
//
// TimeoutNow timeoutNow();
//
// CommandKey commandKey();
//
// Command command();
//
// LogEntry logEntry();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/Message.java
// public interface Message extends DirectPayload, Event {
//
// MessageType type();
//
// default void sendTo(final Sender<? super Message> sender, final ResendStrategy resendStrategy) {
// final long res = sender.offer(this);
// if (res < 0) {
// resendStrategy.onRejectedOffer(sender, this, res);
// }
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/transport/Receiver.java
// public interface Receiver<M extends DirectPayload> {
// /**
// * Polls messages in non-blocking mode. Messages are passed to the specified
// * message event.
// *
// * @param messageMandler the event invoked for each message
// * @param limit maximum number of messages to receive
// * @return number of messages received, zero to at most {@code limit} messages
// */
// int poll(Consumer<? super M> messageMandler, int limit);
// }
| import java.util.Objects;
import java.util.function.Consumer;
import net.openhft.chronicle.ExcerptTailer;
import org.agrona.MutableDirectBuffer;
import org.tools4j.hoverraft.direct.DirectFactory;
import org.tools4j.hoverraft.message.Message;
import org.tools4j.hoverraft.message.MessageType;
import org.tools4j.hoverraft.transport.Receiver; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.transport.chronicle;
/**
* Subscription reading from a chronicle queue.
*/
public class ChronicleReceiver implements Receiver<Message> {
private final DirectFactory directFactory;
private final MutableDirectBuffer mutableDirectBuffer;
private final ExcerptTailer tailer;
public ChronicleReceiver(final DirectFactory directFactory, final MutableDirectBuffer mutableDirectBuffer, final ExcerptTailer tailer) {
this.directFactory = Objects.requireNonNull(directFactory);
this.mutableDirectBuffer = Objects.requireNonNull(mutableDirectBuffer);
this.tailer = Objects.requireNonNull(tailer);
}
@Override
public int poll(final Consumer<? super Message> messageMandler, final int limit) {
int messagesRead = 0;
while (messagesRead < limit && tailer.nextIndex()) {
final int len = tailer.readInt();
for (int i = 0; i < len; ) {
if (i + 8 <= len) {
mutableDirectBuffer.putLong(i, tailer.readLong());
i += 8;
} else {
mutableDirectBuffer.putByte(i, tailer.readByte());
i++;
}
}
consume(messageMandler);
messagesRead++;
}
return messagesRead;
}
private void consume(final Consumer<? super Message> messageMandler) { | // Path: src/main/java/org/tools4j/hoverraft/direct/DirectFactory.java
// public interface DirectFactory {
//
// AppendRequest appendRequest();
//
// AppendResponse appendResponse();
//
// VoteRequest voteRequest();
//
// VoteResponse voteResponse();
//
// TimeoutNow timeoutNow();
//
// CommandKey commandKey();
//
// Command command();
//
// LogEntry logEntry();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/Message.java
// public interface Message extends DirectPayload, Event {
//
// MessageType type();
//
// default void sendTo(final Sender<? super Message> sender, final ResendStrategy resendStrategy) {
// final long res = sender.offer(this);
// if (res < 0) {
// resendStrategy.onRejectedOffer(sender, this, res);
// }
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/MessageType.java
// public enum MessageType {
// VOTE_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteRequest();
// }
// },
// VOTE_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.voteResponse();
// }
// },
// APPEND_REQUEST {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendRequest();
// }
// },
// APPEND_RESPONSE {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.appendResponse();
// }
// },
// TIMEOUT_NOW {
// @Override
// public Message create(final DirectFactory factory) {
// return factory.timeoutNow();
// }
// };
//
// private static final MessageType[] VALUES = values();
//
// public static final MessageType valueByOrdinal(final int ordinal) {
// return VALUES[ordinal];
// }
//
// public static final int maxOrdinal() {
// return VALUES.length - 1;
// }
//
// abstract public Message create(DirectFactory factory);
//
// public static MessageType readFrom(final DirectBuffer directBuffer, final int offset) {
// final int type = directBuffer.getInt(offset);
// if (type >= 0 & type <= MessageType.maxOrdinal()) {
// return MessageType.valueByOrdinal(type);
// }
// throw new IllegalArgumentException("Illegal message type: " + type);
// }
//
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/transport/Receiver.java
// public interface Receiver<M extends DirectPayload> {
// /**
// * Polls messages in non-blocking mode. Messages are passed to the specified
// * message event.
// *
// * @param messageMandler the event invoked for each message
// * @param limit maximum number of messages to receive
// * @return number of messages received, zero to at most {@code limit} messages
// */
// int poll(Consumer<? super M> messageMandler, int limit);
// }
// Path: src/main/java/org/tools4j/hoverraft/transport/chronicle/ChronicleReceiver.java
import java.util.Objects;
import java.util.function.Consumer;
import net.openhft.chronicle.ExcerptTailer;
import org.agrona.MutableDirectBuffer;
import org.tools4j.hoverraft.direct.DirectFactory;
import org.tools4j.hoverraft.message.Message;
import org.tools4j.hoverraft.message.MessageType;
import org.tools4j.hoverraft.transport.Receiver;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.transport.chronicle;
/**
* Subscription reading from a chronicle queue.
*/
public class ChronicleReceiver implements Receiver<Message> {
private final DirectFactory directFactory;
private final MutableDirectBuffer mutableDirectBuffer;
private final ExcerptTailer tailer;
public ChronicleReceiver(final DirectFactory directFactory, final MutableDirectBuffer mutableDirectBuffer, final ExcerptTailer tailer) {
this.directFactory = Objects.requireNonNull(directFactory);
this.mutableDirectBuffer = Objects.requireNonNull(mutableDirectBuffer);
this.tailer = Objects.requireNonNull(tailer);
}
@Override
public int poll(final Consumer<? super Message> messageMandler, final int limit) {
int messagesRead = 0;
while (messagesRead < limit && tailer.nextIndex()) {
final int len = tailer.readInt();
for (int i = 0; i < len; ) {
if (i + 8 <= len) {
mutableDirectBuffer.putLong(i, tailer.readLong());
i += 8;
} else {
mutableDirectBuffer.putByte(i, tailer.readByte());
i++;
}
}
consume(messageMandler);
messagesRead++;
}
return messagesRead;
}
private void consume(final Consumer<? super Message> messageMandler) { | final MessageType messageType = MessageType.readFrom(mutableDirectBuffer, 0); |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/event/VoteRequestHandler.java | // Path: src/main/java/org/tools4j/hoverraft/command/CommandLog.java
// public interface CommandLog {
// long size();
// default long lastIndex() {
// return size() - 1;
// }
// int readTerm(long index);
// void readTo(long index, LogKey target);
// void readTo(long index, CommandKey target);
// void readTo(long index, LogEntry target);
//
// void append(int term, Command command);
// void truncateIncluding(long index);
//
// default int lastTerm() {
// return readTerm(lastIndex());
// }
//
// default void lastKeyTo(final LogKey target) {
// readTo(lastIndex(), target);
// }
//
// default int lastKeyCompareTo(final LogKey logKey) {
// final int termCompare = Integer.compare(lastTerm(), logKey.term());
// return termCompare == 0 ? Long.compare(lastIndex(), logKey.index()) : termCompare;
// }
//
// boolean contains(CommandKey commandKey);
// default LogContainment contains(final LogKey logKey) {
// return LogContainment.containmentFor(logKey, this);
// }
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteRequest.java
// public interface VoteRequest extends Message {
//
// int term();
//
// VoteRequest term(int term);
//
// int candidateId();
//
// VoteRequest candidateId(int candidateId);
//
// LogKey lastLogKey();
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteRequest(serverContext, this);
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/server/ServerContext.java
// public interface ServerContext {
//
// ServerConfig serverConfig();
//
// ConsensusConfig consensusConfig();
//
// Connections<Message> connections();
//
// DirectFactory directFactory();
//
// StateMachine stateMachine();
//
// Timer timer();
//
// ResendStrategy resendStrategy();
//
// void perform();
//
// default int id() {
// return serverConfig().id();
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/PersistentState.java
// public interface PersistentState {
//
// int NOT_VOTED_YET = -1;
//
// int currentTerm();
//
// int votedFor();
//
// int clearVotedForAndSetCurrentTerm(int term);
//
// int clearVotedForAndIncCurrentTerm();
//
// void votedFor(final int candidateId);
//
// CommandLog commandLog();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/Transition.java
// public enum Transition implements Event {
// STEADY(null, false),
// TO_FOLLOWER(Role.FOLLOWER, true),
// TO_CANDIDATE(Role.CANDIDATE, false),
// TO_LEADER(Role.LEADER, false);
//
// private final Role targetRole;
// private final boolean replayEvent;
//
// Transition(final Role targetRole, final boolean replayEvent) {
// this.targetRole = targetRole;//nullable
// this.replayEvent = replayEvent;
// }
//
// public final Role targetRole(final Role currentRole) {
// return this == STEADY ? currentRole : targetRole;
// }
//
// public final boolean replayEvent() {
// return replayEvent;
// }
//
// @Override
// public Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onTransition(serverContext, this);
// }
//
// public static Transition startWith(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// return event.accept(serverContext, eventHandler);
// }
// public final Transition ifSteadyThen(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// if (this == STEADY) {
// return event.accept(serverContext, eventHandler);
// }
// return this;
// }
// }
| import org.tools4j.hoverraft.command.CommandLog;
import org.tools4j.hoverraft.message.VoteRequest;
import org.tools4j.hoverraft.server.ServerContext;
import org.tools4j.hoverraft.state.PersistentState;
import org.tools4j.hoverraft.state.Transition;
import java.util.Objects; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.event;
public final class VoteRequestHandler {
private final PersistentState persistentState;
public VoteRequestHandler(final PersistentState persistentState) {
this.persistentState = Objects.requireNonNull(persistentState);
}
| // Path: src/main/java/org/tools4j/hoverraft/command/CommandLog.java
// public interface CommandLog {
// long size();
// default long lastIndex() {
// return size() - 1;
// }
// int readTerm(long index);
// void readTo(long index, LogKey target);
// void readTo(long index, CommandKey target);
// void readTo(long index, LogEntry target);
//
// void append(int term, Command command);
// void truncateIncluding(long index);
//
// default int lastTerm() {
// return readTerm(lastIndex());
// }
//
// default void lastKeyTo(final LogKey target) {
// readTo(lastIndex(), target);
// }
//
// default int lastKeyCompareTo(final LogKey logKey) {
// final int termCompare = Integer.compare(lastTerm(), logKey.term());
// return termCompare == 0 ? Long.compare(lastIndex(), logKey.index()) : termCompare;
// }
//
// boolean contains(CommandKey commandKey);
// default LogContainment contains(final LogKey logKey) {
// return LogContainment.containmentFor(logKey, this);
// }
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteRequest.java
// public interface VoteRequest extends Message {
//
// int term();
//
// VoteRequest term(int term);
//
// int candidateId();
//
// VoteRequest candidateId(int candidateId);
//
// LogKey lastLogKey();
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteRequest(serverContext, this);
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/server/ServerContext.java
// public interface ServerContext {
//
// ServerConfig serverConfig();
//
// ConsensusConfig consensusConfig();
//
// Connections<Message> connections();
//
// DirectFactory directFactory();
//
// StateMachine stateMachine();
//
// Timer timer();
//
// ResendStrategy resendStrategy();
//
// void perform();
//
// default int id() {
// return serverConfig().id();
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/PersistentState.java
// public interface PersistentState {
//
// int NOT_VOTED_YET = -1;
//
// int currentTerm();
//
// int votedFor();
//
// int clearVotedForAndSetCurrentTerm(int term);
//
// int clearVotedForAndIncCurrentTerm();
//
// void votedFor(final int candidateId);
//
// CommandLog commandLog();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/Transition.java
// public enum Transition implements Event {
// STEADY(null, false),
// TO_FOLLOWER(Role.FOLLOWER, true),
// TO_CANDIDATE(Role.CANDIDATE, false),
// TO_LEADER(Role.LEADER, false);
//
// private final Role targetRole;
// private final boolean replayEvent;
//
// Transition(final Role targetRole, final boolean replayEvent) {
// this.targetRole = targetRole;//nullable
// this.replayEvent = replayEvent;
// }
//
// public final Role targetRole(final Role currentRole) {
// return this == STEADY ? currentRole : targetRole;
// }
//
// public final boolean replayEvent() {
// return replayEvent;
// }
//
// @Override
// public Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onTransition(serverContext, this);
// }
//
// public static Transition startWith(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// return event.accept(serverContext, eventHandler);
// }
// public final Transition ifSteadyThen(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// if (this == STEADY) {
// return event.accept(serverContext, eventHandler);
// }
// return this;
// }
// }
// Path: src/main/java/org/tools4j/hoverraft/event/VoteRequestHandler.java
import org.tools4j.hoverraft.command.CommandLog;
import org.tools4j.hoverraft.message.VoteRequest;
import org.tools4j.hoverraft.server.ServerContext;
import org.tools4j.hoverraft.state.PersistentState;
import org.tools4j.hoverraft.state.Transition;
import java.util.Objects;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.event;
public final class VoteRequestHandler {
private final PersistentState persistentState;
public VoteRequestHandler(final PersistentState persistentState) {
this.persistentState = Objects.requireNonNull(persistentState);
}
| public Transition onVoteRequest(final ServerContext serverContext, final VoteRequest voteRequest) { |
terzerm/hover-raft | src/main/java/org/tools4j/hoverraft/event/VoteRequestHandler.java | // Path: src/main/java/org/tools4j/hoverraft/command/CommandLog.java
// public interface CommandLog {
// long size();
// default long lastIndex() {
// return size() - 1;
// }
// int readTerm(long index);
// void readTo(long index, LogKey target);
// void readTo(long index, CommandKey target);
// void readTo(long index, LogEntry target);
//
// void append(int term, Command command);
// void truncateIncluding(long index);
//
// default int lastTerm() {
// return readTerm(lastIndex());
// }
//
// default void lastKeyTo(final LogKey target) {
// readTo(lastIndex(), target);
// }
//
// default int lastKeyCompareTo(final LogKey logKey) {
// final int termCompare = Integer.compare(lastTerm(), logKey.term());
// return termCompare == 0 ? Long.compare(lastIndex(), logKey.index()) : termCompare;
// }
//
// boolean contains(CommandKey commandKey);
// default LogContainment contains(final LogKey logKey) {
// return LogContainment.containmentFor(logKey, this);
// }
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteRequest.java
// public interface VoteRequest extends Message {
//
// int term();
//
// VoteRequest term(int term);
//
// int candidateId();
//
// VoteRequest candidateId(int candidateId);
//
// LogKey lastLogKey();
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteRequest(serverContext, this);
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/server/ServerContext.java
// public interface ServerContext {
//
// ServerConfig serverConfig();
//
// ConsensusConfig consensusConfig();
//
// Connections<Message> connections();
//
// DirectFactory directFactory();
//
// StateMachine stateMachine();
//
// Timer timer();
//
// ResendStrategy resendStrategy();
//
// void perform();
//
// default int id() {
// return serverConfig().id();
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/PersistentState.java
// public interface PersistentState {
//
// int NOT_VOTED_YET = -1;
//
// int currentTerm();
//
// int votedFor();
//
// int clearVotedForAndSetCurrentTerm(int term);
//
// int clearVotedForAndIncCurrentTerm();
//
// void votedFor(final int candidateId);
//
// CommandLog commandLog();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/Transition.java
// public enum Transition implements Event {
// STEADY(null, false),
// TO_FOLLOWER(Role.FOLLOWER, true),
// TO_CANDIDATE(Role.CANDIDATE, false),
// TO_LEADER(Role.LEADER, false);
//
// private final Role targetRole;
// private final boolean replayEvent;
//
// Transition(final Role targetRole, final boolean replayEvent) {
// this.targetRole = targetRole;//nullable
// this.replayEvent = replayEvent;
// }
//
// public final Role targetRole(final Role currentRole) {
// return this == STEADY ? currentRole : targetRole;
// }
//
// public final boolean replayEvent() {
// return replayEvent;
// }
//
// @Override
// public Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onTransition(serverContext, this);
// }
//
// public static Transition startWith(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// return event.accept(serverContext, eventHandler);
// }
// public final Transition ifSteadyThen(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// if (this == STEADY) {
// return event.accept(serverContext, eventHandler);
// }
// return this;
// }
// }
| import org.tools4j.hoverraft.command.CommandLog;
import org.tools4j.hoverraft.message.VoteRequest;
import org.tools4j.hoverraft.server.ServerContext;
import org.tools4j.hoverraft.state.PersistentState;
import org.tools4j.hoverraft.state.Transition;
import java.util.Objects; | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.event;
public final class VoteRequestHandler {
private final PersistentState persistentState;
public VoteRequestHandler(final PersistentState persistentState) {
this.persistentState = Objects.requireNonNull(persistentState);
}
| // Path: src/main/java/org/tools4j/hoverraft/command/CommandLog.java
// public interface CommandLog {
// long size();
// default long lastIndex() {
// return size() - 1;
// }
// int readTerm(long index);
// void readTo(long index, LogKey target);
// void readTo(long index, CommandKey target);
// void readTo(long index, LogEntry target);
//
// void append(int term, Command command);
// void truncateIncluding(long index);
//
// default int lastTerm() {
// return readTerm(lastIndex());
// }
//
// default void lastKeyTo(final LogKey target) {
// readTo(lastIndex(), target);
// }
//
// default int lastKeyCompareTo(final LogKey logKey) {
// final int termCompare = Integer.compare(lastTerm(), logKey.term());
// return termCompare == 0 ? Long.compare(lastIndex(), logKey.index()) : termCompare;
// }
//
// boolean contains(CommandKey commandKey);
// default LogContainment contains(final LogKey logKey) {
// return LogContainment.containmentFor(logKey, this);
// }
//
// }
//
// Path: src/main/java/org/tools4j/hoverraft/message/VoteRequest.java
// public interface VoteRequest extends Message {
//
// int term();
//
// VoteRequest term(int term);
//
// int candidateId();
//
// VoteRequest candidateId(int candidateId);
//
// LogKey lastLogKey();
//
// @Override
// default Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onVoteRequest(serverContext, this);
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/server/ServerContext.java
// public interface ServerContext {
//
// ServerConfig serverConfig();
//
// ConsensusConfig consensusConfig();
//
// Connections<Message> connections();
//
// DirectFactory directFactory();
//
// StateMachine stateMachine();
//
// Timer timer();
//
// ResendStrategy resendStrategy();
//
// void perform();
//
// default int id() {
// return serverConfig().id();
// }
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/PersistentState.java
// public interface PersistentState {
//
// int NOT_VOTED_YET = -1;
//
// int currentTerm();
//
// int votedFor();
//
// int clearVotedForAndSetCurrentTerm(int term);
//
// int clearVotedForAndIncCurrentTerm();
//
// void votedFor(final int candidateId);
//
// CommandLog commandLog();
// }
//
// Path: src/main/java/org/tools4j/hoverraft/state/Transition.java
// public enum Transition implements Event {
// STEADY(null, false),
// TO_FOLLOWER(Role.FOLLOWER, true),
// TO_CANDIDATE(Role.CANDIDATE, false),
// TO_LEADER(Role.LEADER, false);
//
// private final Role targetRole;
// private final boolean replayEvent;
//
// Transition(final Role targetRole, final boolean replayEvent) {
// this.targetRole = targetRole;//nullable
// this.replayEvent = replayEvent;
// }
//
// public final Role targetRole(final Role currentRole) {
// return this == STEADY ? currentRole : targetRole;
// }
//
// public final boolean replayEvent() {
// return replayEvent;
// }
//
// @Override
// public Transition accept(final ServerContext serverContext, final EventHandler eventHandler) {
// return eventHandler.onTransition(serverContext, this);
// }
//
// public static Transition startWith(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// return event.accept(serverContext, eventHandler);
// }
// public final Transition ifSteadyThen(final ServerContext serverContext, final Event event, final EventHandler eventHandler) {
// if (this == STEADY) {
// return event.accept(serverContext, eventHandler);
// }
// return this;
// }
// }
// Path: src/main/java/org/tools4j/hoverraft/event/VoteRequestHandler.java
import org.tools4j.hoverraft.command.CommandLog;
import org.tools4j.hoverraft.message.VoteRequest;
import org.tools4j.hoverraft.server.ServerContext;
import org.tools4j.hoverraft.state.PersistentState;
import org.tools4j.hoverraft.state.Transition;
import java.util.Objects;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 hover-raft (tools4j), Marco Terzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.hoverraft.event;
public final class VoteRequestHandler {
private final PersistentState persistentState;
public VoteRequestHandler(final PersistentState persistentState) {
this.persistentState = Objects.requireNonNull(persistentState);
}
| public Transition onVoteRequest(final ServerContext serverContext, final VoteRequest voteRequest) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.