repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services/src/main/java/com/acmeair/service/ServiceLocator.java | acmeair-services/src/main/java/com/acmeair/service/ServiceLocator.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.service;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.PostConstruct;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class ServiceLocator {
public static String REPOSITORY_LOOKUP_KEY = "com.acmeair.repository.type";
private static String serviceType;
private static Logger logger = Logger.getLogger(ServiceLocator.class.getName());
private static AtomicReference<ServiceLocator> singletonServiceLocator = new AtomicReference<ServiceLocator>();
@Inject
BeanManager beanManager;
public static ServiceLocator instance() {
if (singletonServiceLocator.get() == null) {
synchronized (singletonServiceLocator) {
if (singletonServiceLocator.get() == null) {
singletonServiceLocator.set(new ServiceLocator());
}
}
}
return singletonServiceLocator.get();
}
@PostConstruct
private void initialization() {
if(beanManager == null){
logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager");
try {
beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
} catch (NamingException e) {
logger.severe("BeanManager not found at java:comp/BeanManager");
}
}
if(beanManager == null){
logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager");
try {
beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager");
} catch (NamingException e) {
logger.severe("BeanManager not found at java:comp/env/BeanManager ");
}
}
}
public static void updateService(String serviceName){
logger.info("Service Locator updating service to : " + serviceName);
serviceType = serviceName;
}
private ServiceLocator() {
String type = null;
String lookup = REPOSITORY_LOOKUP_KEY.replace('.', '/');
javax.naming.Context context = null;
javax.naming.Context envContext = null;
try {
context = new javax.naming.InitialContext();
envContext = (javax.naming.Context) context.lookup("java:comp/env");
if (envContext != null)
type = (String) envContext.lookup(lookup);
} catch (NamingException e) {
// e.printStackTrace();
}
if (type != null) {
logger.info("Found repository in web.xml:" + type);
}
else if (context != null) {
try {
type = (String) context.lookup(lookup);
if (type != null)
logger.info("Found repository in server.xml:" + type);
} catch (NamingException e) {
// e.printStackTrace();
}
}
if (type == null) {
type = System.getProperty(REPOSITORY_LOOKUP_KEY);
if (type != null)
logger.info("Found repository in jvm property:" + type);
else {
type = System.getenv(REPOSITORY_LOOKUP_KEY);
if (type != null)
logger.info("Found repository in environment property:" + type);
}
}
if(beanManager == null) {
logger.info("Attempting to look up BeanManager through JNDI at java:comp/BeanManager");
try {
beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
} catch (NamingException e) {
logger.severe("BeanManager not found at java:comp/BeanManager");
}
}
if(beanManager == null){
logger.info("Attempting to look up BeanManager through JNDI at java:comp/env/BeanManager");
try {
beanManager = (BeanManager) new InitialContext().lookup("java:comp/env/BeanManager");
} catch (NamingException e) {
logger.severe("BeanManager not found at java:comp/env/BeanManager ");
}
}
if (type==null)
{
String vcapJSONString = System.getenv("VCAP_SERVICES");
if (vcapJSONString != null) {
logger.info("Reading VCAP_SERVICES");
Object jsonObject = JSONValue.parse(vcapJSONString);
logger.fine("jsonObject = " + ((JSONObject)jsonObject).toJSONString());
JSONObject json = (JSONObject)jsonObject;
String key;
for (Object k: json.keySet())
{
key = (String ) k;
if (key.startsWith("ElasticCaching")||key.startsWith("DataCache"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="wxs";
break;
}
if (key.startsWith("mongo"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="morphia";
break;
}
if (key.startsWith("redis"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="redis";
break;
}
if (key.startsWith("mysql")|| key.startsWith("cleardb"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="mysql";
break;
}
if (key.startsWith("postgresql"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="postgresql";
break;
}
if (key.startsWith("db2"))
{
logger.info("VCAP_SERVICES existed with service:"+key);
type ="db2";
break;
}
}
}
}
serviceType = type;
logger.info("ServiceType is now : " + serviceType);
if (type ==null) {
logger.warning("Can not determine type. Use default service implementation.");
}
}
@SuppressWarnings("unchecked")
public <T> T getService (Class<T> clazz) {
logger.fine("Looking up service: "+clazz.getName() + " with service type: " + serviceType);
if(beanManager == null) {
logger.severe("BeanManager is null!!!");
}
Set<Bean<?>> beans = beanManager.getBeans(clazz,new AnnotationLiteral<Any>() {
private static final long serialVersionUID = 1L;});
for (Bean<?> bean : beans) {
logger.fine(" Bean = "+bean.getBeanClass().getName());
for (Annotation qualifer: bean.getQualifiers()) {
if(null == serviceType) {
logger.warning("Service type is not set, searching for the default implementation.");
if(Default.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
return (T) beanManager.getReference(bean, clazz, ctx);
}
} else {
if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
DataService service = (DataService) qualifer;
logger.fine(" name="+service.name()+" description="+service.description());
if(serviceType.equalsIgnoreCase(service.name())) {
CreationalContext<?> ctx = beanManager.createCreationalContext(bean);
return (T) beanManager.getReference(bean, clazz, ctx);
}
}
}
}
}
logger.warning("No Service of type: " + serviceType + " found for "+clazz.getName()+" ");
return null;
}
/**
* Retrieves the services that are available for use with the description for each service.
* The Services are determined by looking up all of the implementations of the
* Customer Service interface that are using the DataService qualifier annotation.
* The DataService annotation contains the service name and description information.
* @return Map containing a list of services available and a description of each one.
*/
public Map<String,String> getServices (){
TreeMap<String,String> services = new TreeMap<String,String>();
logger.fine("Getting CustomerService Impls");
Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() {
private static final long serialVersionUID = 1L;});
for (Bean<?> bean : beans) {
for (Annotation qualifer: bean.getQualifiers()){
if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
DataService service = (DataService) qualifer;
logger.fine(" name="+service.name()+" description="+service.description());
services.put(service.name(), service.description());
}
}
}
return services;
}
/**
* The type of service implementation that the application is
* currently configured to use.
*
* @return The type of service in use, or "default" if no service has been set.
*/
public String getServiceType (){
if(serviceType == null){
return "default";
}
return serviceType;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/ReportGenerator.java | acmeair-reporter/src/main/java/com/acmeair/reporter/ReportGenerator.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.tools.generic.ComparisonDateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.apache.velocity.tools.generic.NumberTool;
import com.acmeair.reporter.util.Messages;
import com.acmeair.reporter.util.StatResult;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
import com.acmeair.reporter.parser.component.JmeterJTLParser;
import com.acmeair.reporter.parser.component.JmeterSummariserParser;
import com.acmeair.reporter.parser.component.JtlTotals;
import com.acmeair.reporter.parser.component.NmonParser;
//import freemarker.cache.ClassTemplateLoader;
//import freemarker.template.Configuration;
//import freemarker.template.Template;
public class ReportGenerator {
private static final int max_lines = 15;
private static final String RESULTS_FILE = Messages.getString("ReportGenerator.RESULT_FILE_NAME");
private static String searchingLocation = Messages.getString("inputDirectory");
private static String jmeterFileName = Messages.getString("ReportGenerator.DEFAULT_JMETER_FILENAME");
private static String nmonFileName = Messages.getString("ReportGenerator.DEFAULT_NMON_FILE_NAME");
private static final String BOOK_FLIGHT = "BookFlight";
private static final String CANCEL_BOOKING = "Cancel Booking";
private static final String LOGIN = "Login";
private static final String LOGOUT = "logout";
private static final String LIST_BOOKINGS = "List Bookings";
private static final String QUERY_FLIGHT = "QueryFlight";
private static final String UPDATE_CUSTOMER = "Update Customer";
private static final String VIEW_PROFILE = "View Profile Information";
private LinkedHashMap<String,ArrayList<String>> charMap = new LinkedHashMap<String,ArrayList<String>>();
public static void main(String[] args) {
if (args.length == 1) {
searchingLocation = (args[0]);
}
if (!new File(searchingLocation).isDirectory()) {
System.out.println("\"" + searchingLocation + "\" is not a valid directory");
return;
}
System.out.println("Parsing acme air test results in the location \"" + searchingLocation + "\"");
ReportGenerator generator = new ReportGenerator();
long start, stop;
start = System.currentTimeMillis();
generator.process();
stop = System.currentTimeMillis();
System.out.println("Results generated in " + (stop - start)/1000.0 + " seconds");
}
public void process() {
long start, stop;
String overallChartTitle = Messages.getString("ReportGenerator.THROUGHPUT_TOTAL_LABEL");
String throughputChartTitle = Messages.getString("ReportGenerator.THROUGHPUT_TITLE");
String yAxisLabel = Messages.getString("ReportGenerator.THROUGHPUT_YAXIS_LABEL");
Map<String, Object> input = new HashMap<String, Object>();
start = System.currentTimeMillis();
JmeterSummariserParser jmeterParser = new JmeterSummariserParser();
jmeterParser.setFileName(jmeterFileName);
jmeterParser.setMultipleChartTitle(throughputChartTitle);
jmeterParser.setMultipleYAxisLabel(yAxisLabel);
jmeterParser.processDirectory(searchingLocation);
//always call it before call generating multiple chart string
String url = jmeterParser.generateChartStrings(overallChartTitle, yAxisLabel,
"", jmeterParser.processData(jmeterParser.getAllInputList(), true),
ResultParserHelper.scaleDown(jmeterParser.getAllTimeList(), 3), false);
ArrayList<String> list = new ArrayList<String>();
list.add(url);
charMap.put(overallChartTitle, list);
generateMulitpleLinesChart(jmeterParser);
charMap.put(throughputChartTitle, jmeterParser.getCharStrings());
StatResult jmeterStats = StatResult.getStatistics(jmeterParser.getAllInputList());
input.put("jmeterStats", jmeterStats);
if(!jmeterParser.getAllTimeList().isEmpty()){
input.put("testStart", jmeterParser.getTestDate() + " " + jmeterParser.getAllTimeList().get(0));
input.put("testEnd", jmeterParser.getTestDate() + " " + jmeterParser.getAllTimeList().get(jmeterParser.getAllTimeList().size()-1));
}
input.put("charUrlMap", charMap);
stop = System.currentTimeMillis();
System.out.println("Parsed jmeter in " + (stop - start)/1000.0 + " seconds");
start = System.currentTimeMillis();
JmeterJTLParser jtlParser = new JmeterJTLParser();
jtlParser.processResultsDirectory(searchingLocation);
input.put("totals", jtlParser.getResults());
String urls[] = {BOOK_FLIGHT,CANCEL_BOOKING,LOGIN,LOGOUT,LIST_BOOKINGS,QUERY_FLIGHT,UPDATE_CUSTOMER,VIEW_PROFILE,"Authorization"};
input.put("totalUrlMap" ,reorderTestcases(jtlParser.getResultsByUrl(), urls));
input.put("queryTotals", getTotals(QUERY_FLIGHT, jtlParser.getResultsByUrl()));
input.put("bookingTotals", getTotals(BOOK_FLIGHT, jtlParser.getResultsByUrl()));
input.put("loginTotals", getTotals(LOGIN, jtlParser.getResultsByUrl()));
stop = System.currentTimeMillis();
System.out.println("Parsed jmeter jtl files in " + (stop - start)/1000.0 + " seconds");
List<Object> nmonParsers = Messages.getConfiguration().getList("parsers.nmonParser.directory");
if (nmonParsers != null){
LinkedHashMap<String,StatResult> cpuList = new LinkedHashMap<String,StatResult>();
start = System.currentTimeMillis();
for(int i = 0;i < nmonParsers.size(); i++) {
String enabled = Messages.getString("parsers.nmonParser("+i+")[@enabled]");
if (enabled == null || !enabled.equalsIgnoreCase("false")) {
String directory = Messages.getString("parsers.nmonParser("+i+").directory");
String chartTitle = Messages.getString("parsers.nmonParser("+i+").chartTitle");
String label = Messages.getString("parsers.nmonParser("+i+").label");
String fileName = Messages.getString("parsers.nmonParser("+i+").fileName");
String relativePath = Messages.getString("parsers.nmonParser("+i+").directory[@relative]");
if (relativePath == null || !relativePath.equalsIgnoreCase("false")) {
directory = searchingLocation +"/" + directory;
}
if (fileName == null){
fileName = nmonFileName;
}
NmonParser nmon = parseNmonDirectory(directory, fileName, chartTitle);
cpuList = addCpuStats(nmon, label, cpuList);
}
}
input.put("cpuList", cpuList);
stop = System.currentTimeMillis();
System.out.println("Parsed nmon files in " + (stop - start)/1000.0 + " seconds");
}
if (charMap.size() > 0) {
start = System.currentTimeMillis();
generateHtmlfile(input);
stop = System.currentTimeMillis();
System.out.println("Generated html file in " + (stop - start)/1000.0 + " seconds");
System.out.println("Done, charts were saved to \""
+ searchingLocation + System.getProperty("file.separator") + RESULTS_FILE + "\"");
} else {
System.out.println("Failed, cannot find valid \""
+ jmeterFileName + "\" or \"" + nmonFileName + "\" files in location " + searchingLocation);
}
}
private void generateMulitpleLinesChart(ResultParser parser) {
if (parser.getResults().size()<=max_lines){
parser.generateMultipleLinesCharString(parser.getMultipleChartTitle(),
parser.getMultipleYAxisLabel(), "", parser.getResults());
}else {
System.out.println("More than "+max_lines+" throughput files found, will break them to "+max_lines+" each");
ArrayList<IndividualChartResults> results= parser.getResults();
int size = results.size();
for (int i=0;i<size;i=i+max_lines){
int endLocation = i+max_lines;
if (endLocation >size) {
endLocation=size;
}
parser.generateMultipleLinesCharString(parser.getMultipleChartTitle(),
parser.getMultipleYAxisLabel(), "", results.subList(i,endLocation));
}
}
}
private ArrayList<Double> getCombinedResultsList (NmonParser parser){
Iterator<IndividualChartResults> itr = parser.getMultipleChartResults().getResults().iterator();
ArrayList<Double> resultList = new ArrayList<Double>();
while(itr.hasNext()){
//trim trailing idle times from each of the individual results,
//then combine the results together to get the final tallies.
ArrayList<Double> curList = itr.next().getInputList();
for(int j = curList.size() - 1; j >= 0; j--){
if (curList.get(j).doubleValue() < 1){
curList.remove(j);
}
}
resultList.addAll(curList);
}
return resultList;
}
/*
private void generateHtmlfile(Map<String, Object> input) {
try{
Configuration cfg = new Configuration();
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/templates");
cfg.setTemplateLoader(ctl);
Template template = cfg.getTemplate("acmeair-report.ftl");
Writer file = new FileWriter(new File(searchingLocation
+ System.getProperty("file.separator") + RESULTS_FILE));
template.process(input, file);
file.flush();
file.close();
}catch(Exception e){
e.printStackTrace();
}
}
*/
private void generateHtmlfile(Map<String, Object> input) {
try{
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());
ve.init();
Template template = ve.getTemplate("templates/acmeair-report.vtl");
VelocityContext context = new VelocityContext();
for(Map.Entry<String, Object> entry: input.entrySet()){
context.put(entry.getKey(), entry.getValue());
}
context.put("math", new MathTool());
context.put("number", new NumberTool());
context.put("date", new ComparisonDateTool());
Writer file = new FileWriter(new File(searchingLocation
+ System.getProperty("file.separator") + RESULTS_FILE));
template.merge( context, file );
file.flush();
file.close();
}catch(Exception e){
e.printStackTrace();
}
}
private LinkedHashMap<String,StatResult> addCpuStats(NmonParser parser, String label, LinkedHashMap<String,StatResult> toAdd){
if (parser != null) {
StatResult cpuStats = StatResult.getStatistics(getCombinedResultsList(parser));
cpuStats.setNumberOfResults(parser.getMultipleChartResults().getResults().size());
toAdd.put(label, cpuStats);
}else {
System.out.println("no "+label+" cpu data found");
}
return toAdd;
}
/**
* Re-orders a given map to using an array of Strings.
* Any remaining items in the map that was passed in will be appended to the end of
* the map to be returned.
* @param totalUrlMap the map to be re-ordered.
* @param urls An array of Strings with the desired order for the map keys.
* @return A LinkedHashMap with the keys in the order requested.
* @see LinkedHashMap
*/
private Map<String,JtlTotals> reorderTestcases(Map<String,JtlTotals> totalUrlMap, String urls[]){
LinkedHashMap<String,JtlTotals> newMap = new LinkedHashMap<String,JtlTotals>();
Iterator<String> keys;
for(int i=0; i< urls.length;i++){
keys = totalUrlMap.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
if(key.toLowerCase().contains(urls[i].toLowerCase())){
newMap.put(key, totalUrlMap.get(key));
}
}
}
//loop 2nd time to get the remaining items
keys = totalUrlMap.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
boolean found = false;
for(int i=0; i< urls.length;i++){
if(key.toLowerCase().contains(urls[i].toLowerCase())){
found = true;
}
}
if(!found){
newMap.put(key, totalUrlMap.get(key));
}
}
return newMap;
}
/**
* Searches the map for the given jmeter testcase url key.
* The passed in string is expected to contain all or part of the desired key.
* for example "QueryFlight" could match both "Mobile QueryFlight" and "Desktop QueryFlight" or just "QueryFlight".
* If multiple results are found, their totals are added togehter in the JtlTotals Object returned.
*
* @param url String, jMeter Testcase URL string to search for.
* @param totalUrlMap Map containing Strings and JtlTotals results.
* @return JtlTotals object.
* @see JtlTotals
*/
private JtlTotals getTotals(String url, Map<String,JtlTotals> totalUrlMap){
JtlTotals urlTotals = null;
Iterator<String> keys = totalUrlMap.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
if(key.toLowerCase().contains(url.toLowerCase())){
if(urlTotals == null){
urlTotals = totalUrlMap.get(key);
}else {
urlTotals.add(totalUrlMap.get(key));
}
}
}
return urlTotals;
}
/**
* Sets up a new NmonParser Object for parsing a given directory.
* @param directory directory to search for nmon files.
* @param chartTitle Name of the title for the chart to be generated.
* @return NmonParser object
*/
private NmonParser parseNmonDirectory (String directory, String fileName, String chartTitle ){
if (!new File(directory).isDirectory()) {
return null;
}
NmonParser parser = new NmonParser();
parser.setFileName(fileName);
parser.setMultipleChartTitle(chartTitle);
parser.processDirectory(directory);
generateMulitpleLinesChart(parser);
charMap.put(chartTitle, parser.getCharStrings());
return parser;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/util/StatResult.java | acmeair-reporter/src/main/java/com/acmeair/reporter/util/StatResult.java | package com.acmeair.reporter.util;
import java.util.ArrayList;
public class StatResult {
public double min;
public double max;
public double average;
public int count;
public double sum;
public double numberOfResults;
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public double getNumberOfResults() {
return numberOfResults;
}
public void setNumberOfResults(double numberOfResults) {
this.numberOfResults = numberOfResults;
}
public static StatResult getStatistics(ArrayList <Double> list){
StatResult result = new StatResult();
result.average = 0;
result.sum = 0;
if (list.size()>1)
result.min = list.get(1);
result.max = 0;
result.count = 0;
for (int i = 0; i< list.size();i++){
double current = list.get(i).doubleValue();
if(i > 0 && i < list.size()-1){
result.sum += current;
result.count ++;
result.min = Math.min(result.min, current);
result.max = Math.max(result.max, current);
}
}
if(result.count > 0 && result.sum > 0)
result.average = (result.sum/result.count);
return result;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/util/Messages.java | acmeair-reporter/src/main/java/com/acmeair/reporter/util/Messages.java | package com.acmeair.reporter.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SystemConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
public class Messages {
static ResourceBundle RESOURCE_BUNDLE;
static CompositeConfiguration config;
static {
try {
config = new CompositeConfiguration();
config.addConfiguration(new SystemConfiguration());
config.addConfiguration(new PropertiesConfiguration("messages.properties"));
config.addConfiguration(new XMLConfiguration("config.xml"));
} catch (Exception e) {
System.out.println(e);
}
}
private Messages() {
}
public static String getString(String key) {
try {
return config.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public static Configuration getConfiguration(){
return config;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/MultipleChartResults.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/MultipleChartResults.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser;
import java.util.ArrayList;
public class MultipleChartResults {
private String multipleChartTitle;
private String multipleChartYAxisLabel;
private ArrayList<IndividualChartResults> results = new ArrayList<IndividualChartResults> ();
private ArrayList<String> charStrings= new ArrayList<String>();
public String getMultipleChartTitle() {
return multipleChartTitle;
}
public void setMultipleChartTitle(String multipleChartTitle) {
this.multipleChartTitle = multipleChartTitle;
}
public String getMultipleChartYAxisLabel() {
return multipleChartYAxisLabel;
}
public void setMultipleChartYAxisLabel(String multipleChartYAxisLabel) {
this.multipleChartYAxisLabel = multipleChartYAxisLabel;
}
public ArrayList<IndividualChartResults> getResults() {
return results;
}
public void setResults(ArrayList<IndividualChartResults> results) {
this.results = results;
}
public ArrayList<String> getCharStrings() {
return charStrings;
}
public void setCharStrings(ArrayList<String> charStrings) {
this.charStrings = charStrings;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/OverallResults.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/OverallResults.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser;
import java.util.ArrayList;
public class OverallResults {
private ArrayList<Double> allInputList = new ArrayList<Double>();
private ArrayList<String> allTimeList = new ArrayList<String>();
private double scale_max;
private double overallScale_max;
public ArrayList<Double> getAllInputList() {
return allInputList;
}
public void setAllInputList(ArrayList<Double> allInputList) {
this.allInputList = new ArrayList<Double> (allInputList);
}
public ArrayList<String> getAllTimeList() {
return allTimeList;
}
public void setAllTimeList(ArrayList<String> allTimeList) {
this.allTimeList = new ArrayList<String> (allTimeList);
}
public double getOverallScale_max() {
return overallScale_max;
}
public void setOverallScale_max(double overallScale_max) {
this.overallScale_max = overallScale_max;
}
public double getScale_max() {
return scale_max;
}
public void setScale_max(double scale_max) {
this.scale_max = scale_max;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser;
import java.util.ArrayList;
import com.googlecode.charts4j.Color;
public class ResultParserHelper {
public static Color getColor(int i) {
Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
return colors[i % 15];
}
public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
if (testList==null) {
return null;
}
if (testList.size() <= 7)
return testList;
if (scaleDownFactor > 10 || scaleDownFactor < 0) {
throw new RuntimeException(
"currently only support factor from 0-10");
}
int listLastItemIndex = testList.size() - 1;
int a = (int) java.lang.Math.pow(2, scaleDownFactor);
if (a > listLastItemIndex) {
return testList;
}
ArrayList<E> newList = new ArrayList<E>();
newList.add(testList.get(0));
if (scaleDownFactor == 0) {
newList.add(testList.get(listLastItemIndex));
} else {
for (int m = 1; m <= a; m++) {
newList.add(testList.get(listLastItemIndex * m / a));
}
}
return newList;
}
public static double[] scaleInputsData(ArrayList<Double> inputList,
double scale_factor) {
double[] inputs = new double[inputList.size()];
for (int i = 0; i <= inputList.size() - 1; i++) {
inputs[i] = inputList.get(i) * scale_factor;
}
return inputs;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParser.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParser.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser;
import static com.googlecode.charts4j.Color.ALICEBLUE;
import static com.googlecode.charts4j.Color.BLACK;
import static com.googlecode.charts4j.Color.LAVENDER;
import static com.googlecode.charts4j.Color.WHITE;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import com.acmeair.reporter.parser.component.NmonParser;
import com.googlecode.charts4j.AxisLabels;
import com.googlecode.charts4j.AxisLabelsFactory;
import com.googlecode.charts4j.AxisStyle;
import com.googlecode.charts4j.AxisTextAlignment;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.DataEncoding;
import com.googlecode.charts4j.Fills;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Line;
import com.googlecode.charts4j.LineChart;
import com.googlecode.charts4j.LineStyle;
import com.googlecode.charts4j.LinearGradientFill;
import com.googlecode.charts4j.Plots;
import com.googlecode.charts4j.Shape;
public abstract class ResultParser {
protected MultipleChartResults multipleChartResults = new MultipleChartResults();
protected OverallResults overallResults = new OverallResults();
public MultipleChartResults getMultipleChartResults() {
return multipleChartResults;
}
protected void addUp(ArrayList<Double> list) {
//if empty, don't need to add up
if (overallResults.getAllInputList().isEmpty()) {
overallResults.setAllInputList(list);
return;
}
int size = overallResults.getAllInputList().size();
if (size > list.size()) {
size = list.size();
}
for (int i = 0; i < size; i++) {
overallResults.getAllInputList().set(i, overallResults.getAllInputList().get(i) + list.get(i));
}
}
public void processDirectory(String dirName) {
File root = new File(dirName);
try {
Collection<File> files = FileUtils.listFiles(root,
new RegexFileFilter(getFileName()),
DirectoryFileFilter.DIRECTORY);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
processFile(file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String generateChartStrings(String titileLabel, String ylabel,
String xlable, double[] inputs, ArrayList<String> timeList, boolean addToList) {
if (inputs == null || inputs.length == 0)
return null;
Line line1 = Plots.newLine(Data.newData(inputs),
Color.newColor("CA3D05"), "");
line1.setLineStyle(LineStyle.newLineStyle(2, 1, 0));
line1.addShapeMarkers(Shape.DIAMOND, Color.newColor("CA3D05"), 6);
LineChart chart = GCharts.newLineChart(line1);
// Defining axis info and styles
chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0,
overallResults.getScale_max() / 0.9));
if (timeList != null && timeList.size() > 0) {
chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(timeList));
}
String url = generateDefaultChartSettings(titileLabel, ylabel, xlable,
chart, addToList);
return url;
}
public String generateDefaultChartSettings(String titileLabel,
String ylabel, String xlable, LineChart chart, boolean addToList) {
AxisStyle axisStyle = AxisStyle.newAxisStyle(BLACK, 13,
AxisTextAlignment.CENTER);
AxisLabels yAxisLabel = AxisLabelsFactory.newAxisLabels(ylabel, 50.0);
yAxisLabel.setAxisStyle(axisStyle);
AxisLabels time = AxisLabelsFactory.newAxisLabels(xlable, 50.0);
time.setAxisStyle(axisStyle);
chart.addYAxisLabels(yAxisLabel);
chart.addXAxisLabels(time);
chart.setDataEncoding(DataEncoding.SIMPLE);
chart.setSize(1000, 300);
chart.setTitle(titileLabel, BLACK, 16);
chart.setGrid(100, 10, 3, 2);
chart.setBackgroundFill(Fills.newSolidFill(ALICEBLUE));
LinearGradientFill fill = Fills.newLinearGradientFill(0, LAVENDER, 100);
fill.addColorAndOffset(WHITE, 0);
chart.setAreaFill(fill);
String url = chart.toURLString();
if(addToList) {
getCharStrings().add(url);
}
return url;
}
public String generateMultipleLinesCharString(String titileLabel,
String ylabel, String xlabel, List<IndividualChartResults> list) {
if (list ==null || list.size()==0) {
return null;
}
Line[] lines = new Line[list.size()];
for (int i = 0; i < list.size(); i++) {
double[] multiLineData = processMultiLineData(list.get(i).getInputList());
if (multiLineData!=null) {
lines[i] = Plots.newLine(Data.newData(multiLineData), ResultParserHelper.getColor(i), list.get(i).getTitle());
lines[i].setLineStyle(LineStyle.newLineStyle(2, 1, 0));
} else {
System.out.println("found jmeter log file that doesn't have data:\" " + list.get(i).getTitle() +"\" skipping!");
return null;
}
}
LineChart chart = GCharts.newLineChart(lines);
chart.addYAxisLabels(AxisLabelsFactory.newNumericRangeAxisLabels(0,
overallResults.getOverallScale_max() / 0.9));
chart.addXAxisLabels(AxisLabelsFactory.newAxisLabels(list.get(0)
.getTimeList()));
// Defining axis info and styles
String url = generateDefaultChartSettings(titileLabel, ylabel, xlabel,
chart, true);
return url;
}
public ArrayList<Double> getAllInputList() {
return overallResults.getAllInputList();
}
public ArrayList<String> getAllTimeList() {
return overallResults.getAllTimeList();
}
public ArrayList<String> getCharStrings() {
return getMultipleChartResults().getCharStrings();
}
protected <E> IndividualChartResults getData(String fileName) {
IndividualChartResults results = new IndividualChartResults();
try {
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
processLine(results, strLine);
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
addUp(results.getInputList());
overallResults.setAllTimeList(results.getTimeList());
return results;
}
public abstract String getFileName();
public abstract void setFileName(String fileName);
public ArrayList<IndividualChartResults> getResults() {
return getMultipleChartResults().getResults();
}
public double[] processData(ArrayList<Double> inputList, boolean isTotalThroughput) {
if (inputList != null && inputList.size() > 0) {
if (this instanceof NmonParser) {
overallResults.setScale_max(90.0);
} else {
overallResults.setScale_max(Collections.max(inputList));
}
if (overallResults.getOverallScale_max() < overallResults.getScale_max() && !isTotalThroughput) {
overallResults.setOverallScale_max( overallResults.getScale_max());
}
double scale_factor = 90 / overallResults.getScale_max();
return ResultParserHelper.scaleInputsData(inputList, scale_factor);
}
return null;
}
protected abstract void processFile(File file);
protected abstract void processLine(IndividualChartResults result, String strLine);
public double[] processMultiLineData(ArrayList<Double> inputList) {
if (inputList != null && inputList.size() > 0) {
double scale_factor = 90 / overallResults.getOverallScale_max();
return ResultParserHelper.scaleInputsData(inputList, scale_factor);
}
return null;
}
public String getMultipleChartTitle() {
return multipleChartResults.getMultipleChartTitle();
}
public void setMultipleYAxisLabel(String label){
multipleChartResults.setMultipleChartYAxisLabel(label);
}
public void setMultipleChartTitle(String label){
multipleChartResults.setMultipleChartTitle(label);
}
public String getMultipleYAxisLabel() {
return multipleChartResults.getMultipleChartYAxisLabel();
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser;
import java.util.ArrayList;
public class IndividualChartResults {
private ArrayList<Double> inputList = new ArrayList<Double>();
private String title;
private ArrayList<String> timeList = new ArrayList<String>();
private int files = 0;
public void setTitle(String title) {
this.title = title;
}
public ArrayList<Double> getInputList() {
return inputList;
}
public void setInputList(ArrayList<Double> inputList) {
this.inputList = inputList;
}
public ArrayList<String> getTimeList() {
return timeList;
}
public void setTimeList(ArrayList<String> timeList) {
this.timeList = timeList;
}
public String getTitle() {
return title;
}
public void incrementFiles(){
files++;
}
public int getFilesCount(){
return files;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterJTLParser.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterJTLParser.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser.component;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import com.acmeair.reporter.util.Messages;
public class JmeterJTLParser {
private String jmeterJTLFileName = "AcmeAir[1-9].jtl";
private String regEx =
"<httpSample\\s*" +
"t=\"([^\"]*)\"\\s*" +
"lt=\"([^\"]*)\"\\s*" +
"ts=\"([^\"]*)\"\\s*" +
"s=\"([^\"]*)\"\\s*" +
"lb=\"([^\"]*)\"\\s*" +
"rc=\"([^\"]*)\"\\s*" +
"rm=\"([^\"]*)\"\\s*" +
"tn=\"([^\"]*)\"\\s*" +
"dt=\"([^\"]*)\"\\s*" +
"by=\"([^\"]*)\"\\s*" +
"FLIGHTTOCOUNT=\"([^\"]*)\"\\s*" +
"FLIGHTRETCOUNT=\"([^\"]*)\"\\s*"+
"ONEWAY\\s*=\"([^\"]*)\"\\s*";
// NOTE: The regular expression depends on user.properties in jmeter having the sample_variables property added.
// sample_variables=FLIGHTTOCOUNT,FLIGHTRETCOUNT,ONEWAY
private int GROUP_T = 1;
private int GROUP_TS = 3;
private int GROUP_S = 4;
private int GROUP_LB = 5;
private int GROUP_RC = 6;
private int GROUP_TN = 8;
private int GROUP_FLIGHTTOCOUNT = 11;
private int GROUP_FLIGHTRETCOUNT = 12;
private int GROUP_ONEWAY = 13;
private JtlTotals totalAll;
private Map<String, JtlTotals> totalUrlMap;
public JmeterJTLParser() {
totalAll = new JtlTotals();
totalUrlMap = new HashMap<String, JtlTotals>();
String jtlRegularExpression = Messages.getString("parsers.JmeterJTLParser.jtlRegularExpression");
if (jtlRegularExpression != null){
System.out.println("set regex string to be '" + jtlRegularExpression+ "'");
regEx = jtlRegularExpression;
}
String matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.t");
if (matcherGroup != null){
GROUP_T = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.ts");
if (matcherGroup != null){
GROUP_TS = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.s");
if (matcherGroup != null){
GROUP_S = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.lb");
if (matcherGroup != null){
GROUP_LB = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.rc");
if (matcherGroup != null){
GROUP_RC = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.tn");
if (matcherGroup != null){
GROUP_TN = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.FLIGHTTOCOUNT");
if (matcherGroup != null){
GROUP_FLIGHTTOCOUNT = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.FLIGHTRETCOUNT");
if (matcherGroup != null){
GROUP_FLIGHTRETCOUNT = new Integer(matcherGroup).intValue();
}
matcherGroup = Messages.getString("parsers.JmeterJTLParser.regexGroups.ONEWAY");
if (matcherGroup != null){
GROUP_ONEWAY = new Integer(matcherGroup).intValue();
}
String responseTimeStepping = Messages.getString("parsers.JmeterJTLParser.responseTimeStepping");
if (responseTimeStepping != null){
JtlTotals.setResponseTimeStepping(new Integer(responseTimeStepping).intValue());
}
}
public void setLogFileName (String logFileName) {
this.jmeterJTLFileName = logFileName;
}
public void processResultsDirectory(String dirName) {
File root = new File(dirName);
try {
Collection<File> files = FileUtils.listFiles(root,
new RegexFileFilter(jmeterJTLFileName),
DirectoryFileFilter.DIRECTORY);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
parse(file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void parse(File jmeterJTLfile) throws IOException {
if(totalAll == null){
totalAll = new JtlTotals();
totalUrlMap = new HashMap<String, JtlTotals>();
}
totalAll.incrementFiles();
Pattern pattern = Pattern.compile(regEx);
HashMap <String, Integer> threadCounter = new HashMap<String, Integer>();
BufferedReader reader = new BufferedReader(new FileReader(jmeterJTLfile));
try {
String line = reader.readLine();
while(line != null) {
Matcher matcher = pattern.matcher(line);
if(matcher.find()) {
add(matcher, totalAll);
String url = matcher.group(GROUP_LB);
JtlTotals urlTotals = totalUrlMap.get(url);
if(urlTotals == null) {
urlTotals = new JtlTotals();
totalUrlMap.put(url, urlTotals);
}
add(matcher, urlTotals);
String threadName = matcher.group(GROUP_TN);
Integer threadCnt = threadCounter.get(threadName);
if(threadCnt == null) {
threadCnt = new Integer(1);
}else{
threadCnt = Integer.valueOf(threadCnt.intValue()+1);
}
threadCounter.put(threadName, threadCnt);
}
line = reader.readLine();
}
} finally {
reader.close();
}
totalAll.setThreadMap(threadCounter);
if(totalAll.getCount() == 0) {
System.out.println("JmeterJTLParser - No results found!");
return;
}
}
public JtlTotals getResults() {
return totalAll;
}
public Map<String, JtlTotals> getResultsByUrl() {
return totalUrlMap;
}
private void add(Matcher matcher, JtlTotals total) {
long timestamp = Long.parseLong(matcher.group(GROUP_TS));
total.addTimestamp(timestamp);
int time = Integer.parseInt(matcher.group(GROUP_T));
total.addTime(time);
String rc = matcher.group(GROUP_RC);
total.addReturnCode(rc);
if(!matcher.group(GROUP_S).equalsIgnoreCase("true")) {
total.incrementFailures();
}
String strFlightCount = matcher.group(GROUP_FLIGHTTOCOUNT);
if (strFlightCount != null && !strFlightCount.isEmpty()){
int count = Integer.parseInt(strFlightCount);
total.addToFlight(count);
}
strFlightCount = matcher.group(GROUP_FLIGHTRETCOUNT);
if (strFlightCount != null && !strFlightCount.isEmpty()){
total.addFlightRetCount(Integer.parseInt(strFlightCount));
}
String oneWay = matcher.group(GROUP_ONEWAY);
if (oneWay != null && oneWay.equalsIgnoreCase("true")){
total.incrementOneWayCount();
}
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser.component;
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
public class JmeterSummariserParser extends ResultParser {
private static boolean SKIP_JMETER_DROPOUTS = false;
static {
SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null;
}
private String jmeterFileName = "AcmeAir[1-9].log";
private String testDate = "";
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false);
IndividualChartResults individualResults = new IndividualChartResults();
if(result.getTitle() != null){
individualResults.setTitle(result.getTitle());
} else {
individualResults.setTitle(file.getName());
}
individualResults.setInputList(ResultParserHelper.scaleDown(result.getInputList(),6));
individualResults.setTimeList(ResultParserHelper.scaleDown(result.getTimeList(),3));
super.getMultipleChartResults().getResults().add(individualResults);
}
@Override
public String getFileName() {
return jmeterFileName;
}
@Override
public void setFileName(String fileName) {
jmeterFileName = fileName;
}
public String getTestDate(){
return testDate;
}
@Override
protected void processLine(IndividualChartResults results, String strLine) {
if (strLine.indexOf("summary +") > 0) {
String[] tokens = strLine.split(" ");
results.getTimeList().add(tokens[1].trim());
testDate = tokens[0].trim();
int endposition = strLine.indexOf("/s");
int startposition = strLine.indexOf("=");
String thoughputS = strLine.substring(startposition + 1, endposition).trim();
Double throughput = Double.parseDouble(thoughputS);
if (throughput == 0.0 && SKIP_JMETER_DROPOUTS) {
return;
}
results.getInputList().add(throughput);
} else if (strLine.indexOf("Name:") > 0) {
int startIndex = strLine.indexOf(" Name:")+7;
int endIndex = strLine.indexOf(" ", startIndex);
String name = strLine.substring(startIndex, endIndex);
results.setTitle(name);
}
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JtlTotals.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JtlTotals.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser.component;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
public class JtlTotals {
private static final String DECIMAL_PATTERN = "#,##0.0##";
private static final double MILLIS_PER_SECOND = 1000.0;
private static int millisPerBucket = 500;
private int files = 0;
private int request_count = 0;
private int time_sum = 0;
private int time_max = 0;
private int time_min = Integer.MAX_VALUE;
private int failures = 0;
private long timestamp_start = Long.MAX_VALUE;
private long timestamp_end = 0;
private Map<String, Integer> rcMap = new HashMap<String, Integer>(); // key rc, value count
private Map<Integer, Integer> millisMap = new TreeMap<Integer, Integer>(); // key bucket Integer, value count
private Map <String, Integer> threadMap = new HashMap<String,Integer>();
private ArrayList<Integer> timeList = new ArrayList<Integer>();
private long flight_to_sum = 0;
private long flight_to_count = 0;
private int flight_to_empty_count = 0;
private long flight_ret_count = 0;
private long one_way_count = 0;
public JtlTotals() {
}
public void add(JtlTotals totals){
rcMap.putAll(totals.getReturnCodeCounts());
millisMap.putAll(totals.getMillisMap());
threadMap.putAll(totals.getThreadMap());
one_way_count += totals.getOneWayCount();
flight_ret_count += totals.getFlightRetCount();
flight_to_empty_count += totals.getEmptyToFlightCount();
flight_to_sum += totals.getFlightToSum();
flight_to_count += totals.getFlightToCount();
failures += totals.getFailures();
request_count += totals.getCount();
}
public long getFlightToCount() {
return flight_to_count;
}
public void addTime(int time){
request_count++;
time_sum+=time;
time_max = Math.max(time_max, time);
time_min = Math.min(time_min, time);
timeList.add(time);
Integer bucket = new Integer(time / millisPerBucket);
Integer count = millisMap.get(bucket);
if(count == null) {
count = new Integer(0);
}
millisMap.put(bucket, new Integer(count.intValue() + 1));
}
public Map<Integer, Integer> getMillisMap() {
return millisMap;
}
public void addReturnCode(String rc){
Integer rc_count = rcMap.get(rc);
if(rc_count == null) {
rc_count = new Integer(0);
}
rcMap.put(rc, new Integer(rc_count.intValue() + 1));
}
public void setThreadMap(Map<String,Integer> threadMap){
this.threadMap = threadMap;
}
public void addTimestamp(long timestamp){
timestamp_end = Math.max(timestamp_end, timestamp);
timestamp_start = Math.min(timestamp_start, timestamp);
}
public void incrementFailures(){
failures++;
}
public void addToFlight(int count){
this.flight_to_count++;
this.flight_to_sum += count;
if(count == 0)
this.flight_to_empty_count++;
}
public void addFlightRetCount(int count){
this.flight_ret_count += count;
}
public void incrementOneWayCount(){
one_way_count++;
}
public void incrementFiles(){
files++;
}
public int getFilesCount(){
return files;
}
public int getCount(){
return request_count;
}
public Map<String,Integer> getThreadMap(){
return this.threadMap;
}
public int getAverageResponseTime(){
//in case .jtl file doesn't exist, request_count could be 0
//adding this condition to avoid "divide by zero" runtime exception
if (request_count==0) {
return time_sum;
}
return (time_sum/request_count);
}
public int getMaxResponseTime(){
return time_max;
}
public int getMinResponseTime(){
return time_min;
}
public int getFailures(){
return failures;
}
public int get90thPrecentile(){
if(timeList.isEmpty()){
return Integer.MAX_VALUE;
}
int target = (int)Math.round(timeList.size() * .90 );
Collections.sort(timeList);
if(target == timeList.size()){target--;}
return timeList.get(target);
}
public Map<String, Integer> getReturnCodeCounts(){
return rcMap;
}
public long getElapsedTimeInSeconds(){
double secondsElaspsed = (timestamp_end - timestamp_start) / MILLIS_PER_SECOND;
return Math.round(secondsElaspsed);
}
public long getRequestsPerSecond (){
return Math.round(request_count / getElapsedTimeInSeconds());
}
public long getFlightToSum(){
return flight_to_sum;
}
public long getEmptyToFlightCount(){
return flight_to_empty_count;
}
public float getAverageToFlights(){
return (float)flight_to_sum/flight_to_count;
}
public long getFlightRetCount(){
return flight_ret_count;
}
public long getOneWayCount(){
return one_way_count;
}
public static void setResponseTimeStepping(int milliseconds){
millisPerBucket = milliseconds;
}
public static int getResponseTimeStepping(){
return millisPerBucket;
}
public String cntByTimeString() {
DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN);
List<String> millisStr = new LinkedList<String>();
Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator();
while(iter.hasNext()) {
Entry<Integer,Integer> millisEntry = iter.next();
Integer bucket = (Integer)millisEntry.getKey();
Integer bucketCount = (Integer)millisEntry.getValue();
int minMillis = bucket.intValue() * millisPerBucket;
int maxMillis = (bucket.intValue() + 1) * millisPerBucket;
millisStr.add(
df.format(minMillis/MILLIS_PER_SECOND)+" s "+
"- "+
df.format(maxMillis/MILLIS_PER_SECOND)+" s "+
"= " + bucketCount);
}
return millisStr.toString();
}
public HashMap<String, Integer> cntByTime() {
DecimalFormat df = new DecimalFormat(DECIMAL_PATTERN);
LinkedHashMap<String, Integer> millisStr = new LinkedHashMap<String, Integer>();
Iterator <Entry<Integer,Integer>>iter = millisMap.entrySet().iterator();
while(iter.hasNext()) {
Entry<Integer,Integer> millisEntry = iter.next();
Integer bucket = (Integer)millisEntry.getKey();
Integer bucketCount = (Integer)millisEntry.getValue();
int minMillis = bucket.intValue() * millisPerBucket;
int maxMillis = (bucket.intValue() + 1) * millisPerBucket;
millisStr.put(
df.format(minMillis/MILLIS_PER_SECOND)+" s "+
"- "+
df.format(maxMillis/MILLIS_PER_SECOND)+" s "
, bucketCount);
}
return millisStr;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.reporter.parser.component;
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
public class NmonParser extends ResultParser{
private String nmonFileName = "output.nmon";
public NmonParser(){
super.setMultipleYAxisLabel("usr%+sys%"); //default label
}
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false);
IndividualChartResults individualResults = new IndividualChartResults();
individualResults.setTitle(result.getTitle());
individualResults.setInputList(ResultParserHelper.scaleDown(result.getInputList(),6));
individualResults.setTimeList(ResultParserHelper.scaleDown(result.getTimeList(),3));
super.getMultipleChartResults().getResults().add(individualResults);
}
@Override
public String getFileName() {
return nmonFileName;
}
@Override
public void setFileName(String fileName) {
nmonFileName = fileName;
}
@Override
protected void processLine(IndividualChartResults results, String strLine) {
if(strLine.startsWith("AAA,host,")){
String[] tokens = strLine.split(",");
results.setTitle(tokens[2].trim());
}
if (strLine.indexOf("ZZZZ") >=0){
String[] tokens = strLine.split(",");
results.getTimeList().add(tokens[2].trim());
}
if (strLine.indexOf("CPU_ALL") >=0 && strLine.indexOf("CPU Total")<0) {
String[] tokens = strLine.split(",");
String user = tokens[2].trim();
String sys = tokens[3].trim();
Double userDouble = Double.parseDouble(user);
Double sysDouble = Double.parseDouble(sys);
results.getInputList().add(userDouble+sysDouble);
}
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigDecimalConverter.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigDecimalConverter.java | package com.acmeair.morphia;
import java.math.BigDecimal;
import org.mongodb.morphia.converters.SimpleValueConverter;
import org.mongodb.morphia.converters.TypeConverter;
import org.mongodb.morphia.mapping.MappedField;
import org.mongodb.morphia.mapping.MappingException;
public class BigDecimalConverter extends TypeConverter implements SimpleValueConverter{
public BigDecimalConverter() {
super(BigDecimal.class);
}
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
return value.toString();
}
@Override
public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) throws MappingException {
if (fromDBObject == null) return null;
return new BigDecimal(fromDBObject.toString());
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigIntegerConverter.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/BigIntegerConverter.java | package com.acmeair.morphia;
import java.math.BigInteger;
import org.mongodb.morphia.converters.SimpleValueConverter;
import org.mongodb.morphia.converters.TypeConverter;
import org.mongodb.morphia.mapping.MappedField;
import org.mongodb.morphia.mapping.MappingException;
public class BigIntegerConverter extends TypeConverter implements SimpleValueConverter{
public BigIntegerConverter() {
super(BigInteger.class);
}
@Override
public Object encode(Object value, MappedField optionalExtraInfo) {
return value.toString();
}
@Override
public Object decode(Class targetClass, Object fromDBObject, MappedField optionalExtraInfo) throws MappingException {
if (fromDBObject == null) return null;
return new BigInteger(fromDBObject.toString());
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/MorphiaConstants.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/MorphiaConstants.java | package com.acmeair.morphia;
import com.acmeair.AcmeAirConstants;
public interface MorphiaConstants extends AcmeAirConstants {
public static final String JNDI_NAME = "mongo/acmeairMongodb";
public static final String KEY = "morphia";
public static final String KEY_DESCRIPTION = "mongoDB with morphia implementation";
public static final String HOSTNAME = "mongohostname";
public static final String PORT = "mongoport";
public static final String DATABASE = "mongodatabase";
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/DatastoreFactory.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/DatastoreFactory.java | package com.acmeair.morphia;
import java.util.Properties;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.acmeair.entities.Booking;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.WriteConcern;
public class DatastoreFactory {
private static String mongourl = null;
static {
String vcapJSONString = System.getenv("VCAP_SERVICES");
if (vcapJSONString != null) {
System.out.println("Reading VCAP_SERVICES");
Object jsonObject = JSONValue.parse(vcapJSONString);
JSONObject json = (JSONObject)jsonObject;
System.out.println("jsonObject = " + json.toJSONString());
for (Object key: json.keySet())
{
if (((String)key).contains("mongo"))
{
System.out.println("Found mongo service:" +key);
JSONArray mongoServiceArray = (JSONArray)json.get(key);
JSONObject mongoService = (JSONObject) mongoServiceArray.get(0);
JSONObject credentials = (JSONObject)mongoService.get("credentials");
mongourl = (String)credentials.get("url");
if (mongourl==null)
mongourl= (String)credentials.get("uri");
System.out.println("service url = " + mongourl);
break;
}
}
}
}
public static Datastore getDatastore(Datastore ds)
{
Datastore result =ds;
if (mongourl!=null)
{
try{
Properties prop = new Properties();
prop.load(DatastoreFactory.class.getResource("/acmeair-mongo.properties").openStream());
boolean fsync = new Boolean(prop.getProperty("mongo.fsync"));
int w = new Integer(prop.getProperty("mongo.w"));
int connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost"));
int threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier"));
// To match the local options
MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
.writeConcern(new WriteConcern(w, 0, fsync))
.connectionsPerHost(connectionsPerHost)
.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
MongoClientURI mongoURI = new MongoClientURI(mongourl, builder);
MongoClient mongo = new MongoClient(mongoURI);
Morphia morphia = new Morphia();
result = morphia.createDatastore( mongo ,mongoURI.getDatabase());
System.out.println("create mongo datastore with options:"+result.getMongo().getMongoClientOptions());
}catch (Exception e)
{
e.printStackTrace();
}
}
// The converter is added for handing JDK 7 issue
// result.getMapper().getConverters().addConverter(new BigDecimalConverter());
// result.getMapper().getConverters().addConverter(new BigIntegerConverter());
// Enable index
result.ensureIndex(Booking.class, "pkey.customerId");
result.ensureIndex(Flight.class, "pkey.flightSegmentId,scheduledDepartureTime");
result.ensureIndex(FlightSegment.class, "originPort,destPort");
return result;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/FlightServiceImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/FlightServiceImpl.java | /*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.services;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.acmeair.entities.AirportCodeMapping;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.morphia.MorphiaConstants;
import com.acmeair.morphia.entities.AirportCodeMappingImpl;
import com.acmeair.morphia.entities.FlightImpl;
import com.acmeair.morphia.entities.FlightSegmentImpl;
import com.acmeair.morphia.services.util.MongoConnectionManager;
import com.acmeair.service.DataService;
import com.acmeair.service.FlightService;
import com.acmeair.service.KeyGenerator;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
@DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION)
public class FlightServiceImpl extends FlightService implements MorphiaConstants {
//private final static Logger logger = Logger.getLogger(FlightService.class.getName());
Datastore datastore;
@Inject
KeyGenerator keyGenerator;
@PostConstruct
public void initialization() {
datastore = MongoConnectionManager.getConnectionManager().getDatastore();
}
@Override
public Long countFlights() {
return datastore.find(FlightImpl.class).countAll();
}
@Override
public Long countFlightSegments() {
return datastore.find(FlightSegmentImpl.class).countAll();
}
@Override
public Long countAirports() {
return datastore.find(AirportCodeMappingImpl.class).countAll();
}
/*
@Override
public Flight getFlightByFlightId(String flightId, String flightSegmentId) {
try {
Flight flight = flightPKtoFlightCache.get(flightId);
if (flight == null) {
Query<FlightImpl> q = datastore.find(FlightImpl.class).field("_id").equal(flightId);
flight = q.get();
if (flightId != null && flight != null) {
flightPKtoFlightCache.putIfAbsent(flight, flight);
}
}
return flight;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
*/
protected Flight getFlight(String flightId, String segmentId) {
Query<FlightImpl> q = datastore.find(FlightImpl.class).field("_id").equal(flightId);
return q.get();
}
@Override
protected FlightSegment getFlightSegment(String fromAirport, String toAirport){
Query<FlightSegmentImpl> q = datastore.find(FlightSegmentImpl.class).field("originPort").equal(fromAirport).field("destPort").equal(toAirport);
FlightSegment segment = q.get();
if (segment == null) {
segment = new FlightSegmentImpl(); // put a sentinel value of a non-populated flightsegment
}
return segment;
}
@Override
protected List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate){
Query<FlightImpl> q2;
if(deptDate != null) {
q2 = datastore.find(FlightImpl.class).disableValidation().field("flightSegmentId").equal(segment.getFlightName()).field("scheduledDepartureTime").equal(deptDate);
} else {
q2 = datastore.find(FlightImpl.class).disableValidation().field("flightSegmentId").equal(segment.getFlightName());
}
List<FlightImpl> flightImpls = q2.asList();
List<Flight> flights;
if (flightImpls != null) {
flights = new ArrayList<Flight>();
for (Flight flight : flightImpls) {
flight.setFlightSegment(segment);
flights.add(flight);
}
}
else {
flights = new ArrayList<Flight>(); // put an empty list into the cache in the cache in the case where no matching flights
}
return flights;
}
@Override
public void storeAirportMapping(AirportCodeMapping mapping) {
try{
datastore.save(mapping);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName){
AirportCodeMapping acm = new AirportCodeMappingImpl(airportCode, airportName);
return acm;
}
@Override
public Flight createNewFlight(String flightSegmentId,
Date scheduledDepartureTime, Date scheduledArrivalTime,
BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
int numFirstClassSeats, int numEconomyClassSeats,
String airplaneTypeId) {
String id = keyGenerator.generate().toString();
Flight flight = new FlightImpl(id, flightSegmentId,
scheduledDepartureTime, scheduledArrivalTime,
firstClassBaseCost, economyClassBaseCost,
numFirstClassSeats, numEconomyClassSeats,
airplaneTypeId);
try{
datastore.save(flight);
return flight;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void storeFlightSegment(FlightSegment flightSeg) {
try{
datastore.save(flightSeg);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void storeFlightSegment(String flightName, String origPort, String destPort, int miles) {
FlightSegment flightSeg = new FlightSegmentImpl(flightName, origPort, destPort, miles);
storeFlightSegment(flightSeg);
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java | package com.acmeair.morphia.services;
import java.util.Date;
import javax.annotation.PostConstruct;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.MorphiaConstants;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.services.util.MongoConnectionManager;
import com.acmeair.service.DataService;
import com.acmeair.service.CustomerService;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
@DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION)
public class CustomerServiceImpl extends CustomerService implements MorphiaConstants {
// private final static Logger logger = Logger.getLogger(CustomerService.class.getName());
protected Datastore datastore;
@PostConstruct
public void initialization() {
datastore = MongoConnectionManager.getConnectionManager().getDatastore();
}
@Override
public Long count() {
return datastore.find(CustomerImpl.class).countAll();
}
@Override
public Long countSessions() {
return datastore.find(CustomerSessionImpl.class).countAll();
}
@Override
public Customer createCustomer(String username, String password,
MemberShipStatus status, int total_miles, int miles_ytd,
String phoneNumber, PhoneType phoneNumberType,
CustomerAddress address) {
Customer customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType);
datastore.save(customer);
return customer;
}
@Override
public CustomerAddress createAddress (String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode){
CustomerAddress address = new CustomerAddressImpl(streetAddress1, streetAddress2,
city, stateProvince, country, postalCode);
return address;
}
@Override
public Customer updateCustomer(Customer customer) {
datastore.save(customer);
return customer;
}
@Override
protected Customer getCustomer(String username) {
Query<CustomerImpl> q = datastore.find(CustomerImpl.class).field("_id").equal(username);
Customer customer = q.get();
return customer;
}
@Override
public Customer getCustomerByUsername(String username) {
Query<CustomerImpl> q = datastore.find(CustomerImpl.class).field("_id").equal(username);
Customer customer = q.get();
if (customer != null) {
customer.setPassword(null);
}
return customer;
}
@Override
protected CustomerSession getSession(String sessionid){
Query<CustomerSessionImpl> q = datastore.find(CustomerSessionImpl.class).field("_id").equal(sessionid);
return q.get();
}
@Override
protected void removeSession(CustomerSession session){
datastore.delete(session);
}
@Override
protected CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration) {
CustomerSession cSession = new CustomerSessionImpl(sessionId, customerId, creation, expiration);
datastore.save(cSession);
return cSession;
}
@Override
public void invalidateSession(String sessionid) {
Query<CustomerSessionImpl> q = datastore.find(CustomerSessionImpl.class).field("_id").equal(sessionid);
datastore.delete(q);
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/BookingServiceImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/BookingServiceImpl.java | package com.acmeair.morphia.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.mongodb.morphia.Datastore;
import com.acmeair.entities.Booking;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Flight;
import com.acmeair.morphia.MorphiaConstants;
import com.acmeair.morphia.entities.BookingImpl;
import com.acmeair.morphia.services.util.MongoConnectionManager;
import com.acmeair.service.BookingService;
import com.acmeair.service.CustomerService;
import com.acmeair.service.DataService;
import com.acmeair.service.FlightService;
import com.acmeair.service.KeyGenerator;
import com.acmeair.service.ServiceLocator;
import org.mongodb.morphia.query.Query;
@DataService(name=MorphiaConstants.KEY,description=MorphiaConstants.KEY_DESCRIPTION)
public class BookingServiceImpl implements BookingService, MorphiaConstants {
//private final static Logger logger = Logger.getLogger(BookingService.class.getName());
Datastore datastore;
@Inject
KeyGenerator keyGenerator;
private FlightService flightService = ServiceLocator.instance().getService(FlightService.class);
private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class);
@PostConstruct
public void initialization() {
datastore = MongoConnectionManager.getConnectionManager().getDatastore();
}
public String bookFlight(String customerId, String flightId) {
try{
Flight f = flightService.getFlightByFlightId(flightId, null);
Customer c = customerService.getCustomerByUsername(customerId);
Booking newBooking = new BookingImpl(keyGenerator.generate().toString(), new Date(), c, f);
datastore.save(newBooking);
return newBooking.getBookingId();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String bookFlight(String customerId, String flightSegmentId, String flightId) {
return bookFlight(customerId, flightId);
}
@Override
public Booking getBooking(String user, String bookingId) {
try{
Query<BookingImpl> q = datastore.find(BookingImpl.class).field("_id").equal(bookingId);
Booking booking = q.get();
return booking;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public List<Booking> getBookingsByUser(String user) {
try{
Query<BookingImpl> q = datastore.find(BookingImpl.class).disableValidation().field("customerId").equal(user);
List<BookingImpl> bookingImpls = q.asList();
List<Booking> bookings = new ArrayList<Booking>();
for(Booking b: bookingImpls){
bookings.add(b);
}
return bookings;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void cancelBooking(String user, String bookingId) {
try{
datastore.delete(BookingImpl.class, bookingId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Long count() {
return datastore.find(BookingImpl.class).countAll();
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/util/MongoConnectionManager.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/services/util/MongoConnectionManager.java | package com.acmeair.morphia.services.util;
import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.acmeair.morphia.BigDecimalConverter;
import com.acmeair.morphia.MorphiaConstants;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
public class MongoConnectionManager implements MorphiaConstants{
private static AtomicReference<MongoConnectionManager> connectionManager = new AtomicReference<MongoConnectionManager>();
private final static Logger logger = Logger.getLogger(MongoConnectionManager.class.getName());
@Resource(name = JNDI_NAME)
protected DB db;
private static Datastore datastore;
public static MongoConnectionManager getConnectionManager() {
if (connectionManager.get() == null) {
synchronized (connectionManager) {
if (connectionManager.get() == null) {
connectionManager.set(new MongoConnectionManager());
}
}
}
return connectionManager.get();
}
private MongoConnectionManager (){
Morphia morphia = new Morphia();
// Set default client options, and then check if there is a properties file.
boolean fsync = false;
int w = 0;
int connectionsPerHost = 5;
int threadsAllowedToBlockForConnectionMultiplier = 10;
int connectTimeout= 0;
int socketTimeout= 0;
boolean socketKeepAlive = true;
int maxWaitTime = 2000;
Properties prop = new Properties();
URL mongoPropertyFile = MongoConnectionManager.class.getResource("/com/acmeair/morphia/services/util/mongo.properties");
if(mongoPropertyFile != null){
try {
logger.info("Reading mongo.properties file");
prop.load(mongoPropertyFile.openStream());
fsync = new Boolean(prop.getProperty("mongo.fsync"));
w = new Integer(prop.getProperty("mongo.w"));
connectionsPerHost = new Integer(prop.getProperty("mongo.connectionsPerHost"));
threadsAllowedToBlockForConnectionMultiplier = new Integer(prop.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier"));
connectTimeout= new Integer(prop.getProperty("mongo.connectTimeout"));
socketTimeout= new Integer(prop.getProperty("mongo.socketTimeout"));
socketKeepAlive = new Boolean(prop.getProperty("mongo.socketKeepAlive"));
maxWaitTime =new Integer(prop.getProperty("mongo.maxWaitTime"));
}catch (IOException ioe){
logger.severe("Exception when trying to read from the mongo.properties file" + ioe.getMessage());
}
}
// Set the client options
MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
.writeConcern(new WriteConcern(w, 0, fsync))
.connectionsPerHost(connectionsPerHost)
.connectTimeout(connectTimeout)
.socketTimeout(socketTimeout)
.socketKeepAlive(socketKeepAlive)
.maxWaitTime(maxWaitTime)
.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
try {
//Check if VCAP_SERVICES exist, and if it does, look up the url from the credentials.
String vcapJSONString = System.getenv("VCAP_SERVICES");
if (vcapJSONString != null) {
logger.info("Reading VCAP_SERVICES");
Object jsonObject = JSONValue.parse(vcapJSONString);
JSONObject vcapServices = (JSONObject)jsonObject;
JSONArray mongoServiceArray =null;
for (Object key : vcapServices.keySet()){
if (key.toString().startsWith("mongo")){
mongoServiceArray = (JSONArray) vcapServices.get(key);
break;
}
}
if (mongoServiceArray == null) {
logger.severe("VCAP_SERVICES existed, but a mongo service was not definied.");
} else {
JSONObject mongoService = (JSONObject)mongoServiceArray.get(0);
JSONObject credentials = (JSONObject)mongoService.get("credentials");
String url = (String) credentials.get("url");
logger.fine("service url = " + url);
MongoClientURI mongoURI = new MongoClientURI(url, builder);
MongoClient mongo = new MongoClient(mongoURI);
morphia.getMapper().getConverters().addConverter(new BigDecimalConverter());
datastore = morphia.createDatastore( mongo ,mongoURI.getDatabase());
}
} else {
//VCAP_SERVICES don't exist, so use the DB resource
logger.fine("No VCAP_SERVICES found");
if(db == null){
try {
logger.warning("Resource Injection failed. Attempting to look up " + JNDI_NAME + " via JNDI.");
db = (DB) new InitialContext().lookup(JNDI_NAME);
} catch (NamingException e) {
logger.severe("Caught NamingException : " + e.getMessage() );
}
}
if(db == null){
String host;
String port;
String database;
logger.info("Creating the MongoDB Client connection. Looking up host and port information " );
try {
host = (String) new InitialContext().lookup("java:comp/env/" + HOSTNAME);
port = (String) new InitialContext().lookup("java:comp/env/" + PORT);
database = (String) new InitialContext().lookup("java:comp/env/" + DATABASE);
ServerAddress server = new ServerAddress(host, Integer.parseInt(port));
MongoClient mongo = new MongoClient(server);
db = mongo.getDB(database);
} catch (NamingException e) {
logger.severe("Caught NamingException : " + e.getMessage() );
} catch (Exception e) {
logger.severe("Caught Exception : " + e.getMessage() );
}
}
if(db == null){
logger.severe("Unable to retreive reference to database, please check the server logs.");
} else {
morphia.getMapper().getConverters().addConverter(new BigDecimalConverter());
datastore = morphia.createDatastore(new MongoClient(db.getMongo().getConnectPoint(),builder.build()), db.getName());
}
}
} catch (UnknownHostException e) {
logger.severe("Caught Exception : " + e.getMessage() );
}
logger.info("created mongo datastore with options:"+datastore.getMongo().getMongoClientOptions());
}
public DB getDB(){
return db;
}
public Datastore getDatastore(){
return datastore;
}
@SuppressWarnings("deprecation")
public String getDriverVersion(){
return datastore.getMongo().getVersion();
}
public String getMongoVersion(){
return datastore.getDB().command("buildInfo").getString("version");
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/BookingImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/BookingImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import java.util.Date;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import com.acmeair.entities.Booking;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Flight;
@Entity(value="booking")
public class BookingImpl implements Booking, Serializable{
private static final long serialVersionUID = 1L;
@Id
private String _id;
private String flightId;
private String customerId;
private Date dateOfBooking;
public BookingImpl() {
}
public BookingImpl(String bookingId, Date dateOfFlight, String customerId, String flightId) {
this._id = bookingId;
this.flightId = flightId;
this.customerId = customerId;
this.dateOfBooking = dateOfFlight;
}
public BookingImpl(String bookingId, Date dateOfFlight, Customer customer, Flight flight) {
this._id = bookingId;
this.flightId = flight.getFlightId();
this.dateOfBooking = dateOfFlight;
this.customerId = customer.getCustomerId();
}
public String getBookingId() {
return _id;
}
public void setBookingId(String bookingId) {
this._id = bookingId;
}
public String getFlightId() {
return flightId;
}
public void setFlightId(String flightId) {
this.flightId = flightId;
}
public Date getDateOfBooking() {
return dateOfBooking;
}
public void setDateOfBooking(Date dateOfBooking) {
this.dateOfBooking = dateOfBooking;
}
public String getCustomerId() {
return customerId;
}
public void setCustomer(String customerId) {
this.customerId = customerId;
}
@Override
public String toString() {
return "Booking [key=" + _id + ", flightId=" + flightId
+ ", dateOfBooking=" + dateOfBooking + ", customerId=" + customerId + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookingImpl other = (BookingImpl) obj;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (dateOfBooking == null) {
if (other.dateOfBooking != null)
return false;
} else if (!dateOfBooking.equals(other.dateOfBooking))
return false;
if (flightId == null) {
if (other.flightId != null)
return false;
} else if (!flightId.equals(other.flightId))
return false;
return true;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
@Entity(value="flight")
public class FlightImpl implements Flight, Serializable{
private static final long serialVersionUID = 1L;
@Id
private String _id;
private String flightSegmentId;
private Date scheduledDepartureTime;
private Date scheduledArrivalTime;
private BigDecimal firstClassBaseCost;
private BigDecimal economyClassBaseCost;
private int numFirstClassSeats;
private int numEconomyClassSeats;
private String airplaneTypeId;
private FlightSegment flightSegment;
public FlightImpl() {
}
public FlightImpl(String id, String flightSegmentId,
Date scheduledDepartureTime, Date scheduledArrivalTime,
BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
int numFirstClassSeats, int numEconomyClassSeats,
String airplaneTypeId) {
this._id = id;
this.flightSegmentId = flightSegmentId;
this.scheduledDepartureTime = scheduledDepartureTime;
this.scheduledArrivalTime = scheduledArrivalTime;
this.firstClassBaseCost = firstClassBaseCost;
this.economyClassBaseCost = economyClassBaseCost;
this.numFirstClassSeats = numFirstClassSeats;
this.numEconomyClassSeats = numEconomyClassSeats;
this.airplaneTypeId = airplaneTypeId;
}
public String getFlightId(){
return _id;
}
public void setFlightId(String id){
this._id = id;
}
public String getFlightSegmentId()
{
return flightSegmentId;
}
public void setFlightSegmentId(String segmentId){
this.flightSegmentId = segmentId;
}
public Date getScheduledDepartureTime() {
return scheduledDepartureTime;
}
public void setScheduledDepartureTime(Date scheduledDepartureTime) {
this.scheduledDepartureTime = scheduledDepartureTime;
}
public Date getScheduledArrivalTime() {
return scheduledArrivalTime;
}
public void setScheduledArrivalTime(Date scheduledArrivalTime) {
this.scheduledArrivalTime = scheduledArrivalTime;
}
public BigDecimal getFirstClassBaseCost() {
return firstClassBaseCost;
}
public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) {
this.firstClassBaseCost = firstClassBaseCost;
}
public BigDecimal getEconomyClassBaseCost() {
return economyClassBaseCost;
}
public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) {
this.economyClassBaseCost = economyClassBaseCost;
}
public int getNumFirstClassSeats() {
return numFirstClassSeats;
}
public void setNumFirstClassSeats(int numFirstClassSeats) {
this.numFirstClassSeats = numFirstClassSeats;
}
public int getNumEconomyClassSeats() {
return numEconomyClassSeats;
}
public void setNumEconomyClassSeats(int numEconomyClassSeats) {
this.numEconomyClassSeats = numEconomyClassSeats;
}
public String getAirplaneTypeId() {
return airplaneTypeId;
}
public void setAirplaneTypeId(String airplaneTypeId) {
this.airplaneTypeId = airplaneTypeId;
}
public FlightSegment getFlightSegment() {
return flightSegment;
}
public void setFlightSegment(FlightSegment flightSegment) {
this.flightSegment = flightSegment;
}
@Override
public String toString() {
return "Flight key="+_id
+ ", scheduledDepartureTime=" + scheduledDepartureTime
+ ", scheduledArrivalTime=" + scheduledArrivalTime
+ ", firstClassBaseCost=" + firstClassBaseCost
+ ", economyClassBaseCost=" + economyClassBaseCost
+ ", numFirstClassSeats=" + numFirstClassSeats
+ ", numEconomyClassSeats=" + numEconomyClassSeats
+ ", airplaneTypeId=" + airplaneTypeId + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightImpl other = (FlightImpl) obj;
if (airplaneTypeId == null) {
if (other.airplaneTypeId != null)
return false;
} else if (!airplaneTypeId.equals(other.airplaneTypeId))
return false;
if (economyClassBaseCost == null) {
if (other.economyClassBaseCost != null)
return false;
} else if (!economyClassBaseCost.equals(other.economyClassBaseCost))
return false;
if (firstClassBaseCost == null) {
if (other.firstClassBaseCost != null)
return false;
} else if (!firstClassBaseCost.equals(other.firstClassBaseCost))
return false;
if (flightSegment == null) {
if (other.flightSegment != null)
return false;
} else if (!flightSegment.equals(other.flightSegment))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (numEconomyClassSeats != other.numEconomyClassSeats)
return false;
if (numFirstClassSeats != other.numFirstClassSeats)
return false;
if (scheduledArrivalTime == null) {
if (other.scheduledArrivalTime != null)
return false;
} else if (!scheduledArrivalTime.equals(other.scheduledArrivalTime))
return false;
if (scheduledDepartureTime == null) {
if (other.scheduledDepartureTime != null)
return false;
} else if (!scheduledDepartureTime.equals(other.scheduledDepartureTime))
return false;
return true;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/AirportCodeMappingImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/AirportCodeMappingImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import org.mongodb.morphia.annotations.Entity;
import com.acmeair.entities.AirportCodeMapping;
@Entity(value="airportCodeMapping")
public class AirportCodeMappingImpl implements AirportCodeMapping, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String airportName;
public AirportCodeMappingImpl() {
}
public AirportCodeMappingImpl(String airportCode, String airportName) {
this._id = airportCode;
this.airportName = airportName;
}
public String getAirportCode() {
return _id;
}
public void setAirportCode(String airportCode) {
this._id = airportCode;
}
public String getAirportName() {
return airportName;
}
public void setAirportName(String airportName) {
this.airportName = airportName;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightSegmentImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightSegmentImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import org.mongodb.morphia.annotations.Entity;
import com.acmeair.entities.FlightSegment;
@Entity(value="flightSegment")
public class FlightSegmentImpl implements FlightSegment, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String originPort;
private String destPort;
private int miles;
public FlightSegmentImpl() {
}
public FlightSegmentImpl(String flightName, String origPort, String destPort, int miles) {
this._id = flightName;
this.originPort = origPort;
this.destPort = destPort;
this.miles = miles;
}
public String getFlightName() {
return _id;
}
public void setFlightName(String flightName) {
this._id = flightName;
}
public String getOriginPort() {
return originPort;
}
public void setOriginPort(String originPort) {
this.originPort = originPort;
}
public String getDestPort() {
return destPort;
}
public void setDestPort(String destPort) {
this.destPort = destPort;
}
public int getMiles() {
return miles;
}
public void setMiles(int miles) {
this.miles = miles;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("FlightSegment ").append(_id).append(" originating from:\"").append(originPort).append("\" arriving at:\"").append(destPort).append("\"");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightSegmentImpl other = (FlightSegmentImpl) obj;
if (destPort == null) {
if (other.destPort != null)
return false;
} else if (!destPort.equals(other.destPort))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (miles != other.miles)
return false;
if (originPort == null) {
if (other.originPort != null)
return false;
} else if (!originPort.equals(other.originPort))
return false;
return true;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerSessionImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerSessionImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import java.util.Date;
import org.mongodb.morphia.annotations.Entity;
import com.acmeair.entities.CustomerSession;
@Entity(value="customerSession")
public class CustomerSessionImpl implements CustomerSession, Serializable {
private static final long serialVersionUID = 1L;
private String _id;
private String customerid;
private Date lastAccessedTime;
private Date timeoutTime;
public CustomerSessionImpl() {
}
public CustomerSessionImpl(String id, String customerid, Date lastAccessedTime, Date timeoutTime) {
this._id= id;
this.customerid = customerid;
this.lastAccessedTime = lastAccessedTime;
this.timeoutTime = timeoutTime;
}
public String getId() {
return _id;
}
public void setId(String id) {
this._id = id;
}
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
public Date getLastAccessedTime() {
return lastAccessedTime;
}
public void setLastAccessedTime(Date lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
}
public Date getTimeoutTime() {
return timeoutTime;
}
public void setTimeoutTime(Date timeoutTime) {
this.timeoutTime = timeoutTime;
}
@Override
public String toString() {
return "CustomerSession [id=" + _id + ", customerid=" + customerid
+ ", lastAccessedTime=" + lastAccessedTime + ", timeoutTime="
+ timeoutTime + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerSessionImpl other = (CustomerSessionImpl) obj;
if (customerid == null) {
if (other.customerid != null)
return false;
} else if (!customerid.equals(other.customerid))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (lastAccessedTime == null) {
if (other.lastAccessedTime != null)
return false;
} else if (!lastAccessedTime.equals(other.lastAccessedTime))
return false;
if (timeoutTime == null) {
if (other.timeoutTime != null)
return false;
} else if (!timeoutTime.equals(other.timeoutTime))
return false;
return true;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import org.mongodb.morphia.annotations.Entity;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
@Entity(value="customer")
public class CustomerImpl implements Customer, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String password;
private MemberShipStatus status;
private int total_miles;
private int miles_ytd;
private CustomerAddress address;
private String phoneNumber;
private PhoneType phoneNumberType;
public CustomerImpl() {
}
public CustomerImpl(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, CustomerAddress address, String phoneNumber, PhoneType phoneNumberType) {
this._id = username;
this.password = password;
this.status = status;
this.total_miles = total_miles;
this.miles_ytd = miles_ytd;
this.address = address;
this.phoneNumber = phoneNumber;
this.phoneNumberType = phoneNumberType;
}
public String getCustomerId(){
return _id;
}
public String getUsername() {
return _id;
}
public void setUsername(String username) {
this._id = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberShipStatus getStatus() {
return status;
}
public void setStatus(MemberShipStatus status) {
this.status = status;
}
public int getTotal_miles() {
return total_miles;
}
public void setTotal_miles(int total_miles) {
this.total_miles = total_miles;
}
public int getMiles_ytd() {
return miles_ytd;
}
public void setMiles_ytd(int miles_ytd) {
this.miles_ytd = miles_ytd;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public PhoneType getPhoneNumberType() {
return phoneNumberType;
}
public void setPhoneNumberType(PhoneType phoneNumberType) {
this.phoneNumberType = phoneNumberType;
}
public CustomerAddress getAddress() {
return address;
}
public void setAddress(CustomerAddress address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + _id + ", password=" + password + ", status="
+ status + ", total_miles=" + total_miles + ", miles_ytd="
+ miles_ytd + ", address=" + address + ", phoneNumber="
+ phoneNumber + ", phoneNumberType=" + phoneNumberType + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerImpl other = (CustomerImpl) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (miles_ytd != other.miles_ytd)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (phoneNumber == null) {
if (other.phoneNumber != null)
return false;
} else if (!phoneNumber.equals(other.phoneNumber))
return false;
if (phoneNumberType != other.phoneNumberType)
return false;
if (status != other.status)
return false;
if (total_miles != other.total_miles)
return false;
return true;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerAddressImpl.java | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/CustomerAddressImpl.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.morphia.entities;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.acmeair.entities.CustomerAddress;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class CustomerAddressImpl implements CustomerAddress, Serializable{
private static final long serialVersionUID = 1L;
private String streetAddress1;
private String streetAddress2;
private String city;
private String stateProvince;
private String country;
private String postalCode;
public CustomerAddressImpl() {
}
public CustomerAddressImpl(String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode) {
super();
this.streetAddress1 = streetAddress1;
this.streetAddress2 = streetAddress2;
this.city = city;
this.stateProvince = stateProvince;
this.country = country;
this.postalCode = postalCode;
}
public String getStreetAddress1() {
return streetAddress1;
}
public void setStreetAddress1(String streetAddress1) {
this.streetAddress1 = streetAddress1;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
@Override
public String toString() {
return "CustomerAddress [streetAddress1=" + streetAddress1
+ ", streetAddress2=" + streetAddress2 + ", city=" + city
+ ", stateProvince=" + stateProvince + ", country=" + country
+ ", postalCode=" + postalCode + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerAddressImpl other = (CustomerAddressImpl) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (postalCode == null) {
if (other.postalCode != null)
return false;
} else if (!postalCode.equals(other.postalCode))
return false;
if (stateProvince == null) {
if (other.stateProvince != null)
return false;
} else if (!stateProvince.equals(other.stateProvince))
return false;
if (streetAddress1 == null) {
if (other.streetAddress1 != null)
return false;
} else if (!streetAddress1.equals(other.streetAddress1))
return false;
if (streetAddress2 == null) {
if (other.streetAddress2 != null)
return false;
} else if (!streetAddress2.equals(other.streetAddress2))
return false;
return true;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/AcmeAirConstants.java | acmeair-common/src/main/java/com/acmeair/AcmeAirConstants.java | package com.acmeair;
public interface AcmeAirConstants {
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java | acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface AirportCodeMapping{
public String getAirportCode();
public void setAirportCode(String airportCode);
public String getAirportName();
public void setAirportName(String airportName);
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/CustomerAddress.java | acmeair-common/src/main/java/com/acmeair/entities/CustomerAddress.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface CustomerAddress {
public String getStreetAddress1();
public void setStreetAddress1(String streetAddress1);
public String getStreetAddress2();
public void setStreetAddress2(String streetAddress2);
public String getCity();
public void setCity(String city);
public String getStateProvince();
public void setStateProvince(String stateProvince);
public String getCountry();
public void setCountry(String country);
public String getPostalCode();
public void setPostalCode(String postalCode);
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java | acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface FlightSegment {
public String getFlightName();
public String getOriginPort();
public String getDestPort();
public int getMiles();
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/Customer.java | acmeair-common/src/main/java/com/acmeair/entities/Customer.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface Customer {
public enum MemberShipStatus { NONE, SILVER, GOLD, PLATINUM, EXEC_PLATINUM, GRAPHITE };
public enum PhoneType { UNKNOWN, HOME, BUSINESS, MOBILE };
public String getCustomerId();
public String getUsername();
public void setUsername(String username);
public String getPassword();
public void setPassword(String password);
public MemberShipStatus getStatus();
public void setStatus(MemberShipStatus status);
public int getTotal_miles();
public int getMiles_ytd();
public String getPhoneNumber();
public void setPhoneNumber(String phoneNumber);
public PhoneType getPhoneNumberType();
public void setPhoneNumberType(PhoneType phoneNumberType);
public CustomerAddress getAddress();
public void setAddress(CustomerAddress address);
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/CustomerSession.java | acmeair-common/src/main/java/com/acmeair/entities/CustomerSession.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
import java.util.Date;
public interface CustomerSession {
public String getId();
public String getCustomerid();
public Date getLastAccessedTime();
public Date getTimeoutTime();
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/Flight.java | acmeair-common/src/main/java/com/acmeair/entities/Flight.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
import java.math.BigDecimal;
import java.util.Date;
public interface Flight{
String getFlightId();
void setFlightId(String id);
String getFlightSegmentId();
FlightSegment getFlightSegment();
void setFlightSegment(FlightSegment flightSegment);
Date getScheduledDepartureTime();
Date getScheduledArrivalTime();
BigDecimal getFirstClassBaseCost();
BigDecimal getEconomyClassBaseCost();
int getNumFirstClassSeats();
int getNumEconomyClassSeats();
String getAirplaneTypeId();
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-common/src/main/java/com/acmeair/entities/Booking.java | acmeair-common/src/main/java/com/acmeair/entities/Booking.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
import java.util.Date;
public interface Booking {
public String getBookingId();
public String getFlightId();
public String getCustomerId();
public Date getDateOfBooking();
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-loader/src/main/java/com/acmeair/loader/FlightLoader.java | acmeair-loader/src/main/java/com/acmeair/loader/FlightLoader.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.loader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.*;
import java.math.*;
import com.acmeair.entities.AirportCodeMapping;
import com.acmeair.service.FlightService;
import com.acmeair.service.ServiceLocator;
public class FlightLoader {
private static final int MAX_FLIGHTS_PER_SEGMENT = 30;
private FlightService flightService = ServiceLocator.instance().getService(FlightService.class);
public void loadFlights() throws Exception {
InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv");
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
String line1 = lnr.readLine();
StringTokenizer st = new StringTokenizer(line1, ",");
ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();
// read the first line which are airport names
while (st.hasMoreTokens()) {
AirportCodeMapping acm = flightService.createAirportCodeMapping(null, st.nextToken());
// acm.setAirportName(st.nextToken());
airports.add(acm);
}
// read the second line which contains matching airport codes for the first line
String line2 = lnr.readLine();
st = new StringTokenizer(line2, ",");
int ii = 0;
while (st.hasMoreTokens()) {
String airportCode = st.nextToken();
airports.get(ii).setAirportCode(airportCode);
ii++;
}
// read the other lines which are of format:
// airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two
String line;
int flightNumber = 0;
while (true) {
line = lnr.readLine();
if (line == null || line.trim().equals("")) {
break;
}
st = new StringTokenizer(line, ",");
String airportName = st.nextToken();
String airportCode = st.nextToken();
if (!alreadyInCollection(airportCode, airports)) {
AirportCodeMapping acm = flightService.createAirportCodeMapping(airportCode, airportName);
airports.add(acm);
}
int indexIntoTopLine = 0;
while (st.hasMoreTokens()) {
String milesString = st.nextToken();
if (milesString.equals("NA")) {
indexIntoTopLine++;
continue;
}
int miles = Integer.parseInt(milesString);
String toAirport = airports.get(indexIntoTopLine).getAirportCode();
String flightId = "AA" + flightNumber;
flightService.storeFlightSegment(flightId, airportCode, toAirport, miles);
Date now = new Date();
for (int daysFromNow = 0; daysFromNow < MAX_FLIGHTS_PER_SEGMENT; daysFromNow++) {
Calendar c = Calendar.getInstance();
c.setTime(now);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DATE, daysFromNow);
Date departureTime = c.getTime();
Date arrivalTime = getArrivalTime(departureTime, miles);
flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500), new BigDecimal(200), 10, 200, "B747");
}
flightNumber++;
indexIntoTopLine++;
}
}
for (int jj = 0; jj < airports.size(); jj++) {
flightService.storeAirportMapping(airports.get(jj));
}
lnr.close();
}
private static Date getArrivalTime(Date departureTime, int mileage) {
double averageSpeed = 600.0; // 600 miles/hours
double hours = (double) mileage / averageSpeed; // miles / miles/hour = hours
double partsOfHour = hours % 1.0;
int minutes = (int)(60.0 * partsOfHour);
Calendar c = Calendar.getInstance();
c.setTime(departureTime);
c.add(Calendar.HOUR, (int)hours);
c.add(Calendar.MINUTE, minutes);
return c.getTime();
}
static private boolean alreadyInCollection(String airportCode, ArrayList<AirportCodeMapping> airports) {
for (int ii = 0; ii < airports.size(); ii++) {
if (airports.get(ii).getAirportCode().equals(airportCode)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-loader/src/main/java/com/acmeair/loader/CustomerLoader.java | acmeair-loader/src/main/java/com/acmeair/loader/CustomerLoader.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.loader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.service.CustomerService;
import com.acmeair.service.ServiceLocator;
public class CustomerLoader {
private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class);
public void loadCustomers(long numCustomers) {
CustomerAddress address = customerService.createAddress("123 Main St.", null, "Anytown", "NC", "USA", "27617");
for (long ii = 0; ii < numCustomers; ii++) {
customerService.createCustomer("uid"+ii+"@email.com", "password", Customer.MemberShipStatus.GOLD, 1000000, 1000, "919-123-4567", PhoneType.BUSINESS, address);
}
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-loader/src/main/java/com/acmeair/loader/Loader.java | acmeair-loader/src/main/java/com/acmeair/loader/Loader.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.loader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;
public class Loader {
public static String REPOSITORY_LOOKUP_KEY = "com.acmeair.repository.type";
private static Logger logger = Logger.getLogger(Loader.class.getName());
public String queryLoader() {
String message = System.getProperty("loader.numCustomers");
if (message == null){
logger.info("The system property 'loader.numCustomers' has not been set yet. Looking up the default properties.");
lookupDefaults();
message = System.getProperty("loader.numCustomers");
}
return message;
}
public String loadDB(long numCustomers) {
String message = "";
if(numCustomers == -1)
message = execute();
else {
System.setProperty("loader.numCustomers", Long.toString(numCustomers));
message = execute(numCustomers);
}
return message;
}
public static void main(String args[]) throws Exception {
Loader loader = new Loader();
loader.execute();
}
private String execute() {
String numCustomers = System.getProperty("loader.numCustomers");
if (numCustomers == null){
logger.info("The system property 'loader.numCustomers' has not been set yet. Looking up the default properties.");
lookupDefaults();
numCustomers = System.getProperty("loader.numCustomers");
}
return execute(Long.parseLong(numCustomers));
}
private String execute(long numCustomers) {
FlightLoader flightLoader = new FlightLoader();
CustomerLoader customerLoader = new CustomerLoader();
double length = 0;
try {
long start = System.currentTimeMillis();
logger.info("Start loading flights");
flightLoader.loadFlights();
logger.info("Start loading " + numCustomers + " customers");
customerLoader.loadCustomers(numCustomers);
long stop = System.currentTimeMillis();
logger.info("Finished loading in " + (stop - start)/1000.0 + " seconds");
length = (stop - start)/1000.0;
}
catch (Exception e) {
e.printStackTrace();
}
return "Loaded flights and " + numCustomers + " customers in " + length + " seconds";
}
private void lookupDefaults (){
Properties props = getProperties();
String numCustomers = props.getProperty("loader.numCustomers","100");
System.setProperty("loader.numCustomers", numCustomers);
}
private Properties getProperties(){
/*
* Get Properties from loader.properties file.
* If the file does not exist, use default values
*/
Properties props = new Properties();
String propFileName = "/loader.properties";
try{
InputStream propFileStream = Loader.class.getResourceAsStream(propFileName);
props.load(propFileStream);
// props.load(new FileInputStream(propFileName));
}catch(FileNotFoundException e){
logger.info("Property file " + propFileName + " not found.");
}catch(IOException e){
logger.info("IOException - Property file " + propFileName + " not found.");
}
return props;
}
/*
private void execute(String args[]) {
ApplicationContext ctx = null;
//
// Get Properties from loader.properties file.
// If the file does not exist, use default values
//
Properties props = new Properties();
String propFileName = "/loader.properties";
try{
InputStream propFileStream = Loader.class.getResourceAsStream(propFileName);
props.load(propFileStream);
// props.load(new FileInputStream(propFileName));
}catch(FileNotFoundException e){
logger.info("Property file " + propFileName + " not found.");
}catch(IOException e){
logger.info("IOException - Property file " + propFileName + " not found.");
}
String numCustomers = props.getProperty("loader.numCustomers","100");
System.setProperty("loader.numCustomers", numCustomers);
String type = null;
String lookup = REPOSITORY_LOOKUP_KEY.replace('.', '/');
javax.naming.Context context = null;
javax.naming.Context envContext;
try {
context = new javax.naming.InitialContext();
envContext = (javax.naming.Context) context.lookup("java:comp/env");
if (envContext != null)
type = (String) envContext.lookup(lookup);
} catch (NamingException e) {
// e.printStackTrace();
}
if (type != null) {
logger.info("Found repository in web.xml:" + type);
}
else if (context != null) {
try {
type = (String) context.lookup(lookup);
if (type != null)
logger.info("Found repository in server.xml:" + type);
} catch (NamingException e) {
// e.printStackTrace();
}
}
if (type == null) {
type = System.getProperty(REPOSITORY_LOOKUP_KEY);
if (type != null)
logger.info("Found repository in jvm property:" + type);
else {
type = System.getenv(REPOSITORY_LOOKUP_KEY);
if (type != null)
logger.info("Found repository in environment property:" + type);
}
}
if (type ==null) // Default to wxsdirect
{
type = "wxsdirect";
logger.info("Using default repository :" + type);
}
if (type.equals("wxsdirect"))
ctx = new AnnotationConfigApplicationContext(WXSDirectAppConfig.class);
else if (type.equals("mongodirect"))
ctx = new AnnotationConfigApplicationContext(MongoDirectAppConfig.class);
else
{
logger.info("Did not find a matching config. Using default repository wxsdirect instead");
ctx = new AnnotationConfigApplicationContext(WXSDirectAppConfig.class);
}
FlightLoader flightLoader = ctx.getBean(FlightLoader.class);
CustomerLoader customerLoader = ctx.getBean(CustomerLoader.class);
try {
long start = System.currentTimeMillis();
logger.info("Start loading flights");
flightLoader.loadFlights();
logger.info("Start loading " + numCustomers + " customers");
customerLoader.loadCustomers(Long.parseLong(numCustomers));
long stop = System.currentTimeMillis();
logger.info("Finished loading in " + (stop - start)/1000.0 + " seconds");
}
catch (Exception e) {
e.printStackTrace();
}
}
*/
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/entities/BookingPK.java | acmeair-services-wxs/src/main/java/com/acmeair/entities/BookingPK.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface BookingPK {
public String getId();
public String getCustomerId();
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/entities/FlightPK.java | acmeair-services-wxs/src/main/java/com/acmeair/entities/FlightPK.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.entities;
public interface FlightPK {
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/WXSConstants.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/WXSConstants.java | package com.acmeair.wxs;
public interface WXSConstants {
public static final String JNDI_NAME = "wxs/acmeair";
public static final String KEY = "wxs";
public static final String KEY_DESCRIPTION = "eXtreme Scale";
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/FlightServiceImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/FlightServiceImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.acmeair.entities.AirportCodeMapping;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.service.BookingService;
import com.acmeair.service.DataService;
import com.acmeair.service.FlightService;
import com.acmeair.service.KeyGenerator;
import com.acmeair.wxs.WXSConstants;
import com.acmeair.wxs.entities.AirportCodeMappingImpl;
import com.acmeair.wxs.entities.FlightImpl;
import com.acmeair.wxs.entities.FlightSegmentImpl;
import com.acmeair.wxs.utils.WXSSessionManager;
import com.ibm.websphere.objectgrid.ObjectGrid;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectMap;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.UndefinedMapException;
import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException;
import com.ibm.websphere.objectgrid.plugins.index.MapIndex;
import com.ibm.websphere.objectgrid.plugins.index.MapIndexPlugin;
@DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION)
public class FlightServiceImpl extends FlightService implements WXSConstants {
private static String FLIGHT_MAP_NAME="Flight";
private static String FLIGHT_SEGMENT_MAP_NAME="FlightSegment";
private static String AIRPORT_CODE_MAPPING_MAP_NAME="AirportCodeMapping";
private static String BASE_FLIGHT_MAP_NAME="Flight";
private static String BASE_FLIGHT_SEGMENT_MAP_NAME="FlightSegment";
private static String BASE_AIRPORT_CODE_MAPPING_MAP_NAME="AirportCodeMapping";
private final static Logger logger = Logger.getLogger(BookingService.class.getName());
private ObjectGrid og;
@Inject
KeyGenerator keyGenerator;
@PostConstruct
private void initialization() {
try {
og = WXSSessionManager.getSessionManager().getObjectGrid();
FLIGHT_MAP_NAME = BASE_FLIGHT_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
FLIGHT_SEGMENT_MAP_NAME = BASE_FLIGHT_SEGMENT_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
AIRPORT_CODE_MAPPING_MAP_NAME = BASE_AIRPORT_CODE_MAPPING_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
} catch (ObjectGridException e) {
logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage());
}
}
@Override
public Long countFlights() {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(FLIGHT_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME);
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
/*
int partitions = og.getMap(FLIGHT_MAP_NAME).getPartitionManager().getNumOfPartitions();
Long result = 0L;
ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + FLIGHT_MAP_NAME + " o ");
for(int i = 0; i<partitions;i++){
query.setPartition(i);
result += (Long) query.getSingleResult();
}
*/
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
@Override
public Long countAirports() {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(AIRPORT_CODE_MAPPING_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME);
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
@Override
public Long countFlightSegments() {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME);
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
/*
int partitions = og.getMap(FLIGHT_SEGMENT_MAP_NAME).getPartitionManager().getNumOfPartitions();
Long result = 0L;
ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + FLIGHT_SEGMENT_MAP_NAME + " o ");
for(int i = 0; i<partitions;i++){
query.setPartition(i);
result += (Long) query.getSingleResult();
}
*/
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
/*
public Flight getFlightByFlightKey(FlightPK key) {
try {
Flight flight;
flight = flightPKtoFlightCache.get(key);
if (flight == null) {
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(key.getFlightSegmentId());
for (Flight f : flightsBySegment) {
if (f.getPkey().getId().equals(key.getId())) {
flightPKtoFlightCache.putIfAbsent(key, f);
flight = f;
break;
}
}
}
return flight;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
*/
@Override
protected Flight getFlight(String flightId, String flightSegmentId) {
try {
if(logger.isLoggable(Level.FINER))
logger.finer("in WXS getFlight. search for flightId = '" + flightId + "' and flightSegmentId = '"+flightSegmentId+"'");
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<FlightImpl> flightsBySegment = (HashSet<FlightImpl>)flightMap.get(flightSegmentId);
for (FlightImpl flight : flightsBySegment) {
if (flight.getFlightId().equals(flightId)) {
return flight;
}
}
logger.warning("No matching flights found for flightId =" + flightId + " and flightSegment " + flightSegmentId);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected FlightSegment getFlightSegment(String fromAirport, String toAirport) {
try {
Session session = null;
// boolean startedTran = false;
//session = sessionManager.getObjectGridSession();
session = og.getSession();
FlightSegment segment = null;
/* if (!session.isTransactionActive()) {
startedTran = true;
session.begin();
}
*/
ObjectMap flightSegmentMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<FlightSegment> segmentsByOrigPort = (HashSet<FlightSegment>)flightSegmentMap.get(fromAirport);
if (segmentsByOrigPort!=null) {
for (FlightSegment fs : segmentsByOrigPort) {
if (fs.getDestPort().equals(toAirport)) {
segment = fs;
return segment;
}
}
}
if (segment == null) {
segment = new FlightSegmentImpl(); // put a sentinel value of a non-populated flightsegment
}
// if (startedTran)
// session.commit();
return segment;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate){
try {
List<Flight> flights = new ArrayList<Flight>();
Session session = null;
boolean startedTran = false;
if (session == null) {
//session = sessionManager.getObjectGridSession();
session = og.getSession();
if (!session.isTransactionActive()) {
startedTran = true;
session.begin();
}
}
ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(segment.getFlightName());
if(deptDate != null){
for (Flight f : flightsBySegment) {
if (areDatesSameWithNoTime(f.getScheduledDepartureTime(), deptDate)) {
f.setFlightSegment(segment);
flights.add(f);
}
}
} else {
for (Flight f : flightsBySegment) {
f.setFlightSegment(segment);
flights.add(f);
}
}
if (startedTran)
session.commit();
return flights;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static boolean areDatesSameWithNoTime(Date d1, Date d2) {
return getDateWithNoTime(d1).equals(getDateWithNoTime(d2));
}
private static Date getDateWithNoTime(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
@Override
public void storeAirportMapping(AirportCodeMapping mapping) {
try{
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap airportCodeMappingMap = session.getMap(AIRPORT_CODE_MAPPING_MAP_NAME);
airportCodeMappingMap.upsert(mapping.getAirportCode(), mapping);
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName){
AirportCodeMapping acm = new AirportCodeMappingImpl(airportCode, airportName);
return acm;
}
@Override
public Flight createNewFlight(String flightSegmentId,
Date scheduledDepartureTime, Date scheduledArrivalTime,
BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
int numFirstClassSeats, int numEconomyClassSeats,
String airplaneTypeId) {
try{
String id = keyGenerator.generate().toString();
Flight flight = new FlightImpl(id, flightSegmentId,
scheduledDepartureTime, scheduledArrivalTime,
firstClassBaseCost, economyClassBaseCost,
numFirstClassSeats, numEconomyClassSeats,
airplaneTypeId);
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap flightMap = session.getMap(FLIGHT_MAP_NAME);
//flightMap.insert(flight.getPkey(), flight);
//return flight;
@SuppressWarnings("unchecked")
HashSet<Flight> flightsBySegment = (HashSet<Flight>)flightMap.get(flightSegmentId);
if (flightsBySegment == null) {
flightsBySegment = new HashSet<Flight>();
}
if (!flightsBySegment.contains(flight)) {
flightsBySegment.add(flight);
flightMap.upsert(flightSegmentId, flightsBySegment);
}
return flight;
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public void storeFlightSegment(FlightSegment flightSeg) {
try {
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap flightSegmentMap = session.getMap(FLIGHT_SEGMENT_MAP_NAME);
// TODO: Consider moving this to a ArrayList - List ??
@SuppressWarnings("unchecked")
HashSet<FlightSegment> segmentsByOrigPort = (HashSet<FlightSegment>)flightSegmentMap.get(flightSeg.getOriginPort());
if (segmentsByOrigPort == null) {
segmentsByOrigPort = new HashSet<FlightSegment>();
}
if (!segmentsByOrigPort.contains(flightSeg)) {
segmentsByOrigPort.add(flightSeg);
flightSegmentMap.upsert(flightSeg.getOriginPort(), segmentsByOrigPort);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void storeFlightSegment(String flightName, String origPort, String destPort, int miles) {
FlightSegment flightSeg = new FlightSegmentImpl(flightName, origPort, destPort, miles);
storeFlightSegment(flightSeg);
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/CustomerServiceImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/CustomerServiceImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.service;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.BookingService;
import com.acmeair.service.CustomerService;
import com.acmeair.service.DataService;
import com.acmeair.service.KeyGenerator;
import com.acmeair.wxs.WXSConstants;
import com.acmeair.wxs.entities.CustomerAddressImpl;
import com.acmeair.wxs.entities.CustomerImpl;
import com.acmeair.wxs.entities.CustomerSessionImpl;
import com.acmeair.wxs.utils.WXSSessionManager;
import com.ibm.websphere.objectgrid.ObjectGrid;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectMap;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.UndefinedMapException;
import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException;
import com.ibm.websphere.objectgrid.plugins.index.MapIndex;
import com.ibm.websphere.objectgrid.plugins.index.MapIndexPlugin;
@Default
@DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION)
public class CustomerServiceImpl extends CustomerService implements WXSConstants{
private static String BASE_CUSTOMER_MAP_NAME="Customer";
private static String BASE_CUSTOMER_SESSION_MAP_NAME="CustomerSession";
private static String CUSTOMER_MAP_NAME="Customer";
private static String CUSTOMER_SESSION_MAP_NAME="CustomerSession";
private final static Logger logger = Logger.getLogger(BookingService.class.getName());
private ObjectGrid og;
@Inject
KeyGenerator keyGenerator;
@PostConstruct
private void initialization() {
try {
og = WXSSessionManager.getSessionManager().getObjectGrid();
CUSTOMER_MAP_NAME = BASE_CUSTOMER_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
CUSTOMER_SESSION_MAP_NAME = BASE_CUSTOMER_SESSION_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
} catch (ObjectGridException e) {
logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage());
}
}
@Override
public Long count () {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(CUSTOMER_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME);
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
/*
int partitions = og.getMap(CUSTOMER_MAP_NAME).getPartitionManager().getNumOfPartitions();
ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + CUSTOMER_MAP_NAME + " o ");
for(int i = 0; i<partitions;i++){
query.setPartition(i);
result += (Long) query.getSingleResult();
}
*/
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
@Override
public Long countSessions () {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(CUSTOMER_SESSION_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex(MapIndexPlugin.SYSTEM_KEY_INDEX_NAME);
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
/*
int partitions = og.getMap(CUSTOMER_SESSION_MAP_NAME).getPartitionManager().getNumOfPartitions();
Long result = 0L;
ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + CUSTOMER_SESSION_MAP_NAME + " o ");
for(int i = 0; i<partitions;i++){
query.setPartition(i);
result += (Long) query.getSingleResult();
}
*/
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
@Override
public Customer createCustomer(String username, String password,
MemberShipStatus status, int total_miles, int miles_ytd,
String phoneNumber, PhoneType phoneNumberType,
CustomerAddress address) {
try{
Customer customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType);
// Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME);
customerMap.insert(customer.getUsername(), customer);
return customer;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public CustomerAddress createAddress (String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode){
CustomerAddress address = new CustomerAddressImpl(streetAddress1, streetAddress2,
city, stateProvince, country, postalCode);
return address;
}
@Override
public Customer updateCustomer(Customer customer) {
try{
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME);
customerMap.update(customer.getUsername(), customer);
return customer;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected Customer getCustomer(String username) {
try{
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap customerMap = session.getMap(CUSTOMER_MAP_NAME);
Customer c = (Customer) customerMap.get(username);
return c;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected CustomerSession getSession(String sessionid){
try {
Session session = og.getSession();
ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME);
return (CustomerSession)customerSessionMap.get(sessionid);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected void removeSession(CustomerSession session){
try {
Session ogSession = og.getSession();
ObjectMap customerSessionMap = ogSession.getMap(CUSTOMER_SESSION_MAP_NAME);
customerSessionMap.remove(session.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration) {
try{
CustomerSession cSession = new CustomerSessionImpl(sessionId, customerId, creation, expiration);
// Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME);
customerSessionMap.insert(cSession.getId(), cSession);
return cSession;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void invalidateSession(String sessionid) {
try{
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap customerSessionMap = session.getMap(CUSTOMER_SESSION_MAP_NAME);
customerSessionMap.remove(sessionid);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/BookingServiceImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/service/BookingServiceImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import com.acmeair.entities.Booking;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Flight;
import com.acmeair.service.BookingService;
import com.acmeair.service.CustomerService;
import com.acmeair.service.DataService;
import com.acmeair.service.FlightService;
import com.acmeair.service.KeyGenerator;
import com.acmeair.service.ServiceLocator;
import com.acmeair.wxs.WXSConstants;
import com.acmeair.wxs.entities.BookingImpl;
import com.acmeair.wxs.entities.BookingPKImpl;
import com.acmeair.wxs.entities.FlightPKImpl;
import com.acmeair.wxs.utils.WXSSessionManager;
import com.ibm.websphere.objectgrid.ObjectGrid;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectMap;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.UndefinedMapException;
import com.ibm.websphere.objectgrid.plugins.TransactionCallbackException;
import com.ibm.websphere.objectgrid.plugins.index.MapIndex;
@DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION)
public class BookingServiceImpl implements BookingService, WXSConstants {
private final static Logger logger = Logger.getLogger(BookingService.class.getName());
private static String BOOKING_MAP_NAME="Booking";
private static String BASE_BOOKING_MAP_NAME="Booking";
private ObjectGrid og;
@Inject
private KeyGenerator keyGenerator;
private FlightService flightService = ServiceLocator.instance().getService(FlightService.class);
private CustomerService customerService = ServiceLocator.instance().getService(CustomerService.class);
@PostConstruct
private void initialization() {
try {
og = WXSSessionManager.getSessionManager().getObjectGrid();
BOOKING_MAP_NAME = BASE_BOOKING_MAP_NAME + WXSSessionManager.getSessionManager().getMapSuffix();
} catch (ObjectGridException e) {
logger.severe("Unable to retreive the ObjectGrid reference " + e.getMessage());
}
}
public BookingPKImpl bookFlight(String customerId, FlightPKImpl flightId) {
try{
// We still delegate to the flight and customer service for the map access than getting the map instance directly
Flight f = flightService.getFlightByFlightId(flightId.getId(), flightId.getFlightSegmentId());
Customer c = customerService.getCustomerByUsername(customerId);
BookingImpl newBooking = new BookingImpl(keyGenerator.generate().toString(), new Date(), c, f);
BookingPKImpl key = newBooking.getPkey();
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<Booking> bookingsByUser = (HashSet<Booking>)bookingMap.get(customerId);
if (bookingsByUser == null) {
bookingsByUser = new HashSet<Booking>();
}
if (bookingsByUser.contains(newBooking)) {
throw new Exception("trying to book a duplicate booking");
}
bookingsByUser.add(newBooking);
bookingMap.upsert(customerId, bookingsByUser);
return key;
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public String bookFlight(String customerId, String flightSegmentId, String id) {
if(logger.isLoggable(Level.FINER))
logger.finer("WXS booking service, bookFlight with customerId = '"+ customerId+"', flightSegmentId = '"+ flightSegmentId + "', and id = '" + id + "'");
return bookFlight(customerId, new FlightPKImpl(flightSegmentId, id)).getId();
}
@Override
public Booking getBooking(String user, String id) {
try{
//Session session = sessionManager.getObjectGridSession();
Session session = og.getSession();
ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME);
// return (Booking)bookingMap.get(new BookingPK(user, id));
@SuppressWarnings("unchecked")
HashSet<BookingImpl> bookingsByUser = (HashSet<BookingImpl>)bookingMap.get(user);
if (bookingsByUser == null) {
return null;
}
for (BookingImpl b : bookingsByUser) {
if (b.getPkey().getId().equals(id)) {
return b;
}
}
return null;
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public void cancelBooking(String user, String id) {
try{
Session session = og.getSession();
//Session session = sessionManager.getObjectGridSession();
ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<BookingImpl> bookingsByUser = (HashSet<BookingImpl>)bookingMap.get(user);
if (bookingsByUser == null) {
return;
}
boolean found = false;
HashSet<Booking> newBookings = new HashSet<Booking>();
for (BookingImpl b : bookingsByUser) {
if (b.getPkey().getId().equals(id)) {
found = true;
}
else {
newBookings.add(b);
}
}
if (found) {
bookingMap.upsert(user, newBookings);
}
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public List<Booking> getBookingsByUser(String user) {
try{
Session session = og.getSession();
//Session session = sessionManager.getObjectGridSession();
boolean startedTran = false;
if (!session.isTransactionActive()) {
startedTran = true;
session.begin();
}
ObjectMap bookingMap = session.getMap(BOOKING_MAP_NAME);
@SuppressWarnings("unchecked")
HashSet<Booking> bookingsByUser = (HashSet<Booking>)bookingMap.get(user);
if (bookingsByUser == null) {
bookingsByUser = new HashSet<Booking>();
}
ArrayList<Booking> bookingsList = new ArrayList<Booking>();
for (Booking b : bookingsByUser) {
bookingsList.add(b);
}
if (startedTran)
session.commit();
return bookingsList;
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Override
public Long count () {
try {
Session session = og.getSession();
ObjectMap objectMap = session.getMap(BOOKING_MAP_NAME);
MapIndex mapIndex = (MapIndex)objectMap.getIndex("com.ibm.ws.objectgrid.builtin.map.KeyIndex");
Iterator<?> keyIterator = mapIndex.findAll();
Long result = 0L;
while(keyIterator.hasNext()) {
keyIterator.next();
result++;
}
/*
int partitions = og.getMap(BOOKING_MAP_NAME).getPartitionManager().getNumOfPartitions();
Long result = 0L;
ObjectQuery query = og.getSession().createObjectQuery("SELECT COUNT ( o ) FROM " + BOOKING_MAP_NAME + " o ");
for(int i = 0; i<partitions;i++){
query.setPartition(i);
result += (Long) query.getSingleResult();
}
*/
return result;
} catch (UndefinedMapException e) {
e.printStackTrace();
} catch (TransactionCallbackException e) {
e.printStackTrace();
} catch (ObjectGridException e) {
e.printStackTrace();
}
return -1L;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingPKImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingPKImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import com.acmeair.entities.BookingPK;
import com.ibm.websphere.objectgrid.plugins.PartitionableKey;
public class BookingPKImpl implements BookingPK, Serializable, PartitionableKey {
private static final long serialVersionUID = 1L;
private String id;
private String customerId;
public BookingPKImpl() {
super();
}
public BookingPKImpl(String customerId,String id) {
super();
this.id = id;
this.customerId = customerId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
@Override
public Object ibmGetPartition() {
return this.customerId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookingPKImpl other = (BookingPKImpl) obj;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "BookingPK [customerId=" + customerId + ",id=" + id + "]";
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/BookingImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import java.util.*;
import com.acmeair.entities.Booking;
import com.acmeair.entities.Customer;
import com.acmeair.entities.Flight;
public class BookingImpl implements Booking, Serializable{
private static final long serialVersionUID = 1L;
private BookingPKImpl pkey;
private FlightPKImpl flightKey;
private Date dateOfBooking;
private Customer customer;
private Flight flight;
public BookingImpl() {
}
public BookingImpl(String id, Date dateOfFlight, Customer customer, Flight flight) {
this(id, dateOfFlight, customer, (FlightImpl)flight);
}
public BookingImpl(String id, Date dateOfFlight, Customer customer, FlightImpl flight) {
this.pkey = new BookingPKImpl(customer.getUsername(),id);
this.flightKey = flight.getPkey();
this.dateOfBooking = dateOfFlight;
this.customer = customer;
this.flight = flight;
}
public BookingPKImpl getPkey() {
return pkey;
}
// adding the method for index calculation
public String getCustomerId() {
return pkey.getCustomerId();
}
public void setPkey(BookingPKImpl pkey) {
this.pkey = pkey;
}
public FlightPKImpl getFlightKey() {
return flightKey;
}
public void setFlightKey(FlightPKImpl flightKey) {
this.flightKey = flightKey;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public Date getDateOfBooking() {
return dateOfBooking;
}
public void setDateOfBooking(Date dateOfBooking) {
this.dateOfBooking = dateOfBooking;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Flight getFlight() {
return flight;
}
@Override
public String toString() {
return "Booking [key=" + pkey + ", flightKey=" + flightKey
+ ", dateOfBooking=" + dateOfBooking + ", customer=" + customer
+ ", flight=" + flight + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BookingImpl other = (BookingImpl) obj;
if (customer == null) {
if (other.customer != null)
return false;
} else if (!customer.equals(other.customer))
return false;
if (dateOfBooking == null) {
if (other.dateOfBooking != null)
return false;
} else if (!dateOfBooking.equals(other.dateOfBooking))
return false;
if (flight == null) {
if (other.flight != null)
return false;
} else if (!flight.equals(other.flight))
return false;
if (flightKey == null) {
if (other.flightKey != null)
return false;
} else if (!flightKey.equals(other.flightKey))
return false;
if (pkey == null) {
if (other.pkey != null)
return false;
} else if (!pkey.equals(other.pkey))
return false;
return true;
}
@Override
public String getBookingId() {
return pkey.getId();
}
@Override
public String getFlightId() {
return flight.getFlightId();
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
public class FlightImpl implements Flight, Serializable{
private static final long serialVersionUID = 1L;
private FlightPKImpl pkey;
private Date scheduledDepartureTime;
private Date scheduledArrivalTime;
private BigDecimal firstClassBaseCost;
private BigDecimal economyClassBaseCost;
private int numFirstClassSeats;
private int numEconomyClassSeats;
private String airplaneTypeId;
private FlightSegment flightSegment;
public FlightImpl() {
}
public FlightImpl(String id, String flightSegmentId,
Date scheduledDepartureTime, Date scheduledArrivalTime,
BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
int numFirstClassSeats, int numEconomyClassSeats,
String airplaneTypeId) {
this.pkey = new FlightPKImpl(flightSegmentId,id);
this.scheduledDepartureTime = scheduledDepartureTime;
this.scheduledArrivalTime = scheduledArrivalTime;
this.firstClassBaseCost = firstClassBaseCost;
this.economyClassBaseCost = economyClassBaseCost;
this.numFirstClassSeats = numFirstClassSeats;
this.numEconomyClassSeats = numEconomyClassSeats;
this.airplaneTypeId = airplaneTypeId;
}
public FlightPKImpl getPkey() {
return pkey;
}
public void setPkey(FlightPKImpl pkey) {
this.pkey = pkey;
}
@Override
public String getFlightId() {
return pkey.getId();
}
@Override
public void setFlightId(String id) {
pkey.setId(id);
}
// The method is needed for index calculation
public String getFlightSegmentId()
{
return pkey.getFlightSegmentId();
}
public Date getScheduledDepartureTime() {
return scheduledDepartureTime;
}
public void setScheduledDepartureTime(Date scheduledDepartureTime) {
this.scheduledDepartureTime = scheduledDepartureTime;
}
public Date getScheduledArrivalTime() {
return scheduledArrivalTime;
}
public void setScheduledArrivalTime(Date scheduledArrivalTime) {
this.scheduledArrivalTime = scheduledArrivalTime;
}
public BigDecimal getFirstClassBaseCost() {
return firstClassBaseCost;
}
public void setFirstClassBaseCost(BigDecimal firstClassBaseCost) {
this.firstClassBaseCost = firstClassBaseCost;
}
public BigDecimal getEconomyClassBaseCost() {
return economyClassBaseCost;
}
public void setEconomyClassBaseCost(BigDecimal economyClassBaseCost) {
this.economyClassBaseCost = economyClassBaseCost;
}
public int getNumFirstClassSeats() {
return numFirstClassSeats;
}
public void setNumFirstClassSeats(int numFirstClassSeats) {
this.numFirstClassSeats = numFirstClassSeats;
}
public int getNumEconomyClassSeats() {
return numEconomyClassSeats;
}
public void setNumEconomyClassSeats(int numEconomyClassSeats) {
this.numEconomyClassSeats = numEconomyClassSeats;
}
public String getAirplaneTypeId() {
return airplaneTypeId;
}
public void setAirplaneTypeId(String airplaneTypeId) {
this.airplaneTypeId = airplaneTypeId;
}
public FlightSegment getFlightSegment() {
return flightSegment;
}
public void setFlightSegment(FlightSegment flightSegment) {
this.flightSegment = flightSegment;
}
@Override
public String toString() {
return "Flight key="+pkey
+ ", scheduledDepartureTime=" + scheduledDepartureTime
+ ", scheduledArrivalTime=" + scheduledArrivalTime
+ ", firstClassBaseCost=" + firstClassBaseCost
+ ", economyClassBaseCost=" + economyClassBaseCost
+ ", numFirstClassSeats=" + numFirstClassSeats
+ ", numEconomyClassSeats=" + numEconomyClassSeats
+ ", airplaneTypeId=" + airplaneTypeId + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightImpl other = (FlightImpl) obj;
if (airplaneTypeId == null) {
if (other.airplaneTypeId != null)
return false;
} else if (!airplaneTypeId.equals(other.airplaneTypeId))
return false;
if (economyClassBaseCost == null) {
if (other.economyClassBaseCost != null)
return false;
} else if (!economyClassBaseCost.equals(other.economyClassBaseCost))
return false;
if (firstClassBaseCost == null) {
if (other.firstClassBaseCost != null)
return false;
} else if (!firstClassBaseCost.equals(other.firstClassBaseCost))
return false;
if (flightSegment == null) {
if (other.flightSegment != null)
return false;
} else if (!flightSegment.equals(other.flightSegment))
return false;
if (pkey == null) {
if (other.pkey != null)
return false;
} else if (!pkey.equals(other.pkey))
return false;
if (numEconomyClassSeats != other.numEconomyClassSeats)
return false;
if (numFirstClassSeats != other.numFirstClassSeats)
return false;
if (scheduledArrivalTime == null) {
if (other.scheduledArrivalTime != null)
return false;
} else if (!scheduledArrivalTime.equals(other.scheduledArrivalTime))
return false;
if (scheduledDepartureTime == null) {
if (other.scheduledDepartureTime != null)
return false;
} else if (!scheduledDepartureTime.equals(other.scheduledDepartureTime))
return false;
return true;
}
/*
public void setFlightSegmentId(String segmentId) {
pkey.setFlightSegmentId(segmentId);
}
*/
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/AirportCodeMappingImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/AirportCodeMappingImpl.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import com.acmeair.entities.AirportCodeMapping;
public class AirportCodeMappingImpl implements AirportCodeMapping, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String airportName;
public AirportCodeMappingImpl() {
}
public AirportCodeMappingImpl(String airportCode, String airportName) {
this._id = airportCode;
this.airportName = airportName;
}
public String getAirportCode() {
return _id;
}
public void setAirportCode(String airportCode) {
this._id = airportCode;
}
public String getAirportName() {
return airportName;
}
public void setAirportName(String airportName) {
this.airportName = airportName;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightPKImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightPKImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import com.acmeair.entities.FlightPK;
import com.ibm.websphere.objectgrid.plugins.PartitionableKey;
public class FlightPKImpl implements FlightPK, Serializable, PartitionableKey {
private static final long serialVersionUID = 1L;
private String id;
private String flightSegmentId;
public FlightPKImpl() {
super();
}
public FlightPKImpl(String flightSegmentId,String id) {
super();
this.id = id;
this.flightSegmentId = flightSegmentId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFlightSegmentId() {
return flightSegmentId;
}
public void setFlightSegmentId(String flightSegmentId) {
this.flightSegmentId = flightSegmentId;
}
@Override
public Object ibmGetPartition() {
return this.flightSegmentId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((flightSegmentId == null) ? 0 : flightSegmentId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightPKImpl other = (FlightPKImpl) obj;
if (flightSegmentId == null) {
if (other.flightSegmentId != null)
return false;
} else if (!flightSegmentId.equals(other.flightSegmentId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "FlightPK [flightSegmentId=" + flightSegmentId +",id=" + id+ "]";
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightSegmentImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/FlightSegmentImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import com.acmeair.entities.FlightSegment;
public class FlightSegmentImpl implements FlightSegment, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String originPort;
private String destPort;
private int miles;
public FlightSegmentImpl() {
}
public FlightSegmentImpl(String flightName, String origPort, String destPort, int miles) {
this._id = flightName;
this.originPort = origPort;
this.destPort = destPort;
this.miles = miles;
}
public String getFlightName() {
return _id;
}
public void setFlightName(String flightName) {
this._id = flightName;
}
public String getOriginPort() {
return originPort;
}
public void setOriginPort(String originPort) {
this.originPort = originPort;
}
public String getDestPort() {
return destPort;
}
public void setDestPort(String destPort) {
this.destPort = destPort;
}
public int getMiles() {
return miles;
}
public void setMiles(int miles) {
this.miles = miles;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("FlightSegment ").append(_id).append(" originating from:\"").append(originPort).append("\" arriving at:\"").append(destPort).append("\"");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FlightSegmentImpl other = (FlightSegmentImpl) obj;
if (destPort == null) {
if (other.destPort != null)
return false;
} else if (!destPort.equals(other.destPort))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (miles != other.miles)
return false;
if (originPort == null) {
if (other.originPort != null)
return false;
} else if (!originPort.equals(other.originPort))
return false;
return true;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerSessionImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerSessionImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import java.util.Date;
import com.acmeair.entities.CustomerSession;
public class CustomerSessionImpl implements CustomerSession, Serializable {
private static final long serialVersionUID = 1L;
private String _id;
private String customerid;
private Date lastAccessedTime;
private Date timeoutTime;
public CustomerSessionImpl() {
}
public CustomerSessionImpl(String id, String customerid, Date lastAccessedTime, Date timeoutTime) {
this._id= id;
this.customerid = customerid;
this.lastAccessedTime = lastAccessedTime;
this.timeoutTime = timeoutTime;
}
public String getId() {
return _id;
}
public void setId(String id) {
this._id = id;
}
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
public Date getLastAccessedTime() {
return lastAccessedTime;
}
public void setLastAccessedTime(Date lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
}
public Date getTimeoutTime() {
return timeoutTime;
}
public void setTimeoutTime(Date timeoutTime) {
this.timeoutTime = timeoutTime;
}
@Override
public String toString() {
return "CustomerSession [id=" + _id + ", customerid=" + customerid
+ ", lastAccessedTime=" + lastAccessedTime + ", timeoutTime="
+ timeoutTime + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerSessionImpl other = (CustomerSessionImpl) obj;
if (customerid == null) {
if (other.customerid != null)
return false;
} else if (!customerid.equals(other.customerid))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (lastAccessedTime == null) {
if (other.lastAccessedTime != null)
return false;
} else if (!lastAccessedTime.equals(other.lastAccessedTime))
return false;
if (timeoutTime == null) {
if (other.timeoutTime != null)
return false;
} else if (!timeoutTime.equals(other.timeoutTime))
return false;
return true;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
public class CustomerImpl implements Customer, Serializable{
private static final long serialVersionUID = 1L;
private String _id;
private String password;
private MemberShipStatus status;
private int total_miles;
private int miles_ytd;
private CustomerAddress address;
private String phoneNumber;
private PhoneType phoneNumberType;
public CustomerImpl() {
}
public CustomerImpl(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, CustomerAddress address, String phoneNumber, PhoneType phoneNumberType) {
this._id = username;
this.password = password;
this.status = status;
this.total_miles = total_miles;
this.miles_ytd = miles_ytd;
this.address = address;
this.phoneNumber = phoneNumber;
this.phoneNumberType = phoneNumberType;
}
@Override
public String getCustomerId() {
return _id;
}
public String getUsername() {
return _id;
}
public void setUsername(String username) {
this._id = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberShipStatus getStatus() {
return status;
}
public void setStatus(MemberShipStatus status) {
this.status = status;
}
public int getTotal_miles() {
return total_miles;
}
public void setTotal_miles(int total_miles) {
this.total_miles = total_miles;
}
public int getMiles_ytd() {
return miles_ytd;
}
public void setMiles_ytd(int miles_ytd) {
this.miles_ytd = miles_ytd;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public PhoneType getPhoneNumberType() {
return phoneNumberType;
}
public void setPhoneNumberType(PhoneType phoneNumberType) {
this.phoneNumberType = phoneNumberType;
}
public CustomerAddress getAddress() {
return address;
}
public void setAddress(CustomerAddress address) {
this.address = address;
}
@Override
public String toString() {
return "Customer [id=" + _id + ", password=" + password + ", status="
+ status + ", total_miles=" + total_miles + ", miles_ytd="
+ miles_ytd + ", address=" + address + ", phoneNumber="
+ phoneNumber + ", phoneNumberType=" + phoneNumberType + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerImpl other = (CustomerImpl) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (_id == null) {
if (other._id != null)
return false;
} else if (!_id.equals(other._id))
return false;
if (miles_ytd != other.miles_ytd)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (phoneNumber == null) {
if (other.phoneNumber != null)
return false;
} else if (!phoneNumber.equals(other.phoneNumber))
return false;
if (phoneNumberType != other.phoneNumberType)
return false;
if (status != other.status)
return false;
if (total_miles != other.total_miles)
return false;
return true;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerAddressImpl.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/entities/CustomerAddressImpl.java | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.entities;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.acmeair.entities.CustomerAddress;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class CustomerAddressImpl implements CustomerAddress, Serializable{
private static final long serialVersionUID = 1L;
private String streetAddress1;
private String streetAddress2;
private String city;
private String stateProvince;
private String country;
private String postalCode;
public CustomerAddressImpl() {
}
public CustomerAddressImpl(String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode) {
super();
this.streetAddress1 = streetAddress1;
this.streetAddress2 = streetAddress2;
this.city = city;
this.stateProvince = stateProvince;
this.country = country;
this.postalCode = postalCode;
}
public String getStreetAddress1() {
return streetAddress1;
}
public void setStreetAddress1(String streetAddress1) {
this.streetAddress1 = streetAddress1;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
@Override
public String toString() {
return "CustomerAddress [streetAddress1=" + streetAddress1
+ ", streetAddress2=" + streetAddress2 + ", city=" + city
+ ", stateProvince=" + stateProvince + ", country=" + country
+ ", postalCode=" + postalCode + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerAddressImpl other = (CustomerAddressImpl) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (postalCode == null) {
if (other.postalCode != null)
return false;
} else if (!postalCode.equals(other.postalCode))
return false;
if (stateProvince == null) {
if (other.stateProvince != null)
return false;
} else if (!stateProvince.equals(other.stateProvince))
return false;
if (streetAddress1 == null) {
if (other.streetAddress1 != null)
return false;
} else if (!streetAddress1.equals(other.streetAddress1))
return false;
if (streetAddress2 == null) {
if (other.streetAddress2 != null)
return false;
} else if (!streetAddress2.equals(other.streetAddress2))
return false;
return true;
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/MapPutAllAgent.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/MapPutAllAgent.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectMap;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.datagrid.MapGridAgent;
import com.ibm.websphere.objectgrid.plugins.io.dataobject.SerializedKey;
public class MapPutAllAgent implements MapGridAgent {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(MapPutAllAgent.class.getName());
private HashMap<Object, HashMap<Object,Object>>objectsToSave = null ;
public HashMap<Object, HashMap<Object,Object>> getObjectsToSave() {
return objectsToSave;
}
public void setObjectsToSave(HashMap<Object,HashMap<Object,Object>> objectsToSave) {
this.objectsToSave = objectsToSave;
}
//@Override
public Object process(Session arg0, ObjectMap arg1, Object arg2) {
// The key is the partition key, can be either the PK or when partition field is defined the partition field value
try{
Object key;
// I need to find the real key as the hashmap is using the real key...
if( arg2 instanceof SerializedKey )
key = ((SerializedKey)arg2).getObject();
else
key = arg2;
HashMap<Object, Object> objectsForThePartition = this.objectsToSave.get(key);
if (objectsForThePartition==null)
logger.info("ERROR!!! Can not get the objects for partiton key:"+arg2);
else
{
Entry<Object, Object> entry;
Object value;
for (Iterator<Map.Entry<Object, Object>> itr = objectsForThePartition.entrySet().iterator(); itr.hasNext();)
{
entry = itr.next();
key = entry.getKey();
value = entry.getValue();
logger.finer("Save using agent:"+key+",value:"+value);
arg1.upsert(key, value);
}
}
}catch (ObjectGridException e)
{
logger.info("Getting exception:"+e);
}
return arg2;
}
//@Override
public Map<Object, Object> processAllEntries(Session arg0, ObjectMap arg1) {
return null;
}
} | java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
acmeair/acmeair | https://github.com/acmeair/acmeair/blob/f16122729873ef0449ea276dfb2d2a1d45bebb40/acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/WXSSessionManager.java | acmeair-services-wxs/src/main/java/com/acmeair/wxs/utils/WXSSessionManager.java | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.acmeair.wxs.utils;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.acmeair.service.DataService;
import com.acmeair.service.TransactionService;
import com.acmeair.wxs.WXSConstants;
import com.ibm.websphere.objectgrid.BackingMap;
import com.ibm.websphere.objectgrid.ClientClusterContext;
import com.ibm.websphere.objectgrid.ObjectGrid;
import com.ibm.websphere.objectgrid.ObjectGridException;
import com.ibm.websphere.objectgrid.ObjectGridManager;
import com.ibm.websphere.objectgrid.ObjectGridManagerFactory;
import com.ibm.websphere.objectgrid.ObjectGridRuntimeException;
import com.ibm.websphere.objectgrid.Session;
import com.ibm.websphere.objectgrid.config.BackingMapConfiguration;
import com.ibm.websphere.objectgrid.config.ObjectGridConfigFactory;
import com.ibm.websphere.objectgrid.config.ObjectGridConfiguration;
import com.ibm.websphere.objectgrid.config.Plugin;
import com.ibm.websphere.objectgrid.config.PluginType;
import com.ibm.websphere.objectgrid.security.config.ClientSecurityConfiguration;
import com.ibm.websphere.objectgrid.security.config.ClientSecurityConfigurationFactory;
import com.ibm.websphere.objectgrid.security.plugins.CredentialGenerator;
import com.ibm.websphere.objectgrid.security.plugins.builtins.UserPasswordCredentialGenerator;
import com.ibm.websphere.objectgrid.spring.SpringLocalTxManager;
@DataService(name=WXSConstants.KEY,description=WXSConstants.KEY_DESCRIPTION)
public class WXSSessionManager implements TransactionService, WXSConstants{
private static final String GRID_CONNECT_LOOKUP_KEY = "com.acmeair.service.wxs.gridConnect";
private static final String GRID_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.gridName";
private static final String GRID_DISABLE_NEAR_CACHE_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.disableNearCacheName";
private static final String GRID_PARTITION_FIELD_NAME_LOOKUP_KEY = "com.acmeair.service.wxs.partitionFieldName";
private static final Logger logger = Logger.getLogger(WXSSessionManager.class.getName());
private static final String SPLIT_COMMA = "\\s*,\\s*";
private static final String SPLIT_COLON = "\\s*:\\s*";
private String gridConnectString;
private String gridUsername = null;
private String gridPassword = null;
private String gridName = "Grid";
private boolean integrateWithWASTransactions = false;
private String disableNearCacheNameString;
private String[] disableNearCacheNames = null;
private String partitionFieldNameString;
private HashMap<String, String> partitionFieldNames = null; // For now to make it simple to only support one partition field
private SpringLocalTxManager txManager;
private String mapSuffix = "";
private AtomicReference<ObjectGrid> sharedGrid = new AtomicReference<ObjectGrid>();
private static AtomicReference<WXSSessionManager> connectionManager = new AtomicReference<WXSSessionManager>();
public static WXSSessionManager getSessionManager() {
if (connectionManager.get() == null) {
synchronized (connectionManager) {
if (connectionManager.get() == null) {
connectionManager.set(new WXSSessionManager());
}
}
}
return connectionManager.get();
}
private WXSSessionManager(){
ObjectGrid og = null;
try {
InitialContext ic = new InitialContext();
og = (ObjectGrid) ic.lookup(JNDI_NAME);
} catch (NamingException e) {
logger.warning("Unable to look up the ObjectGrid reference " + e.getMessage());
}
if(og != null) {
sharedGrid.set(og);
} else {
initialization();
}
}
private void initialization() {
String vcapJSONString = System.getenv("VCAP_SERVICES");
if (vcapJSONString != null) {
logger.info("Reading VCAP_SERVICES");
Object jsonObject = JSONValue.parse(vcapJSONString);
logger.info("jsonObject = " + ((JSONObject)jsonObject).toJSONString());
JSONObject json = (JSONObject)jsonObject;
String key;
for (Object k: json.keySet())
{
key = (String ) k;
if (key.startsWith("ElasticCaching")||key.startsWith("DataCache"))
{
JSONArray elasticCachingServiceArray = (JSONArray)json.get(key);
JSONObject elasticCachingService = (JSONObject)elasticCachingServiceArray.get(0);
JSONObject credentials = (JSONObject)elasticCachingService.get("credentials");
String username = (String)credentials.get("username");
setGridUsername(username);
String password = (String)credentials.get("password");
setGridPassword(password);
String gridName = (String)credentials.get("gridName");
String catalogEndPoint = (String)credentials.get("catalogEndPoint");
logger.info("username = " + username + "; password = " + password + "; gridName = " + gridName + "; catalogEndpoint = " + catalogEndPoint);
setGridConnectString(catalogEndPoint);
setGridName(gridName);
break;
}
}
setMapSuffix(".NONE.O");
} else {
logger.info("Creating the WXS Client connection. Looking up host and port information" );
gridName = lookup(GRID_NAME_LOOKUP_KEY);
if(gridName == null){
gridName = "AcmeGrid";
}
gridConnectString = lookup(GRID_CONNECT_LOOKUP_KEY);
if(gridConnectString == null){
gridConnectString = "127.0.0.1:2809";
logger.info("Using default grid connection setting of " + gridConnectString);
}
setDisableNearCacheNameString(lookup(GRID_DISABLE_NEAR_CACHE_NAME_LOOKUP_KEY));
setPartitionFieldNameString(lookup(GRID_PARTITION_FIELD_NAME_LOOKUP_KEY));
}
if(getDisableNearCacheNameString() == null){
setDisableNearCacheNameString("Flight,FlightSegment,AirportCodeMapping,CustomerSession,Booking,Customer");
logger.info("Using default disableNearCacheNameString value of " + disableNearCacheNameString);
}
if(getPartitionFieldNameString() == null){
setPartitionFieldNameString("Flight:pk.flightSegmentId,FlightSegment:originPort,Booking:pk.customerId");
logger.info("Using default partitionFieldNameString value of " + partitionFieldNameString);
}
if (!integrateWithWASTransactions && txManager!=null) // Using Spring TX if WAS TX is not enabled
{
logger.info("Session will be created from SpringLocalTxManager w/ tx support.");
}else
{
txManager=null;
logger.info("Session will be created from ObjectGrid directly w/o tx support.");
}
try {
prepareForTransaction();
} catch (ObjectGridException e) {
e.printStackTrace();
}
}
private String lookup (String key){
String value = null;
String lookup = key.replace('.', '/');
javax.naming.Context context = null;
javax.naming.Context envContext = null;
try {
context = new javax.naming.InitialContext();
envContext = (javax.naming.Context) context.lookup("java:comp/env");
if (envContext != null)
value = (String) envContext.lookup(lookup);
} catch (NamingException e) { }
if (value != null) {
logger.info("JNDI Found " + lookup + " : " + value);
}
else if (context != null) {
try {
value = (String) context.lookup(lookup);
if (value != null)
logger.info("JNDI Found " +lookup + " : " + value);
} catch (NamingException e) { }
}
if (value == null) {
value = System.getProperty(key);
if (value != null)
logger.info("Found " + key + " in jvm property : " + value);
else {
value = System.getenv(key);
if (value != null)
logger.info("Found "+key+" in environment property : " + value);
}
}
return value;
}
/**
* Connect to a remote ObjectGrid
* @param cep the catalog server end points in the form: <host>:<port>
* @param gridName the name of the ObjectGrid to connect to that is managed by the Catalog Service
* @return a client ObjectGrid connection.
*/
private ObjectGrid connectClient(String cep, String gridName, boolean integrateWithWASTransactions,String[] disableNearCacheNames) {
try {
ObjectGrid gridToReturn = sharedGrid.get();
if (gridToReturn == null) {
synchronized(sharedGrid) {
if (sharedGrid.get() == null) {
ObjectGridManager ogm = ObjectGridManagerFactory.getObjectGridManager();
ObjectGridConfiguration ogConfig = ObjectGridConfigFactory.createObjectGridConfiguration(gridName);
if (integrateWithWASTransactions) // Using WAS Transactions as Highest Priority
{
Plugin trans = ObjectGridConfigFactory.createPlugin(PluginType.TRANSACTION_CALLBACK,
"com.ibm.websphere.objectgrid.plugins.builtins.WebSphereTransactionCallback");
ogConfig.addPlugin(trans);
}
if (disableNearCacheNames!=null) {
String mapNames[] = disableNearCacheNames;
for (String mName : mapNames) {
BackingMapConfiguration bmc = ObjectGridConfigFactory.createBackingMapConfiguration(mName);
bmc.setNearCacheEnabled(false);
ogConfig.addBackingMapConfiguration(bmc);
}
}
ClientClusterContext ccc = null;
if (gridUsername != null) {
ClientSecurityConfiguration clientSC = ClientSecurityConfigurationFactory.getClientSecurityConfiguration();
clientSC.setSecurityEnabled(true);
CredentialGenerator credGen = new UserPasswordCredentialGenerator(gridUsername, gridPassword);
clientSC.setCredentialGenerator(credGen);
ccc = ogm.connect(cep, clientSC, null);
}
else {
ccc = ogm.connect(cep, null, null);
}
ObjectGrid grid = ObjectGridManagerFactory.getObjectGridManager().getObjectGrid(ccc, gridName, ogConfig);
sharedGrid.compareAndSet(null, grid);
gridToReturn = grid;
logger.info("Create instance of Grid: " + gridToReturn);
}else{
gridToReturn = sharedGrid.get();
}
}
}
return gridToReturn;
} catch (Exception e) {
throw new ObjectGridRuntimeException("Unable to connect to catalog server at endpoints:" + cep, e);
}
}
public String getMapSuffix(){
return mapSuffix;
}
public void setMapSuffix(String suffix){
this.mapSuffix = suffix;
}
public String getGridConnectString() {
return gridConnectString;
}
public void setGridConnectString(String gridConnectString) {
this.gridConnectString = gridConnectString;
}
public String getGridName() {
return gridName;
}
public void setGridName(String gridName) {
this.gridName = gridName;
}
public String getGridUsername() {
return gridUsername;
}
public void setGridUsername(String gridUsername) {
this.gridUsername = gridUsername;
}
public String getGridPassword() {
return gridPassword;
}
public void setGridPassword(String gridPassword) {
this.gridPassword = gridPassword;
}
public boolean isIntegrateWithWASTransactions() {
return integrateWithWASTransactions;
}
public void setIntegrateWithWASTransactions(boolean integrateWithWASTransactions) {
this.integrateWithWASTransactions = integrateWithWASTransactions;
}
public String getDisableNearCacheNameString() {
return disableNearCacheNameString;
}
public void setDisableNearCacheNameString(String disableNearCacheNameString) {
this.disableNearCacheNameString = disableNearCacheNameString;
if (disableNearCacheNameString ==null || disableNearCacheNameString.length()==0)
disableNearCacheNames =null;
else
disableNearCacheNames = disableNearCacheNameString.split(SPLIT_COMMA);
}
public String getPartitionFieldNameString() {
return partitionFieldNameString;
}
public void setPartitionFieldNameString(String partitionFieldNameString) {
this.partitionFieldNameString = partitionFieldNameString;
// In the form of <MapName>:<PartitionFieldName>,<MapName>:<PartitionFieldName>
if (partitionFieldNameString ==null || partitionFieldNameString.length()==0)
partitionFieldNames =null;
else
{
String[] maps = partitionFieldNameString.split(SPLIT_COMMA);
partitionFieldNames = new HashMap<String, String>();
String[] mapDef;
for (int i=0; i<maps.length; i++)
{
mapDef = maps[i].split(SPLIT_COLON);
partitionFieldNames.put(mapDef[0], mapDef[1]);
}
}
}
public String getPartitionFieldName(String mapName) {
if (partitionFieldNames == null)
return null;
return partitionFieldNames.get(mapName);
}
public SpringLocalTxManager getTxManager() {
return txManager;
}
public void setTxManager(SpringLocalTxManager txManager) {
logger.finer("txManager:"+txManager);
this.txManager = txManager;
}
// This method needs to be called by the client from its thread before triggering a service with @Transactional annotation
public void prepareForTransaction() throws ObjectGridException
{
ObjectGrid grid = this.getObjectGrid();
if (txManager!=null)
txManager.setObjectGridForThread(grid);
}
// Helper function
public ObjectGrid getObjectGrid() throws ObjectGridException {
ObjectGrid grid = connectClient(this.gridConnectString, this.gridName, this.integrateWithWASTransactions, this.disableNearCacheNames);
return grid;
}
public Session getObjectGridSession() throws ObjectGridException {
Session result;
ObjectGrid grid = getObjectGrid();
if (txManager!=null)
result= txManager.getSession();
else
result = grid.getSession();
// this.log.debug("Got session:"+ result);
return result;
}
public BackingMap getBackingMap(String mapName)throws ObjectGridException
{
return this.getObjectGrid().getMap(mapName);
}
}
| java | Apache-2.0 | f16122729873ef0449ea276dfb2d2a1d45bebb40 | 2026-01-05T02:38:07.986560Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-http/src/test/java/io/vertx/blueprint/kue/http/KueRestApiTest.java | kue-http/src/test/java/io/vertx/blueprint/kue/http/KueRestApiTest.java | package io.vertx.blueprint.kue.http;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.KueVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.*;
/**
* Vert.x Kue REST API test case
*
* @author Eric Zhao
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(VertxUnitRunner.class)
public class KueRestApiTest {
private static final int PORT = 8080;
private static final String HOST = "localhost";
private static final String TYPE = "test:inserts";
private static Kue kue;
@BeforeClass
public static void setUp(TestContext context) throws Exception {
Async async = context.async();
Vertx.clusteredVertx(new VertxOptions(), r -> {
if (r.succeeded()) {
Vertx vertx = r.result();
kue = Kue.createQueue(vertx, new JsonObject());
vertx.deployVerticle(new KueVerticle(), r2 -> {
if (r2.succeeded()) {
kue.jobRangeByType(TYPE, "inactive", 0, 100, "asc").setHandler(r1 -> {
if (r1.succeeded()) {
r1.result().forEach(Job::remove);
vertx.deployVerticle(new KueHttpVerticle(), r3 -> {
if (r3.succeeded())
async.complete();
else
context.fail(r3.cause());
});
} else {
context.fail(r1.cause());
}
});
} else {
context.fail(r2.cause());
}
});
} else {
context.fail(r.cause());
}
});
}
@Test
public void testApiStats(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
client.getNow(PORT, HOST, "/stats", response -> {
response.bodyHandler(body -> {
JsonObject stats = new JsonObject(body.toString());
context.assertEquals(stats.getInteger("inactiveCount") > 0, true);
client.close();
async.complete();
});
});
}
public void testApiTypeStateStats(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
}
public void testJobTypes(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
}
public void testJobRange(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
}
public void testJobTypeRange(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
}
public void testJobStateRange(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
}
@Test
public void testApiGetJob(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
kue.createJob(TYPE, new JsonObject().put("data", TYPE + ":data"))
.save()
.setHandler(jr -> {
if (jr.succeeded()) {
long id = jr.result().getId();
client.getNow(PORT, HOST, "/job/" + id, response -> response.bodyHandler(body -> {
context.assertEquals(new Job(new JsonObject(body.toString())).getId(), id);
client.close();
async.complete();
}));
} else {
context.fail(jr.cause());
}
});
}
@Test
public void testDeleteJob(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
client.delete(PORT, HOST, "/job/66", rsp -> {
context.assertEquals(204, rsp.statusCode());
client.close();
async.complete();
}).end();
}
@Test
public void testApiCreateJob(TestContext context) throws Exception {
Vertx vertx = Vertx.vertx();
HttpClient client = vertx.createHttpClient();
Async async = context.async();
Job job = kue.createJob(TYPE, new JsonObject().put("data", TYPE + ":data"));
client.put(PORT, HOST, "/job", response -> {
context.assertEquals(201, response.statusCode());
response.bodyHandler(body -> {
context.assertEquals(new JsonObject(body.toString()).getString("message"), "job created");
client.close();
async.complete();
});
}).putHeader("content-type", "application/json")
.end(job.toString());
}
} | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-http/src/main/java/io/vertx/blueprint/kue/http/KueHttpVerticle.java | kue-http/src/main/java/io/vertx/blueprint/kue/http/KueHttpVerticle.java | package io.vertx.blueprint.kue.http;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.templ.JadeTemplateEngine;
/**
* The verticle serving Kue UI and REST API.
*
* @author Eric Zhao
*/
public class KueHttpVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(KueHttpVerticle.class);
private static final String HOST = "0.0.0.0";
private static final int PORT = 8080; // Default port
// Kue REST API
private static final String KUE_API_JOB_SEARCH = "/job/search/:q";
private static final String KUE_API_STATS = "/stats";
private static final String KUE_API_TYPE_STATE_STATS = "/jobs/:type/:state/stats";
private static final String KUE_API_GET_JOB = "/job/:id";
private static final String KUE_API_GET_JOB_TYPES = "/job/types";
private static final String KUE_API_JOB_RANGE = "/jobs/:from/to/:to";
private static final String KUE_API_JOB_TYPE_RANGE = "/jobs/:type/:state/:from/to/:to/:order";
private static final String KUE_API_JOB_STATE_RANGE = "/jobs/:state/:from/to/:to/:order";
private static final String KUE_API_JOB_RANGE_ORDER = "/jobs/:from/to/:to/:order";
private static final String KUE_API_CREATE_JOB = "/job";
private static final String KUE_API_UPDATE_JOB_STATE = "/job/:id/state/:state";
private static final String KUE_API_DELETE_JOB = "/job/:id";
private static final String KUE_API_GET_JOB_LOG = "/job/:id/log";
private static final String KUE_API_RESTART_JOB = "/inactive/:id";
// Kue UI
private static final String KUE_UI_ROOT = "/";
private static final String KUE_UI_ACTIVE = "/active";
private static final String KUE_UI_INACTIVE = "/inactive";
private static final String KUE_UI_FAILED = "/failed";
private static final String KUE_UI_COMPLETE = "/complete";
private static final String KUE_UI_DELAYED = "/delayed";
private Kue kue;
private JadeTemplateEngine engine;
@Override
public void start(Future<Void> future) throws Exception {
// init kue
kue = Kue.createQueue(vertx, config());
engine = JadeTemplateEngine.create();
// create route
final Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
// REST API routes
router.get(KUE_API_JOB_SEARCH).handler(this::apiSearchJob);
router.get(KUE_API_STATS).handler(this::apiStats);
router.get(KUE_API_TYPE_STATE_STATS).handler(this::apiTypeStateStats);
router.get(KUE_API_GET_JOB_TYPES).handler(this::apiJobTypes);
router.get(KUE_API_JOB_RANGE).handler(this::apiJobRange); // \/jobs\/([0-9]*)\.\.([0-9]*)(\/[^\/]+)?
router.get(KUE_API_JOB_TYPE_RANGE).handler(this::apiJobTypeRange);
router.get(KUE_API_JOB_STATE_RANGE).handler(this::apiJobStateRange);
router.get(KUE_API_JOB_RANGE_ORDER).handler(this::apiJobRange);
router.put(KUE_API_CREATE_JOB).handler(this::apiCreateJob);
router.put(KUE_API_UPDATE_JOB_STATE).handler(this::apiUpdateJobState);
router.get(KUE_API_GET_JOB).handler(this::apiGetJob);
router.get(KUE_API_GET_JOB_LOG).handler(this::apiFetchLog);
router.delete(KUE_API_DELETE_JOB).handler(this::apiDeleteJob);
router.post(KUE_API_RESTART_JOB).handler(this::apiRestartJob);
// UI routes
router.route(KUE_UI_ROOT).handler(this::handleUIRoot);
router.route(KUE_UI_ACTIVE).handler(this::handleUIActive);
router.route(KUE_UI_INACTIVE).handler(this::handleUIInactive);
router.route(KUE_UI_COMPLETE).handler(this::handleUIComplete);
router.route(KUE_UI_FAILED).handler(this::handleUIFailed);
router.route(KUE_UI_DELAYED).handler(this::handleUIADelayed);
// static resources route
router.route().handler(StaticHandler.create());
// create server
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", PORT),
config().getString("http.address", HOST), result -> {
if (result.succeeded()) {
System.out.println("Kue http server is running on " + PORT + " port...");
future.complete();
} else {
future.fail(result.cause());
}
});
}
/**
* Render UI by job state
*
* @param state job state
*/
private void render(RoutingContext context, String state) { // TODO: bug in `types` param
final String uiPath = "webroot/views/job/list.jade";
String title = config().getString("kue.ui.title", "Vert.x Kue");
kue.getAllTypes()
.setHandler(resultHandler(context, r -> {
context.put("state", state)
.put("types", r)
.put("title", title);
engine.render(context, uiPath, res -> {
if (res.succeeded()) {
context.response()
.putHeader("content-type", "text/html")
.end(res.result());
} else {
context.fail(res.cause());
}
});
}));
}
private void handleUIRoot(RoutingContext context) {
handleUIActive(context); // by default active
}
private void handleUIInactive(RoutingContext context) {
render(context, "inactive");
}
private void handleUIFailed(RoutingContext context) {
render(context, "failed");
}
private void handleUIComplete(RoutingContext context) {
render(context, "complete");
}
private void handleUIActive(RoutingContext context) {
render(context, "active");
}
private void handleUIADelayed(RoutingContext context) {
render(context, "delayed");
}
private void apiSearchJob(RoutingContext context) {
notImplemented(context); // TODO: Not Implemented
}
private void apiStats(RoutingContext context) {
JsonObject stats = new JsonObject();
kue.getWorkTime().compose(r -> {
stats.put("workTime", r);
return kue.getIdsByState(JobState.INACTIVE);
}).compose(r -> {
stats.put("inactiveCount", r.size());
return kue.getIdsByState(JobState.COMPLETE);
}).compose(r -> {
stats.put("completeCount", r.size());
return kue.getIdsByState(JobState.ACTIVE);
}).compose(r -> {
stats.put("activeCount", r.size());
return kue.getIdsByState(JobState.FAILED);
}).compose(r -> {
stats.put("failedCount", r.size());
return kue.getIdsByState(JobState.DELAYED);
}).map(r -> {
stats.put("delayedCount", r.size());
return stats;
}).setHandler(resultHandler(context, r -> {
context.response()
.putHeader("content-type", "application/json")
.end(r.encodePrettily());
}));
}
private void apiTypeStateStats(RoutingContext context) {
try {
String type = context.request().getParam("type");
JobState state = JobState.valueOf(context.request().getParam("state").toUpperCase());
kue.cardByType(type, state).setHandler(resultHandler(context, r -> {
context.response()
.putHeader("content-type", "application/json")
.end(new JsonObject().put("count", r).encodePrettily());
}));
} catch (Exception e) {
badRequest(context, e);
}
}
private void apiJobTypes(RoutingContext context) {
kue.getAllTypes().setHandler(resultHandler(context, r -> {
context.response()
.putHeader("content-type", "application/json")
.end(new JsonArray(r).encodePrettily());
}));
}
private void apiCreateJob(RoutingContext context) {
try {
Job job = new Job(new JsonObject(context.getBodyAsString())); // TODO: support json array create
job.save().setHandler(resultHandler(context, r -> {
String result = new JsonObject().put("message", "job created")
.put("id", r.getId())
.encodePrettily();
context.response().setStatusCode(201)
.putHeader("content-type", "application/json")
.end(result);
}));
} catch (DecodeException e) {
badRequest(context, e);
}
}
private void apiUpdateJobState(RoutingContext context) {
try {
long id = Long.parseLong(context.request().getParam("id"));
JobState state = JobState.valueOf(context.request().getParam("state").toUpperCase());
kue.getJob(id)
.compose(j1 -> {
if (j1.isPresent()) {
return j1.get().state(state)
.compose(Job::save);
} else {
return Future.succeededFuture();
}
}).setHandler(resultHandler(context, job -> {
if (job != null) {
context.response().putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "job_state_updated").encodePrettily());
} else {
context.response().setStatusCode(404)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "job_not_found").encodePrettily());
}
}));
} catch (Exception e) {
badRequest(context, e);
}
}
private void apiGetJob(RoutingContext context) {
try {
long id = Long.parseLong(context.request().getParam("id"));
kue.getJob(id).setHandler(resultHandler(context, r -> {
if (r.isPresent()) {
context.response()
.putHeader("content-type", "application/json")
.end(r.get().toString());
} else {
notFound(context);
}
}));
} catch (Exception e) {
badRequest(context, e);
}
}
private void apiJobRange(RoutingContext context) {
try {
String order = context.request().getParam("order");
if (order == null || !isOrderValid(order))
order = "asc";
Long from = Long.parseLong(context.request().getParam("from"));
Long to = Long.parseLong(context.request().getParam("to"));
kue.jobRange(from, to, order)
.setHandler(resultHandler(context, r -> {
String result = new JsonArray(r).encodePrettily();
context.response()
.putHeader("content-type", "application/json")
.end(result);
}));
} catch (Exception e) {
e.printStackTrace();
badRequest(context, e);
}
}
private void apiJobTypeRange(RoutingContext context) {
try {
String order = context.request().getParam("order");
if (order == null || !isOrderValid(order)) {
order = "asc";
}
Long from = Long.parseLong(context.request().getParam("from"));
Long to = Long.parseLong(context.request().getParam("to"));
String state = context.request().getParam("state");
String type = context.request().getParam("type");
kue.jobRangeByType(type, state, from, to, order)
.setHandler(resultHandler(context, r -> {
String result = new JsonArray(r).encodePrettily();
context.response()
.putHeader("content-type", "application/json")
.end(result);
}));
} catch (Exception e) {
e.printStackTrace();
badRequest(context, e);
}
}
private void apiJobStateRange(RoutingContext context) {
try {
String order = context.request().getParam("order");
if (order == null || !isOrderValid(order))
order = "asc";
Long from = Long.parseLong(context.request().getParam("from"));
Long to = Long.parseLong(context.request().getParam("to"));
String state = context.request().getParam("state");
kue.jobRangeByState(state, from, to, order)
.setHandler(resultHandler(context, r -> {
String result = new JsonArray(r).encodePrettily();
context.response()
.putHeader("content-type", "application/json")
.end(result);
}));
} catch (Exception e) {
e.printStackTrace();
badRequest(context, e);
}
}
private boolean isOrderValid(String order) {
return order.equals("asc") && order.equals("desc");
}
private void apiDeleteJob(RoutingContext context) {
try {
long id = Long.parseLong(context.request().getParam("id"));
kue.removeJob(id).setHandler(resultHandler(context, r -> {
context.response().setStatusCode(204)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "job " + id + " removed").encodePrettily());
}));
} catch (Exception e) {
badRequest(context, e);
}
}
private void apiRestartJob(RoutingContext context) {
try {
long id = Long.parseLong(context.request().getParam("id"));
kue.getJob(id).setHandler(resultHandler(context, r -> {
if (r.isPresent()) {
r.get().inactive().setHandler(resultHandler(context, r1 -> {
context.response()
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "job " + id + " restart").encodePrettily());
}));
} else {
notFound(context);
}
}));
} catch (Exception e) {
badRequest(context, e);
}
}
private void apiFetchLog(RoutingContext context) {
try {
long id = Long.parseLong(context.request().getParam("id"));
kue.getJobLog(id).setHandler(resultHandler(context, r -> {
context.response().putHeader("content-type", "application/json")
.end(r.encodePrettily());
}));
} catch (Exception e) {
badRequest(context, e);
}
}
// helper methods
/**
* Wrap the result handler with failure handler (503 Service Unavailable)
*/
private <T> Handler<AsyncResult<T>> resultHandler(RoutingContext context, Handler<T> handler) {
return res -> {
if (res.succeeded()) {
handler.handle(res.result());
} else {
serviceUnavailable(context, res.cause());
}
};
}
private void sendError(int statusCode, RoutingContext context) {
context.response().setStatusCode(statusCode).end();
}
private void badRequest(RoutingContext context, Throwable ex) {
context.response().setStatusCode(400)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
private void notFound(RoutingContext context) {
context.response().setStatusCode(404).end();
}
private void notImplemented(RoutingContext context) {
context.response().setStatusCode(501)
.end(new JsonObject().put("message", "not_implemented").encodePrettily());
}
private void serviceUnavailable(RoutingContext context) {
context.response().setStatusCode(503).end();
}
private void serviceUnavailable(RoutingContext context, Throwable ex) {
context.response().setStatusCode(503)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/CallbackKue.java | kue-core/src/main/java/io/vertx/blueprint/kue/CallbackKue.java | package io.vertx.blueprint.kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
/**
* A callback-based {@link io.vertx.blueprint.kue.Kue} interface for Vert.x Codegen to support polyglot languages.
*
* @author Eric Zhao
*/
@VertxGen
public interface CallbackKue extends JobService {
static CallbackKue createKue(Vertx vertx, JsonObject config) {
return new CallbackKueImpl(vertx, config);
}
Job createJob(String type, JsonObject data);
@Fluent
<R> CallbackKue on(String eventType, Handler<Message<R>> handler);
@Fluent
CallbackKue saveJob(Job job, Handler<AsyncResult<Job>> handler);
@Fluent
CallbackKue jobProgress(Job job, int complete, int total, Handler<AsyncResult<Job>> handler);
@Fluent
CallbackKue jobDone(Job job);
@Fluent
CallbackKue jobDoneFail(Job job, Throwable ex);
@Fluent
CallbackKue process(String type, int n, Handler<Job> handler);
@Fluent
CallbackKue processBlocking(String type, int n, Handler<Job> handler);
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/package-info.java | kue-core/src/main/java/io/vertx/blueprint/kue/package-info.java | @ModuleGen(groupPackage = "io.vertx.blueprint.kue", name = "vertx-kue-root-module")
package io.vertx.blueprint.kue;
import io.vertx.codegen.annotations.ModuleGen; | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/CallbackKueImpl.java | kue-core/src/main/java/io/vertx/blueprint/kue/CallbackKueImpl.java | package io.vertx.blueprint.kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.List;
/**
* Implementation of {@link io.vertx.blueprint.kue.CallbackKue}.
*
* @author Eric Zhao
*/
public class CallbackKueImpl implements CallbackKue {
private final Kue kue;
private final JobService jobService;
public CallbackKueImpl(Vertx vertx, JsonObject config) {
this.kue = new Kue(vertx, config);
this.jobService = kue.getJobService();
}
@Override
public Job createJob(String type, JsonObject data) {
return kue.createJob(type, data);
}
@Override
public CallbackKue saveJob(Job job, Handler<AsyncResult<Job>> handler) {
job.save().setHandler(handler);
return this;
}
@Override
public CallbackKue jobProgress(Job job, int complete, int total, Handler<AsyncResult<Job>> handler) {
job.progress(complete, total).setHandler(handler);
return this;
}
@Override
public CallbackKue jobDoneFail(Job job, Throwable ex) {
job.done(ex);
return this;
}
@Override
public CallbackKue jobDone(Job job) {
job.done();
return this;
}
@Override
public <R> CallbackKue on(String eventType, Handler<Message<R>> handler) {
kue.on(eventType, handler);
return this;
}
@Override
public CallbackKue process(String type, int n, Handler<Job> handler) {
kue.process(type, n, handler);
return this;
}
@Override
public CallbackKue processBlocking(String type, int n, Handler<Job> handler) {
kue.processBlocking(type, n, handler);
return this;
}
@Override
public CallbackKue getJob(long id, Handler<AsyncResult<Job>> handler) {
jobService.getJob(id, handler);
return this;
}
@Override
public CallbackKue removeJob(long id, Handler<AsyncResult<Void>> handler) {
jobService.removeJob(id, handler);
return this;
}
@Override
public CallbackKue existsJob(long id, Handler<AsyncResult<Boolean>> handler) {
jobService.existsJob(id, handler);
return this;
}
@Override
public CallbackKue getJobLog(long id, Handler<AsyncResult<JsonArray>> handler) {
jobService.getJobLog(id, handler);
return this;
}
@Override
public CallbackKue jobRangeByState(String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
jobService.jobRangeByState(state, from, to, order, handler);
return this;
}
@Override
public JobService jobRangeByType(String type, String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
jobService.jobRangeByType(type, state, from, to, order, handler);
return this;
}
@Override
public JobService jobRange(long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
jobService.jobRange(from, to, order, handler);
return this;
}
@Override
public CallbackKue cardByType(String type, JobState state, Handler<AsyncResult<Long>> handler) {
jobService.cardByType(type, state, handler);
return this;
}
@Override
public CallbackKue card(JobState state, Handler<AsyncResult<Long>> handler) {
jobService.card(state, handler);
return this;
}
@Override
public CallbackKue completeCount(String type, Handler<AsyncResult<Long>> handler) {
jobService.completeCount(type, handler);
return this;
}
@Override
public CallbackKue failedCount(String type, Handler<AsyncResult<Long>> handler) {
jobService.failedCount(type, handler);
return this;
}
@Override
public CallbackKue inactiveCount(String type, Handler<AsyncResult<Long>> handler) {
jobService.inactiveCount(type, handler);
return this;
}
@Override
public CallbackKue activeCount(String type, Handler<AsyncResult<Long>> handler) {
jobService.activeCount(type, handler);
return this;
}
@Override
public CallbackKue delayedCount(String type, Handler<AsyncResult<Long>> handler) {
jobService.delayedCount(type, handler);
return this;
}
@Override
public CallbackKue getAllTypes(Handler<AsyncResult<List<String>>> handler) {
jobService.getAllTypes(handler);
return this;
}
@Override
public CallbackKue getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
jobService.getIdsByState(state, handler);
return this;
}
@Override
public CallbackKue getWorkTime(Handler<AsyncResult<Long>> handler) {
jobService.getWorkTime(handler);
return this;
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/Kue.java | kue-core/src/main/java/io/vertx/blueprint/kue/Kue.java | package io.vertx.blueprint.kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.blueprint.kue.queue.KueWorker;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.blueprint.kue.util.RedisHelper;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;
import io.vertx.redis.op.RangeLimitOptions;
import java.util.List;
import java.util.Optional;
import static io.vertx.blueprint.kue.queue.KueVerticle.EB_JOB_SERVICE_ADDRESS;
/**
* The Kue class refers to a job queue.
*
* @author Eric Zhao
*/
public class Kue {
private final JsonObject config;
private final Vertx vertx;
private final JobService jobService;
private final RedisClient client;
public Kue(Vertx vertx, JsonObject config) {
this.vertx = vertx;
this.config = config;
this.jobService = JobService.createProxy(vertx, EB_JOB_SERVICE_ADDRESS);
this.client = RedisHelper.client(vertx, config);
Job.setVertx(vertx, RedisHelper.client(vertx, config)); // init static vertx instance inner job
}
/**
* Generate handler address with certain job on event bus.
* <p>Format: vertx.kue.handler.job.{handlerType}.{addressId}.{jobType}</p>
*
* @return corresponding address
*/
public static String getCertainJobAddress(String handlerType, Job job) {
return "vertx.kue.handler.job." + handlerType + "." + job.getAddress_id() + "." + job.getType();
}
/**
* Generate worker address on event bus.
* <p>Format: vertx.kue.handler.workers.{eventType}</p>
*
* @return corresponding address
*/
public static String workerAddress(String eventType) {
return "vertx.kue.handler.workers." + eventType;
}
/**
* Generate worker address on event bus.
* <p>Format: vertx.kue.handler.workers.{eventType}.{addressId}</p>
*
* @return corresponding address
*/
public static String workerAddress(String eventType, Job job) {
return "vertx.kue.handler.workers." + eventType + "." + job.getAddress_id();
}
/**
* Create a Kue instance.
*
* @param vertx vertx instance
* @param config config json object
* @return kue instance
*/
public static Kue createQueue(Vertx vertx, JsonObject config) {
return new Kue(vertx, config);
}
/**
* Get the JobService.
* <em>Notice: only available in package scope</em>
*/
JobService getJobService() {
return this.jobService;
}
/**
* Create a job instance.
*
* @param type job type
* @param data job extra data
* @return a new job instance
*/
public Job createJob(String type, JsonObject data) {
return new Job(type, data);
}
private void processInternal(String type, Handler<Job> handler, boolean isWorker) {
KueWorker worker = new KueWorker(type, handler, this);
vertx.deployVerticle(worker, new DeploymentOptions().setWorker(isWorker), r0 -> {
if (r0.succeeded()) {
this.on("job_complete", msg -> {
long dur = new Job(((JsonObject) msg.body()).getJsonObject("job")).getDuration();
client.incrby(RedisHelper.getKey("stats:work-time"), dur, r1 -> {
if (r1.failed())
r1.cause().printStackTrace();
});
});
}
});
}
/**
* Queue-level events listener.
*
* @param eventType event type
* @param handler handler
*/
public <R> Kue on(String eventType, Handler<Message<R>> handler) {
vertx.eventBus().consumer(Kue.workerAddress(eventType), handler);
return this;
}
/**
* Process a job in asynchronous way.
*
* @param type job type
* @param n job process times
* @param handler job process handler
*/
public Kue process(String type, int n, Handler<Job> handler) {
if (n <= 0) {
throw new IllegalStateException("The process times must be positive");
}
while (n-- > 0) {
processInternal(type, handler, false);
}
setupTimers();
return this;
}
/**
* Process a job in asynchronous way (once).
*
* @param type job type
* @param handler job process handler
*/
public Kue process(String type, Handler<Job> handler) {
processInternal(type, handler, false);
setupTimers();
return this;
}
/**
* Process a job that may be blocking.
*
* @param type job type
* @param n job process times
* @param handler job process handler
*/
public Kue processBlocking(String type, int n, Handler<Job> handler) {
if (n <= 0) {
throw new IllegalStateException("The process times must be positive");
}
while (n-- > 0) {
processInternal(type, handler, true);
}
setupTimers();
return this;
}
// job logic
/**
* Get job from backend by id.
*
* @param id job id
* @return async result
*/
public Future<Optional<Job>> getJob(long id) {
Future<Optional<Job>> future = Future.future();
jobService.getJob(id, r -> {
if (r.succeeded()) {
future.complete(Optional.ofNullable(r.result()));
} else {
future.fail(r.cause());
}
});
return future;
}
/**
* Remove a job by id.
*
* @param id job id
* @return async result
*/
public Future<Void> removeJob(long id) {
return this.getJob(id).compose(r -> {
if (r.isPresent()) {
return r.get().remove();
} else {
return Future.succeededFuture();
}
});
}
/**
* Judge whether a job with certain id exists.
*
* @param id job id
* @return async result
*/
public Future<Boolean> existsJob(long id) {
Future<Boolean> future = Future.future();
jobService.existsJob(id, future.completer());
return future;
}
/**
* Get job log by id.
*
* @param id job id
* @return async result
*/
public Future<JsonArray> getJobLog(long id) {
Future<JsonArray> future = Future.future();
jobService.getJobLog(id, future.completer());
return future;
}
/**
* Get a list of job in certain state in range (from, to) with order.
*
* @return async result
* @see JobService#jobRangeByState(String, long, long, String, Handler)
*/
public Future<List<Job>> jobRangeByState(String state, long from, long to, String order) {
Future<List<Job>> future = Future.future();
jobService.jobRangeByState(state, from, to, order, future.completer());
return future;
}
/**
* Get a list of job in certain state and type in range (from, to) with order.
*
* @return async result
* @see JobService#jobRangeByType(String, String, long, long, String, Handler)
*/
public Future<List<Job>> jobRangeByType(String type, String state, long from, long to, String order) {
Future<List<Job>> future = Future.future();
jobService.jobRangeByType(type, state, from, to, order, future.completer());
return future;
}
/**
* Get a list of job in range (from, to) with order.
*
* @return async result
* @see JobService#jobRange(long, long, String, Handler)
*/
public Future<List<Job>> jobRange(long from, long to, String order) {
Future<List<Job>> future = Future.future();
jobService.jobRange(from, to, order, future.completer());
return future;
}
// runtime cardinality metrics
/**
* Get cardinality by job type and state.
*
* @param type job type
* @param state job state
* @return corresponding cardinality (Future)
*/
public Future<Long> cardByType(String type, JobState state) {
Future<Long> future = Future.future();
jobService.cardByType(type, state, future.completer());
return future;
}
/**
* Get cardinality by job state.
*
* @param state job state
* @return corresponding cardinality (Future)
*/
public Future<Long> card(JobState state) {
Future<Long> future = Future.future();
jobService.card(state, future.completer());
return future;
}
/**
* Get cardinality of completed jobs.
*
* @param type job type; if null, then return global metrics.
*/
public Future<Long> completeCount(String type) {
Future<Long> future = Future.future();
jobService.completeCount(type, future.completer());
return future;
}
/**
* Get cardinality of failed jobs.
*
* @param type job type; if null, then return global metrics.
*/
public Future<Long> failedCount(String type) {
Future<Long> future = Future.future();
jobService.failedCount(type, future.completer());
return future;
}
/**
* Get cardinality of inactive jobs.
*
* @param type job type; if null, then return global metrics.
*/
public Future<Long> inactiveCount(String type) {
Future<Long> future = Future.future();
jobService.inactiveCount(type, future.completer());
return future;
}
/**
* Get cardinality of active jobs.
*
* @param type job type; if null, then return global metrics.
*/
public Future<Long> activeCount(String type) {
Future<Long> future = Future.future();
jobService.activeCount(type, future.completer());
return future;
}
/**
* Get cardinality of delayed jobs.
*
* @param type job type; if null, then return global metrics.
*/
public Future<Long> delayedCount(String type) {
Future<Long> future = Future.future();
jobService.delayedCount(type, future.completer());
return future;
}
/**
* Get the job types present.
*
* @return async result list
*/
public Future<List<String>> getAllTypes() {
Future<List<String>> future = Future.future();
jobService.getAllTypes(future.completer());
return future;
}
/**
* Return job ids with the given `state`.
*
* @param state job state
* @return async result list
*/
public Future<List<Long>> getIdsByState(JobState state) {
Future<List<Long>> future = Future.future();
jobService.getIdsByState(state, future.completer());
return future;
}
/**
* Get queue work time in milliseconds.
*
* @return async result
*/
public Future<Long> getWorkTime() {
Future<Long> future = Future.future();
jobService.getWorkTime(future.completer());
return future;
}
/**
* Set up timers for checking job promotion and active job ttl.
*/
private void setupTimers() {
this.checkJobPromotion();
this.checkActiveJobTtl();
}
/**
* Check job promotion.
* Promote delayed jobs, checking every `ms`.
*/
private void checkJobPromotion() { // TODO: TO REVIEW
int timeout = config.getInteger("job.promotion.interval", 1000);
int limit = config.getInteger("job.promotion.limit", 1000);
// need a mechanism to stop the circuit timer
vertx.setPeriodic(timeout, l -> {
client.zrangebyscore(RedisHelper.getKey("jobs:DELAYED"), String.valueOf(0), String.valueOf(System.currentTimeMillis()),
new RangeLimitOptions(new JsonObject().put("offset", 0).put("count", limit)), r -> {
if (r.succeeded()) {
r.result().forEach(r1 -> {
long id = Long.parseLong(RedisHelper.stripFIFO((String) r1));
this.getJob(id).compose(jr -> jr.get().inactive())
.setHandler(jr -> {
if (jr.succeeded()) {
jr.result().emit("promotion", jr.result().getId());
} else {
jr.cause().printStackTrace();
}
});
});
} else {
r.cause().printStackTrace();
}
});
});
}
/**
* Check active job ttl.
*/
private void checkActiveJobTtl() { // TODO
int timeout = config.getInteger("job.ttl.interval", 1000);
int limit = config.getInteger("job.ttl.limit", 1000);
// need a mechanism to stop the circuit timer
vertx.setPeriodic(timeout, l -> {
client.zrangebyscore(RedisHelper.getKey("jobs:ACTIVE"), String.valueOf(100000), String.valueOf(System.currentTimeMillis()),
new RangeLimitOptions(new JsonObject().put("offset", 0).put("count", limit)), r -> {
});
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/util/RedisHelper.java | kue-core/src/main/java/io/vertx/blueprint/kue/util/RedisHelper.java | package io.vertx.blueprint.kue.util;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
/**
* Helper class for operating Redis.
*
* @author Eric Zhao
*/
public final class RedisHelper {
private static final String VERTX_KUE_REDIS_PREFIX = "vertx_kue";
private RedisHelper() {
}
/**
* Factory method for creating a Redis client in Vert.x context.
*
* @param vertx Vertx instance
* @param config configuration
* @return the new Redis client instance
*/
public static RedisClient client(Vertx vertx, JsonObject config) {
return RedisClient.create(vertx, options(config));
}
/**
* Factory method for creating a default local Redis client configuration.
*
* @param config configuration from Vert.x context
* @return the new configuration instance
*/
public static RedisOptions options(JsonObject config) {
return new RedisOptions()
.setHost(config.getString("redis.host", "127.0.0.1"))
.setPort(config.getInteger("redis.port", 6379));
}
/**
* Wrap the key with prefix of Vert.x Kue namespace.
*
* @param key the key to wrap
* @return the wrapped key
*/
public static String getKey(String key) {
return VERTX_KUE_REDIS_PREFIX + ":" + key;
}
/**
* Generate the key of a certain task state with prefix of Vert.x Kue namespace.
*
* @param state task state
* @return the generated key
*/
public static String getStateKey(JobState state) {
return VERTX_KUE_REDIS_PREFIX + ":jobs:" + state.name();
}
/**
* Create an id for the zset to preserve FIFO order.
*
* @param id id
*/
public static String createFIFO(long id) {
String idLen = "" + ("" + id).length();
int len = 2 - idLen.length();
while (len-- > 0)
idLen = "0" + idLen;
return idLen + "|" + id;
}
/**
* Parse out original ID from zid.
*
* @param zid zid
*/
public static String stripFIFO(String zid) {
return zid.substring(zid.indexOf('|') + 1);
}
/**
* Parse out original ID from zid.
*
* @param zid zid
*/
public static long numStripFIFO(String zid) {
return Long.parseLong(zid.substring(zid.indexOf('|') + 1));
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/service/JobService.java | kue-core/src/main/java/io/vertx/blueprint/kue/service/JobService.java | package io.vertx.blueprint.kue.service;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.blueprint.kue.service.impl.JobServiceImpl;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.serviceproxy.ProxyHelper;
import java.util.List;
/**
* Service interface for task operations.
*
* @author Eric Zhao
*/
@ProxyGen
@VertxGen
public interface JobService {
/**
* Factory method for creating a {@link JobService} instance.
*
* @param vertx Vertx instance
* @param config configuration
* @return the new {@link JobService} instance
*/
static JobService create(Vertx vertx, JsonObject config) {
return new JobServiceImpl(vertx, config);
}
/**
* Factory method for creating a {@link JobService} service proxy.
* This is useful for doing RPCs.
*
* @param vertx Vertx instance
* @param address event bus address of RPC
* @return the new {@link JobService} service proxy
*/
static JobService createProxy(Vertx vertx, String address) {
return ProxyHelper.createProxy(JobService.class, vertx, address);
}
/**
* Get the certain from backend by id.
*
* @param id job id
* @param handler async result handler
*/
@Fluent
JobService getJob(long id, Handler<AsyncResult<Job>> handler);
/**
* Remove a job by id.
*
* @param id job id
* @param handler async result handler
*/
@Fluent
JobService removeJob(long id, Handler<AsyncResult<Void>> handler);
/**
* Judge whether a job with certain id exists.
*
* @param id job id
* @param handler async result handler
*/
@Fluent
JobService existsJob(long id, Handler<AsyncResult<Boolean>> handler);
/**
* Get job log by id.
*
* @param id job id
* @param handler async result handler
*/
@Fluent
JobService getJobLog(long id, Handler<AsyncResult<JsonArray>> handler);
/**
* Get a list of job in certain state in range (from, to) with order.
*
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
*/
@Fluent
JobService jobRangeByState(String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler);
/**
* Get a list of job in certain state and type in range (from, to) with order.
*
* @param type expected job type
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
*/
@Fluent
JobService jobRangeByType(String type, String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler);
/**
* Get a list of job in range (from, to) with order.
*
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
*/
@Fluent
JobService jobRange(long from, long to, String order, Handler<AsyncResult<List<Job>>> handler);
// Runtime cardinality metrics
/**
* Get cardinality by job type and state.
*
* @param type job type
* @param state job state
* @param handler async result handler
*/
@Fluent
JobService cardByType(String type, JobState state, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality by job state.
*
* @param state job state
* @param handler async result handler
*/
@Fluent
JobService card(JobState state, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality of completed jobs.
*
* @param type job type; if null, then return global metrics
* @param handler async result handler
*/
@Fluent
JobService completeCount(String type, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality of failed jobs.
*
* @param type job type; if null, then return global metrics
*/
@Fluent
JobService failedCount(String type, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality of inactive jobs.
*
* @param type job type; if null, then return global metrics
*/
@Fluent
JobService inactiveCount(String type, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality of active jobs.
*
* @param type job type; if null, then return global metrics
*/
@Fluent
JobService activeCount(String type, Handler<AsyncResult<Long>> handler);
/**
* Get cardinality of delayed jobs.
*
* @param type job type; if null, then return global metrics
*/
@Fluent
JobService delayedCount(String type, Handler<AsyncResult<Long>> handler);
/**
* Get the job types present.
*
* @param handler async result handler
*/
@Fluent
JobService getAllTypes(Handler<AsyncResult<List<String>>> handler);
/**
* Return job ids with the given {@link JobState}.
*
* @param state job state
* @param handler async result handler
*/
@Fluent
JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler);
/**
* Get queue work time in milliseconds.
*
* @param handler async result handler
*/
@Fluent
JobService getWorkTime(Handler<AsyncResult<Long>> handler);
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/service/package-info.java | kue-core/src/main/java/io/vertx/blueprint/kue/service/package-info.java | @ModuleGen(groupPackage = "io.vertx.blueprint.kue.service", name = "vertx-kue-service-module")
package io.vertx.blueprint.kue.service;
import io.vertx.codegen.annotations.ModuleGen; | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/service/impl/JobServiceImpl.java | kue-core/src/main/java/io/vertx/blueprint/kue/service/impl/JobServiceImpl.java | package io.vertx.blueprint.kue.service.impl;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.blueprint.kue.util.RedisHelper;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Redis backend implementation of {@link JobService}.
*
* @author Eric Zhao
*/
public final class JobServiceImpl implements JobService {
private final Vertx vertx;
private final JsonObject config;
private final RedisClient client;
public JobServiceImpl(Vertx vertx) {
this(vertx, new JsonObject());
}
public JobServiceImpl(Vertx vertx, JsonObject config) {
this.vertx = vertx;
this.config = config;
this.client = RedisClient.create(vertx, RedisHelper.options(config));
Job.setVertx(vertx, RedisHelper.client(vertx, config)); // init static vertx instance inner job
}
@Override
public JobService getJob(long id, Handler<AsyncResult<Job>> handler) {
String zid = RedisHelper.createFIFO(id);
client.hgetall(RedisHelper.getKey("job:" + id), r -> {
if (r.succeeded()) {
try {
if (!r.result().containsKey("id")) {
handler.handle(Future.succeededFuture());
} else {
Job job = new Job(r.result());
job.setId(id);
job.setZid(zid);
handler.handle(Future.succeededFuture(job));
}
} catch (Exception e) {
e.printStackTrace();
this.removeBadJob(id, "", null);
handler.handle(Future.failedFuture(e));
}
} else {
this.removeBadJob(id, "", null);
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
@Override
public JobService removeJob(long id, Handler<AsyncResult<Void>> handler) {
this.getJob(id, r -> {
if (r.succeeded()) {
if (r.result() != null) {
r.result().remove()
.setHandler(handler);
} else {
handler.handle(Future.succeededFuture());
}
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
@Override
public JobService existsJob(long id, Handler<AsyncResult<Boolean>> handler) {
client.exists(RedisHelper.getKey("job:" + id), r -> {
if (r.succeeded()) {
if (r.result() == 0)
handler.handle(Future.succeededFuture(false));
else
handler.handle(Future.succeededFuture(true));
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
@Override
public JobService getJobLog(long id, Handler<AsyncResult<JsonArray>> handler) {
client.lrange(RedisHelper.getKey("job:" + id + ":log"), 0, -1, handler);
return this;
}
@Override
public JobService jobRangeByState(String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
return rangeGeneral("jobs:" + state.toUpperCase(), from, to, order, handler);
}
@Override
public JobService jobRangeByType(String type, String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
return rangeGeneral("jobs:" + type + ":" + state.toUpperCase(), from, to, order, handler);
}
@Override
public JobService jobRange(long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
return rangeGeneral("jobs", from, to, order, handler);
}
/**
* Range job by from, to and order
*
* @param key range type(key)
* @param from from
* @param to to
* @param order range order(asc, desc)
* @param handler result handler
*/
private JobService rangeGeneral(String key, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
if (to < from) {
handler.handle(Future.failedFuture("to can not be greater than from"));
return this;
}
client.zrange(RedisHelper.getKey(key), from, to, r -> {
if (r.succeeded()) {
if (r.result().size() == 0) { // maybe empty
handler.handle(Future.succeededFuture(new ArrayList<>()));
} else {
List<Long> list = (List<Long>) r.result().getList().stream()
.map(e -> RedisHelper.numStripFIFO((String) e))
.collect(Collectors.toList());
list.sort((a1, a2) -> {
if (order.equals("asc"))
return Long.compare(a1, a2);
else
return Long.compare(a2, a1);
});
long max = Math.max(list.get(0), list.get(list.size() - 1));
List<Job> jobList = new ArrayList<>();
list.forEach(e -> {
this.getJob(e, jr -> {
if (jr.succeeded()) {
if (jr.result() != null) {
jobList.add(jr.result());
}
if (e >= max) {
handler.handle(Future.succeededFuture(jobList));
}
} else {
handler.handle(Future.failedFuture(jr.cause()));
}
});
});
}
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
/**
* Remove bad job by id (absolutely)
*
* @param id job id
* @param handler result handler
*/
private JobService removeBadJob(long id, String jobType, Handler<AsyncResult<Void>> handler) {
String zid = RedisHelper.createFIFO(id);
client.transaction().multi(null)
.del(RedisHelper.getKey("job:" + id + ":log"), null)
.del(RedisHelper.getKey("job:" + id), null)
.zrem(RedisHelper.getKey("jobs:INACTIVE"), zid, null)
.zrem(RedisHelper.getKey("jobs:ACTIVE"), zid, null)
.zrem(RedisHelper.getKey("jobs:COMPLETE"), zid, null)
.zrem(RedisHelper.getKey("jobs:FAILED"), zid, null)
.zrem(RedisHelper.getKey("jobs:DELAYED"), zid, null)
.zrem(RedisHelper.getKey("jobs"), zid, null)
.zrem(RedisHelper.getKey("jobs:" + jobType + ":INACTIVE"), zid, null)
.zrem(RedisHelper.getKey("jobs:" + jobType + ":ACTIVE"), zid, null)
.zrem(RedisHelper.getKey("jobs:" + jobType + ":COMPLETE"), zid, null)
.zrem(RedisHelper.getKey("jobs:" + jobType + ":FAILED"), zid, null)
.zrem(RedisHelper.getKey("jobs:" + jobType + ":DELAYED"), zid, null)
.exec(r -> {
if (handler != null) {
if (r.succeeded())
handler.handle(Future.succeededFuture());
else
handler.handle(Future.failedFuture(r.cause()));
}
});
// TODO: add search functionality
return this;
}
@Override
public JobService cardByType(String type, JobState state, Handler<AsyncResult<Long>> handler) {
client.zcard(RedisHelper.getKey("jobs:" + type + ":" + state.name()), handler);
return this;
}
@Override
public JobService card(JobState state, Handler<AsyncResult<Long>> handler) {
client.zcard(RedisHelper.getKey("jobs:" + state.name()), handler);
return this;
}
@Override
public JobService completeCount(String type, Handler<AsyncResult<Long>> handler) {
if (type == null)
return this.card(JobState.COMPLETE, handler);
else
return this.cardByType(type, JobState.COMPLETE, handler);
}
@Override
public JobService failedCount(String type, Handler<AsyncResult<Long>> handler) {
if (type == null)
return this.card(JobState.FAILED, handler);
else
return this.cardByType(type, JobState.FAILED, handler);
}
@Override
public JobService inactiveCount(String type, Handler<AsyncResult<Long>> handler) {
if (type == null)
return this.card(JobState.INACTIVE, handler);
else
return this.cardByType(type, JobState.INACTIVE, handler);
}
@Override
public JobService activeCount(String type, Handler<AsyncResult<Long>> handler) {
if (type == null)
return this.card(JobState.ACTIVE, handler);
else
return this.cardByType(type, JobState.ACTIVE, handler);
}
@Override
public JobService delayedCount(String type, Handler<AsyncResult<Long>> handler) {
if (type == null)
return this.card(JobState.DELAYED, handler);
else
return this.cardByType(type, JobState.DELAYED, handler);
}
@Override
public JobService getAllTypes(Handler<AsyncResult<List<String>>> handler) {
client.smembers(RedisHelper.getKey("job:types"), r -> {
if (r.succeeded()) {
handler.handle(Future.succeededFuture(r.result().getList()));
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
@Override
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
client.zrange(RedisHelper.getStateKey(state), 0, -1, r -> {
if (r.succeeded()) {
List<Long> list = r.result().stream()
.map(e -> RedisHelper.numStripFIFO((String) e))
.collect(Collectors.toList());
handler.handle(Future.succeededFuture(list));
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
@Override
public JobService getWorkTime(Handler<AsyncResult<Long>> handler) {
client.get(RedisHelper.getKey("stats:work-time"), r -> {
if (r.succeeded()) {
handler.handle(Future.succeededFuture(Long.parseLong(r.result() == null ? "0" : r.result())));
} else {
handler.handle(Future.failedFuture(r.cause()));
}
});
return this;
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/package-info.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/package-info.java | @ModuleGen(groupPackage = "io.vertx.blueprint.kue.queue", name = "vertx-kue-queue-core-module")
package io.vertx.blueprint.kue.queue;
import io.vertx.codegen.annotations.ModuleGen; | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/JobState.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/JobState.java | package io.vertx.blueprint.kue.queue;
import io.vertx.codegen.annotations.VertxGen;
/**
* Vert.x Blueprint - Job Queue
* Job state enum class
*
* @author Eric Zhao
*/
@VertxGen
public enum JobState {
INACTIVE,
ACTIVE,
COMPLETE,
FAILED,
DELAYED
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/Priority.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/Priority.java | package io.vertx.blueprint.kue.queue;
import io.vertx.codegen.annotations.VertxGen;
/**
* Vert.x Blueprint - Job Queue
* Job priority enum class
*
* @author Eric Zhao
*/
@VertxGen
public enum Priority {
LOW(10),
NORMAL(0),
MEDIUM(-5),
HIGH(-10),
CRITICAL(-15);
private int value;
Priority(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/KueWorker.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/KueWorker.java | package io.vertx.blueprint.kue.queue;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.util.RedisHelper;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.redis.RedisClient;
import java.util.Optional;
/**
* The verticle for processing Kue tasks.
*
* @author Eric Zhao
*/
public class KueWorker extends AbstractVerticle {
private static Logger logger = LoggerFactory.getLogger(Job.class);
private final Kue kue;
private RedisClient client; // Every worker use different clients.
private EventBus eventBus;
private Job job;
private final String type;
private final Handler<Job> jobHandler;
private MessageConsumer doneConsumer; // Preserve for unregister the consumer.
private MessageConsumer doneFailConsumer;
public KueWorker(String type, Handler<Job> jobHandler, Kue kue) {
this.type = type;
this.jobHandler = jobHandler;
this.kue = kue;
}
@Override
public void start() throws Exception {
this.eventBus = vertx.eventBus();
this.client = RedisHelper.client(vertx, config());
prepareAndStart();
}
/**
* Prepare job and start processing procedure.
*/
private void prepareAndStart() {
cleanup();
this.getJobFromBackend().setHandler(jr -> {
if (jr.succeeded()) {
if (jr.result().isPresent()) {
this.job = jr.result().get();
process();
} else {
this.emitJobEvent("error", null, new JsonObject().put("message", "job_not_exist"));
throw new IllegalStateException("job not exist");
}
} else {
this.emitJobEvent("error", null, new JsonObject().put("message", jr.cause().getMessage()));
jr.cause().printStackTrace();
}
});
}
/**
* Process the job.
*/
private void process() {
long curTime = System.currentTimeMillis();
this.job.setStarted_at(curTime)
.set("started_at", String.valueOf(curTime))
.compose(Job::active)
.setHandler(r -> {
if (r.succeeded()) {
Job j = r.result();
// emit start event
this.emitJobEvent("start", j, null);
logger.debug("KueWorker::process[instance:Verticle(" + this.deploymentID() + ")] with job " + job.getId());
// process logic invocation
try {
jobHandler.handle(j);
} catch (Exception ex) {
j.done(ex);
}
// subscribe the job done event
doneConsumer = eventBus.consumer(Kue.workerAddress("done", j), msg -> {
createDoneCallback(j).handle(Future.succeededFuture(
((JsonObject) msg.body()).getJsonObject("result")));
});
doneFailConsumer = eventBus.consumer(Kue.workerAddress("done_fail", j), msg -> {
createDoneCallback(j).handle(Future.failedFuture(
(String) msg.body()));
});
} else {
this.emitJobEvent("error", this.job, new JsonObject().put("message", r.cause().getMessage()));
r.cause().printStackTrace();
}
});
}
private void cleanup() {
Optional.ofNullable(doneConsumer).ifPresent(MessageConsumer::unregister);
Optional.ofNullable(doneFailConsumer).ifPresent(MessageConsumer::unregister);
this.job = null;
}
private void error(Throwable ex, Job job) {
JsonObject err = new JsonObject().put("message", ex.getMessage())
.put("id", job.getId());
eventBus.send(Kue.workerAddress("error"), err);
}
private void fail(Throwable ex) {
job.failedAttempt(ex).setHandler(r -> {
if (r.failed()) {
this.error(r.cause(), job);
} else {
Job res = r.result();
if (res.hasAttempts()) {
this.emitJobEvent("failed_attempt", job, new JsonObject().put("message", ex.getMessage())); // shouldn't include err?
} else {
this.emitJobEvent("failed", job, new JsonObject().put("message", ex.getMessage()));
}
prepareAndStart();
}
});
}
/**
* Redis zpop atomic primitive with transaction.
*
* @param key redis key
* @return the async result of zpop
*/
private Future<Long> zpop(String key) {
Future<Long> future = Future.future();
client.transaction()
.multi(_failure())
.zrange(key, 0, 0, _failure())
.zremrangebyrank(key, 0, 0, _failure())
.exec(r -> {
if (r.succeeded()) {
JsonArray res = r.result();
if (res.getJsonArray(0).size() == 0) // empty set
future.fail(new IllegalStateException("Empty zpop set"));
else {
try {
future.complete(Long.parseLong(RedisHelper.stripFIFO(
res.getJsonArray(0).getString(0))));
} catch (Exception ex) {
future.fail(ex);
}
}
} else {
future.fail(r.cause());
}
});
return future;
}
/**
* Get a job from Redis backend by priority.
*
* @return async result of job
*/
private Future<Optional<Job>> getJobFromBackend() {
Future<Optional<Job>> future = Future.future();
client.blpop(RedisHelper.getKey(this.type + ":jobs"), 0, r1 -> {
if (r1.failed()) {
client.lpush(RedisHelper.getKey(this.type + ":jobs"), "1", r2 -> {
if (r2.failed())
future.fail(r2.cause());
});
} else {
this.zpop(RedisHelper.getKey("jobs:" + this.type + ":INACTIVE"))
.compose(kue::getJob)
.setHandler(r -> {
if (r.succeeded()) {
future.complete(r.result());
} else
future.fail(r.cause());
});
}
});
return future;
}
private Handler<AsyncResult<JsonObject>> createDoneCallback(Job job) {
return r0 -> {
if (job == null) {
// maybe should warn
return;
}
if (r0.failed()) {
this.fail(r0.cause());
return;
}
long dur = System.currentTimeMillis() - job.getStarted_at();
job.setDuration(dur)
.set("duration", String.valueOf(dur));
JsonObject result = r0.result();
if (result != null) {
job.setResult(result)
.set("result", result.encodePrettily());
}
job.complete().setHandler(r -> {
if (r.succeeded()) {
Job j = r.result();
if (j.isRemoveOnComplete()) {
j.remove();
}
this.emitJobEvent("complete", j, null);
this.prepareAndStart(); // prepare for next job
}
});
};
}
@Override
public void stop() throws Exception {
// stop hook
cleanup();
}
/**
* Emit job event.
*
* @param event event type
* @param job corresponding job
* @param extra extra data
*/
private void emitJobEvent(String event, Job job, JsonObject extra) {
JsonObject data = new JsonObject().put("extra", extra);
if (job != null) {
data.put("job", job.toJson());
}
eventBus.send(Kue.workerAddress("job_" + event), data);
switch (event) {
case "failed":
case "failed_attempt":
eventBus.send(Kue.getCertainJobAddress(event, job), data);
break;
case "error":
eventBus.send(Kue.workerAddress("error"), data);
break;
default:
eventBus.send(Kue.getCertainJobAddress(event, job), job.toJson());
}
}
private static <T> Handler<AsyncResult<T>> _failure() {
return r -> {
if (r.failed())
r.cause().printStackTrace();
};
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/Job.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/Job.java | package io.vertx.blueprint.kue.queue;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.util.RedisHelper;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.codegen.annotations.Fluent;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.redis.RedisClient;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;
/**
* Vert.x Kue
* Job domain class.
*
* @author Eric Zhao
*/
@DataObject(generateConverter = true)
public class Job {
// TODO: refactor the job class.
private static Logger logger = LoggerFactory.getLogger(Job.class);
private static Vertx vertx;
private static RedisClient client;
private static EventBus eventBus;
public static void setVertx(Vertx v, RedisClient redisClient) {
vertx = v;
client = redisClient;
eventBus = vertx.eventBus();
}
// job properties
private final String address_id;
private long id = -1;
private String zid;
private String type;
private JsonObject data;
private Priority priority = Priority.NORMAL;
private JobState state = JobState.INACTIVE;
private long delay = 0;
private int max_attempts = 1;
private boolean removeOnComplete = false;
private int ttl = 0;
private JsonObject backoff;
private int attempts = 0;
private int progress = 0;
private JsonObject result;
// job metrics
private long created_at;
private long promote_at;
private long updated_at;
private long failed_at;
private long started_at;
private long duration;
public Job() {
this.address_id = UUID.randomUUID().toString();
_checkStatic();
}
public Job(JsonObject json) { // TODO: optimize this!
JobConverter.fromJson(json, this);
this.address_id = json.getString("address_id");
// generated converter cannot handle this
if (this.data == null) {
this.data = new JsonObject(json.getString("data"));
if (json.getValue("backoff") != null) {
this.backoff = new JsonObject(json.getString("backoff"));
}
this.progress = Integer.parseInt(json.getString("progress"));
this.attempts = Integer.parseInt(json.getString("attempts"));
this.max_attempts = Integer.parseInt(json.getString("max_attempts"));
this.created_at = Long.parseLong(json.getString("created_at"));
this.updated_at = Long.parseLong(json.getString("updated_at"));
this.started_at = Long.parseLong(json.getString("started_at"));
this.promote_at = Long.parseLong(json.getString("promote_at"));
this.delay = Long.parseLong(json.getString("delay"));
this.duration = Long.parseLong(json.getString("duration"));
}
if (this.id < 0) {
if ((json.getValue("id")) instanceof CharSequence)
this.setId(Long.parseLong(json.getString("id")));
}
_checkStatic();
}
public Job(Job other) {
this.id = other.id;
this.zid = other.zid;
this.address_id = other.address_id;
this.type = other.type;
this.data = other.data == null ? null : other.data.copy();
this.priority = other.priority;
this.state = other.state;
this.delay = other.delay;
// job metrics
this.created_at = other.created_at;
this.promote_at = other.promote_at;
this.updated_at = other.updated_at;
this.failed_at = other.failed_at;
this.started_at = other.started_at;
this.duration = other.duration;
this.attempts = other.attempts;
this.max_attempts = other.max_attempts;
this.removeOnComplete = other.removeOnComplete;
_checkStatic();
}
public Job(String type, JsonObject data) {
this.type = type;
this.data = data;
this.address_id = UUID.randomUUID().toString();
_checkStatic();
}
public JsonObject toJson() {
JsonObject json = new JsonObject();
JobConverter.toJson(this, json);
return json;
}
private void _checkStatic() {
if (vertx == null) {
logger.warn("static Vertx instance in Job class is not initialized!");
}
}
/**
* Set job priority.
*
* @param level job priority level
*/
@Fluent
public Job priority(Priority level) {
if (level != null)
this.priority = level;
return this;
}
/**
* Set new job state.
*
* @param newState new job state
* @return async result of this job
*/
public Future<Job> state(JobState newState) {
Future<Job> future = Future.future();
RedisClient client = RedisHelper.client(vertx, new JsonObject()); // use a new client to keep transaction
JobState oldState = this.state;
logger.debug("Job::state(from: " + oldState + ", to:" + newState.name() + ")");
client.transaction().multi(r0 -> {
if (r0.succeeded()) {
if (oldState != null && !oldState.equals(newState)) {
client.transaction().zrem(RedisHelper.getStateKey(oldState), this.zid, _failure())
.zrem(RedisHelper.getKey("jobs:" + this.type + ":" + oldState.name()), this.zid, _failure());
}
client.transaction().hset(RedisHelper.getKey("job:" + this.id), "state", newState.name(), _failure())
.zadd(RedisHelper.getKey("jobs:" + newState.name()), this.priority.getValue(), this.zid, _failure())
.zadd(RedisHelper.getKey("jobs:" + this.type + ":" + newState.name()), this.priority.getValue(), this.zid, _failure());
switch (newState) { // dispatch different state
case ACTIVE:
client.transaction().zadd(RedisHelper.getKey("jobs:" + newState.name()),
this.priority.getValue() < 0 ? this.priority.getValue() : -this.priority.getValue(),
this.zid, _failure());
break;
case DELAYED:
client.transaction().zadd(RedisHelper.getKey("jobs:" + newState.name()),
this.promote_at, this.zid, _failure());
break;
case INACTIVE:
client.transaction().lpush(RedisHelper.getKey(this.type + ":jobs"), "1", _failure());
break;
default:
}
this.state = newState;
client.transaction().exec(r -> {
if (r.succeeded()) {
future.complete(this);
} else {
future.fail(r.cause());
}
});
} else {
future.fail(r0.cause());
}
});
return future.compose(Job::updateNow);
}
/**
* Set error to the job.
*
* @param ex exception
*/
public Future<Job> error(Throwable ex) {
// send this on worker address in order to consume it with `Kue#on` method
return this.emitError(ex)
.set("error", ex.getMessage())
.compose(j -> j.log("error | " + ex.getMessage()));
}
/**
* Complete a job.
*/
public Future<Job> complete() {
return this.setProgress(100)
.set("progress", "100")
.compose(r -> r.state(JobState.COMPLETE));
}
/**
* Set a job to `failed` state.
*/
public Future<Job> failed() {
this.failed_at = System.currentTimeMillis();
return this.updateNow()
.compose(j -> j.set("failed_at", String.valueOf(j.failed_at)))
.compose(j -> j.state(JobState.FAILED));
}
/**
* Set a job to `inactive` state.
*/
public Future<Job> inactive() {
return this.state(JobState.INACTIVE);
}
/**
* Set a job active(started).
*/
public Future<Job> active() {
return this.state(JobState.ACTIVE);
}
/**
* Set a job to `delayed` state.
*/
public Future<Job> delayed() {
return this.state(JobState.DELAYED);
}
/**
* Log with some messages.
*/
public Future<Job> log(String msg) {
Future<Job> future = Future.future();
client.rpush(RedisHelper.getKey("job:" + this.id + ":log"), msg, _completer(future, this));
return future.compose(Job::updateNow);
}
/**
* Set progress.
*
* @param complete current value
* @param total total value
*/
public Future<Job> progress(int complete, int total) {
int n = Math.min(100, complete * 100 / total);
this.emit("progress", n);
return this.setProgress(n)
.set("progress", String.valueOf(n))
.compose(Job::updateNow);
}
/**
* Set a key with value in Redis.
*
* @param key property key
* @param value value
*/
public Future<Job> set(String key, String value) {
Future<Job> future = Future.future();
client.hset(RedisHelper.getKey("job:" + this.id), key, value, r -> {
if (r.succeeded())
future.complete(this);
else
future.fail(r.cause());
});
return future;
}
/**
* Get a property of the job from backend.
*
* @param key property key(name)
* @return async result
*/
@Fluent
public Future<String> get(String key) {
Future<String> future = Future.future();
client.hget(RedisHelper.getKey("job:" + this.id), key, future.completer());
return future;
}
// TODO: enhancement: integrate backoff with Circuit Breaker
/**
* Get job attempt backoff strategy implementation.
* Current we support two types: `exponential` and `fixed`.
*
* @return the corresponding function
*/
private Function<Integer, Long> getBackoffImpl() {
String type = this.backoff.getString("type", "fixed"); // by default `fixed` type
long _delay = this.backoff.getLong("delay", this.delay);
switch (type) {
case "exponential":
return attempts -> Math.round(_delay * 0.5 * (Math.pow(2, attempts) - 1));
case "fixed":
default:
return attempts -> _delay;
}
}
/**
* Try to reattempt the job.
*/
private Future<Job> reattempt() {
if (this.backoff != null) {
long delay = this.getBackoffImpl().apply(attempts); // calc delay time
return this.setDelay(delay)
.setPromote_at(System.currentTimeMillis() + delay)
.update()
.compose(Job::delayed);
} else {
return this.inactive(); // only restart the job
}
}
/**
* Attempt once and save attemptAdd times to Redis backend.
*/
private Future<Job> attemptAdd() {
Future<Job> future = Future.future();
String key = RedisHelper.getKey("job:" + this.id);
if (this.attempts < this.max_attempts) {
client.hincrby(key, "attempts", 1, r -> {
if (r.succeeded()) {
this.attempts = r.result().intValue();
future.complete(this);
} else {
this.emitError(r.cause());
future.fail(r.cause());
}
});
} else {
future.complete(this);
}
return future;
}
private Future<Job> attemptInternal() {
int remaining = this.max_attempts - this.attempts;
logger.debug("Job attempting...max=" + this.max_attempts + ", past=" + this.attempts);
if (remaining > 0) {
return this.attemptAdd()
.compose(Job::reattempt)
.setHandler(r -> {
if (r.failed()) {
this.emitError(r.cause());
}
});
} else if (remaining == 0) {
return Future.failedFuture("No more attempts");
} else {
return Future.failedFuture(new IllegalStateException("Attempts Exceeded"));
}
}
/**
* Failed attempt.
*
* @param err exception
*/
Future<Job> failedAttempt(Throwable err) {
return this.error(err)
.compose(Job::failed)
.compose(Job::attemptInternal);
}
/**
* Refresh ttl
*/
Future<Job> refreshTtl() {
Future<Job> future = Future.future();
if (this.state == JobState.ACTIVE && this.ttl > 0) {
client.zadd(RedisHelper.getStateKey(this.state), System.currentTimeMillis() + ttl,
this.zid, _completer(future, this));
}
return future;
}
/**
* Save the job to the backend.
*/
public Future<Job> save() {
// check
Objects.requireNonNull(this.type, "Job type cannot be null");
if (this.id > 0)
return update();
Future<Job> future = Future.future();
// generate id
client.incr(RedisHelper.getKey("ids"), res -> {
if (res.succeeded()) {
this.id = res.result();
this.zid = RedisHelper.createFIFO(id);
String key = RedisHelper.getKey("job:" + this.id);
// need subscribe
if (this.delay > 0) {
this.state = JobState.DELAYED;
}
client.sadd(RedisHelper.getKey("job:types"), this.type, _failure());
this.created_at = System.currentTimeMillis();
this.promote_at = this.created_at + this.delay;
// save job
client.hmset(key, this.toJson(), _completer(future, this));
} else {
future.fail(res.cause());
}
});
return future.compose(Job::update);
}
/**
* Update the job update time (`updateTime`).
*/
Future<Job> updateNow() {
this.updated_at = System.currentTimeMillis();
return this.set("updated_at", String.valueOf(updated_at));
}
/**
* Update the job.
*/
Future<Job> update() {
Future<Job> future = Future.future();
this.updated_at = System.currentTimeMillis();
client.transaction().multi(_failure())
.hmset(RedisHelper.getKey("job:" + this.id), this.toJson(), _failure())
.zadd(RedisHelper.getKey("jobs"), this.priority.getValue(), this.zid, _failure())
.exec(_completer(future, this));
// TODO: add search functionality (full-index engine, for Chinese language this is difficult)
return future.compose(r ->
this.state(this.state));
}
/**
* Remove the job.
*/
public Future<Void> remove() {
Future<Void> future = Future.future();
client.transaction().multi(_failure())
.zrem(RedisHelper.getKey("jobs:" + this.stateName()), this.zid, _failure())
.zrem(RedisHelper.getKey("jobs:" + this.type + ":" + this.stateName()), this.zid, _failure())
.zrem(RedisHelper.getKey("jobs"), this.zid, _failure())
.del(RedisHelper.getKey("job:" + this.id + ":log"), _failure())
.del(RedisHelper.getKey("job:" + this.id), _failure())
.exec(r -> {
if (r.succeeded()) {
this.emit("remove", new JsonObject().put("id", this.id));
future.complete();
} else {
future.fail(r.cause());
}
});
return future;
}
/**
* Add on complete handler on event bus.
*
* @param completeHandler complete handler
*/
@Fluent
public Job onComplete(Handler<Job> completeHandler) {
this.on("complete", message -> {
completeHandler.handle(new Job((JsonObject) message.body()));
});
return this;
}
/**
* Add on failure handler on event bus.
*
* @param failureHandler failure handler
*/
@Fluent
public Job onFailure(Handler<JsonObject> failureHandler) {
this.on("failed", message -> {
failureHandler.handle((JsonObject) message.body());
});
return this;
}
/**
* Add on failure attemptAdd handler on event bus.
*
* @param failureHandler failure handler
*/
@Fluent
public Job onFailureAttempt(Handler<JsonObject> failureHandler) {
this.on("failed_attempt", message -> {
failureHandler.handle((JsonObject) message.body());
});
return this;
}
/**
* Add on promotion handler on event bus.
*
* @param handler failure handler
*/
@Fluent
public Job onPromotion(Handler<Job> handler) {
this.on("promotion", message -> {
handler.handle(new Job((JsonObject) message.body()));
});
return this;
}
/**
* Add on start handler on event bus.
*
* @param handler failure handler
*/
@Fluent
public Job onStart(Handler<Job> handler) {
this.on("start", message -> {
handler.handle(new Job((JsonObject) message.body()));
});
return this;
}
/**
* Add on remove handler on event bus.
*
* @param removeHandler failure handler
*/
@Fluent
public Job onRemove(Handler<JsonObject> removeHandler) {
this.on("start", message -> {
removeHandler.handle((JsonObject) message.body());
});
return this;
}
/**
* Add on progress changed handler on event bus.
*
* @param progressHandler progress handler
*/
@Fluent
public Job onProgress(Handler<Integer> progressHandler) {
this.on("progress", message -> {
progressHandler.handle((Integer) message.body());
});
return this;
}
/**
* Add a certain event handler on event bus.
*
* @param event event type
* @param handler event handler
*/
@Fluent
public <T> Job on(String event, Handler<Message<T>> handler) {
logger.debug("[LOG] On: " + Kue.getCertainJobAddress(event, this));
eventBus.consumer(Kue.getCertainJobAddress(event, this), handler);
return this;
}
/**
* Send an event to event bus with some data.
*
* @param event event type
* @param msg data
*/
@Fluent
public Job emit(String event, Object msg) {
logger.debug("[LOG] Emit: " + Kue.getCertainJobAddress(event, this));
eventBus.send(Kue.getCertainJobAddress(event, this), msg);
return this;
}
@Fluent
public Job emitError(Throwable ex) {
JsonObject errorMessage = new JsonObject().put("id", this.id)
.put("message", ex.getMessage());
eventBus.send(Kue.workerAddress("error"), errorMessage);
eventBus.send(Kue.getCertainJobAddress("error", this), errorMessage);
return this;
}
/**
* Fail a job.
*/
@Fluent
public Job done(Throwable ex) {
eventBus.send(Kue.workerAddress("done_fail", this), ex.getMessage());
return this;
}
/**
* Finish a job.
*/
@Fluent
public Job done() {
eventBus.send(Kue.workerAddress("done", this), this.toJson());
return this;
}
// getter and setter
public long getId() {
return id;
}
public Job setId(long id) {
this.id = id;
return this;
}
public JsonObject getData() {
return data;
}
public Job setData(JsonObject data) {
this.data = data;
return this;
}
public String getType() {
return type;
}
public Job setType(String type) {
this.type = type;
return this;
}
public Priority getPriority() {
return priority;
}
public Job setPriority(Priority priority) {
this.priority = priority;
return this;
}
public JsonObject getResult() {
return result;
}
public Job setResult(JsonObject result) {
this.result = result;
return this;
}
public int getProgress() {
return progress;
}
public Job setProgress(int progress) {
this.progress = progress;
return this;
}
public long getDelay() {
return delay;
}
public Job setDelay(long delay) {
if (delay > 0) {
this.delay = delay;
}
return this;
}
public JobState getState() {
return state;
}
public String stateName() {
return state.name();
}
public Job setState(JobState state) {
this.state = state;
return this;
}
public String getZid() {
return zid;
}
public Job setZid(String zid) {
this.zid = zid;
return this;
}
public boolean hasAttempts() {
return this.max_attempts - this.attempts > 0;
}
public int getAttempts() {
return attempts;
}
public Job setAttempts(int attempts) {
this.attempts = attempts;
return this;
}
public long getCreated_at() {
return created_at;
}
public Job setCreated_at(long created_at) {
this.created_at = created_at;
return this;
}
public long getPromote_at() {
return promote_at;
}
public Job setPromote_at(long promote_at) {
this.promote_at = promote_at;
return this;
}
public long getUpdated_at() {
return updated_at;
}
public Job setUpdated_at(long updated_at) {
this.updated_at = updated_at;
return this;
}
public long getFailed_at() {
return failed_at;
}
public Job setFailed_at(long failed_at) {
this.failed_at = failed_at;
return this;
}
public long getStarted_at() {
return started_at;
}
public Job setStarted_at(long started_at) {
this.started_at = started_at;
return this;
}
public long getDuration() {
return duration;
}
public Job setDuration(long duration) {
this.duration = duration;
return this;
}
public int getMax_attempts() {
return max_attempts;
}
public Job setMax_attempts(int max_attempts) {
this.max_attempts = max_attempts;
return this;
}
public String getAddress_id() {
return address_id;
}
public boolean isRemoveOnComplete() {
return removeOnComplete;
}
public Job setRemoveOnComplete(boolean removeOnComplete) {
this.removeOnComplete = removeOnComplete;
return this;
}
public JsonObject getBackoff() {
return backoff;
}
public Job setBackoff(JsonObject backoff) {
this.backoff = backoff;
return this;
}
public int getTtl() {
return ttl;
}
public Job setTtl(int ttl) {
this.ttl = ttl;
return this;
}
/**
* Basic failure handler (always throws the exception)
*/
private static <T> Handler<AsyncResult<T>> _failure() {
return r -> {
if (r.failed())
r.cause().printStackTrace();
};
}
private static <T, R> Handler<AsyncResult<T>> _completer(Future<R> future, R result) {
return r -> {
if (r.failed())
future.fail(r.cause());
else
future.complete(result);
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Job job = (Job) o;
if (id != job.id) return false;
if (!address_id.equals(job.address_id)) return false;
return type.equals(job.type);
}
@Override
public int hashCode() {
int result = address_id.hashCode();
result = 31 * result + (int) (id ^ (id >>> 32));
result = 31 * result + type.hashCode();
return result;
}
@Override
public String toString() {
return this.toJson().encodePrettily();
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/java/io/vertx/blueprint/kue/queue/KueVerticle.java | kue-core/src/main/java/io/vertx/blueprint/kue/queue/KueVerticle.java | package io.vertx.blueprint.kue.queue;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.blueprint.kue.util.RedisHelper;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.redis.RedisClient;
import io.vertx.serviceproxy.ProxyHelper;
/**
* Vert.x Blueprint - Job Queue
* Kue Verticle
*
* @author Eric Zhao
*/
public class KueVerticle extends AbstractVerticle {
private static Logger logger = LoggerFactory.getLogger(Job.class);
public static final String EB_JOB_SERVICE_ADDRESS = "vertx.kue.service.job.internal";
private JsonObject config;
private JobService jobService;
@Override
public void start(Future<Void> future) throws Exception {
this.config = config();
this.jobService = JobService.create(vertx, config);
// create redis client
RedisClient redisClient = RedisHelper.client(vertx, config);
redisClient.ping(pr -> { // test connection
if (pr.succeeded()) {
logger.info("Kue Verticle is running...");
// register job service
ProxyHelper.registerService(JobService.class, vertx, jobService, EB_JOB_SERVICE_ADDRESS);
future.complete();
} else {
logger.error("oops!", pr.cause());
future.fail(pr.cause());
}
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/generated/io/vertx/blueprint/kue/service/JobServiceVertxProxyHandler.java | kue-core/src/main/generated/io/vertx/blueprint/kue/service/JobServiceVertxProxyHandler.java | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.blueprint.kue.service;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.core.Vertx;
import io.vertx.core.Handler;
import io.vertx.core.AsyncResult;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.eventbus.ReplyException;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import io.vertx.serviceproxy.ProxyHelper;
import io.vertx.serviceproxy.ProxyHandler;
import io.vertx.serviceproxy.ServiceException;
import io.vertx.serviceproxy.ServiceExceptionMessageCodec;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.core.Vertx;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.core.json.JsonArray;
import java.util.List;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.core.json.JsonObject;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
/*
Generated Proxy code - DO NOT EDIT
@author Roger the Robot
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class JobServiceVertxProxyHandler extends ProxyHandler {
public static final long DEFAULT_CONNECTION_TIMEOUT = 5 * 60; // 5 minutes
private final Vertx vertx;
private final JobService service;
private final long timerID;
private long lastAccessed;
private final long timeoutSeconds;
public JobServiceVertxProxyHandler(Vertx vertx, JobService service) {
this(vertx, service, DEFAULT_CONNECTION_TIMEOUT);
}
public JobServiceVertxProxyHandler(Vertx vertx, JobService service, long timeoutInSecond) {
this(vertx, service, true, timeoutInSecond);
}
public JobServiceVertxProxyHandler(Vertx vertx, JobService service, boolean topLevel, long timeoutSeconds) {
this.vertx = vertx;
this.service = service;
this.timeoutSeconds = timeoutSeconds;
try {
this.vertx.eventBus().registerDefaultCodec(ServiceException.class,
new ServiceExceptionMessageCodec());
} catch (IllegalStateException ex) {
}
if (timeoutSeconds != -1 && !topLevel) {
long period = timeoutSeconds * 1000 / 2;
if (period > 10000) {
period = 10000;
}
this.timerID = vertx.setPeriodic(period, this::checkTimedOut);
} else {
this.timerID = -1;
}
accessed();
}
public MessageConsumer<JsonObject> registerHandler(String address) {
MessageConsumer<JsonObject> consumer = vertx.eventBus().<JsonObject>consumer(address).handler(this);
this.setConsumer(consumer);
return consumer;
}
private void checkTimedOut(long id) {
long now = System.nanoTime();
if (now - lastAccessed > timeoutSeconds * 1000000000) {
close();
}
}
@Override
public void close() {
if (timerID != -1) {
vertx.cancelTimer(timerID);
}
super.close();
}
private void accessed() {
this.lastAccessed = System.nanoTime();
}
public void handle(Message<JsonObject> msg) {
try {
JsonObject json = msg.body();
String action = msg.headers().get("action");
if (action == null) {
throw new IllegalStateException("action not specified");
}
accessed();
switch (action) {
case "getJob": {
service.getJob(json.getValue("id") == null ? null : (json.getLong("id").longValue()), res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(res.result() == null ? null : res.result().toJson());
}
});
break;
}
case "removeJob": {
service.removeJob(json.getValue("id") == null ? null : (json.getLong("id").longValue()), createHandler(msg));
break;
}
case "existsJob": {
service.existsJob(json.getValue("id") == null ? null : (json.getLong("id").longValue()), createHandler(msg));
break;
}
case "getJobLog": {
service.getJobLog(json.getValue("id") == null ? null : (json.getLong("id").longValue()), createHandler(msg));
break;
}
case "jobRangeByState": {
service.jobRangeByState((java.lang.String) json.getValue("state"), json.getValue("from") == null ? null : (json.getLong("from").longValue()), json.getValue("to") == null ? null : (json.getLong("to").longValue()), (java.lang.String) json.getValue("order"), res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(new JsonArray(res.result().stream().map(Job::toJson).collect(Collectors.toList())));
}
});
break;
}
case "jobRangeByType": {
service.jobRangeByType((java.lang.String) json.getValue("type"), (java.lang.String) json.getValue("state"), json.getValue("from") == null ? null : (json.getLong("from").longValue()), json.getValue("to") == null ? null : (json.getLong("to").longValue()), (java.lang.String) json.getValue("order"), res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(new JsonArray(res.result().stream().map(Job::toJson).collect(Collectors.toList())));
}
});
break;
}
case "jobRange": {
service.jobRange(json.getValue("from") == null ? null : (json.getLong("from").longValue()), json.getValue("to") == null ? null : (json.getLong("to").longValue()), (java.lang.String) json.getValue("order"), res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(new JsonArray(res.result().stream().map(Job::toJson).collect(Collectors.toList())));
}
});
break;
}
case "cardByType": {
service.cardByType((java.lang.String) json.getValue("type"), json.getString("state") == null ? null : io.vertx.blueprint.kue.queue.JobState.valueOf(json.getString("state")), createHandler(msg));
break;
}
case "card": {
service.card(json.getString("state") == null ? null : io.vertx.blueprint.kue.queue.JobState.valueOf(json.getString("state")), createHandler(msg));
break;
}
case "completeCount": {
service.completeCount((java.lang.String) json.getValue("type"), createHandler(msg));
break;
}
case "failedCount": {
service.failedCount((java.lang.String) json.getValue("type"), createHandler(msg));
break;
}
case "inactiveCount": {
service.inactiveCount((java.lang.String) json.getValue("type"), createHandler(msg));
break;
}
case "activeCount": {
service.activeCount((java.lang.String) json.getValue("type"), createHandler(msg));
break;
}
case "delayedCount": {
service.delayedCount((java.lang.String) json.getValue("type"), createHandler(msg));
break;
}
case "getAllTypes": {
service.getAllTypes(createListHandler(msg));
break;
}
case "getIdsByState": {
service.getIdsByState(json.getString("state") == null ? null : io.vertx.blueprint.kue.queue.JobState.valueOf(json.getString("state")), createListHandler(msg));
break;
}
case "getWorkTime": {
service.getWorkTime(createHandler(msg));
break;
}
default: {
throw new IllegalStateException("Invalid action: " + action);
}
}
} catch (Throwable t) {
msg.reply(new ServiceException(500, t.getMessage()));
throw t;
}
}
private <T> Handler<AsyncResult<T>> createHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
if (res.result() != null && res.result().getClass().isEnum()) {
msg.reply(((Enum) res.result()).name());
} else {
msg.reply(res.result());
}
}
};
}
private <T> Handler<AsyncResult<List<T>>> createListHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(new JsonArray(res.result()));
}
};
}
private <T> Handler<AsyncResult<Set<T>>> createSetHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
msg.reply(new JsonArray(new ArrayList<>(res.result())));
}
};
}
private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
JsonArray arr = new JsonArray();
for (Character chr : res.result()) {
arr.add((int) chr);
}
msg.reply(arr);
}
};
}
private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
return res -> {
if (res.failed()) {
if (res.cause() instanceof ServiceException) {
msg.reply(res.cause());
} else {
msg.reply(new ServiceException(-1, res.cause().getMessage()));
}
} else {
JsonArray arr = new JsonArray();
for (Character chr : res.result()) {
arr.add((int) chr);
}
msg.reply(arr);
}
};
}
private <T> Map<String, T> convertMap(Map map) {
return (Map<String, T>) map;
}
private <T> List<T> convertList(List list) {
return (List<T>) list;
}
private <T> Set<T> convertSet(List list) {
return new HashSet<T>((List<T>) list);
}
} | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/generated/io/vertx/blueprint/kue/service/JobServiceVertxEBProxy.java | kue-core/src/main/generated/io/vertx/blueprint/kue/service/JobServiceVertxEBProxy.java | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.blueprint.kue.service;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.Vertx;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.function.Function;
import io.vertx.serviceproxy.ProxyHelper;
import io.vertx.serviceproxy.ServiceException;
import io.vertx.serviceproxy.ServiceExceptionMessageCodec;
import io.vertx.blueprint.kue.service.JobService;
import io.vertx.core.Vertx;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.core.json.JsonArray;
import java.util.List;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.core.json.JsonObject;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
/*
Generated Proxy code - DO NOT EDIT
@author Roger the Robot
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class JobServiceVertxEBProxy implements JobService {
private Vertx _vertx;
private String _address;
private DeliveryOptions _options;
private boolean closed;
public JobServiceVertxEBProxy(Vertx vertx, String address) {
this(vertx, address, null);
}
public JobServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) {
this._vertx = vertx;
this._address = address;
this._options = options;
try {
this._vertx.eventBus().registerDefaultCodec(ServiceException.class,
new ServiceExceptionMessageCodec());
} catch (IllegalStateException ex) {
}
}
public JobService getJob(long id, Handler<AsyncResult<Job>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("id", id);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "getJob");
_vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body() == null ? null : new Job(res.result().body())));
}
});
return this;
}
public JobService removeJob(long id, Handler<AsyncResult<Void>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("id", id);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "removeJob");
_vertx.eventBus().<Void>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService existsJob(long id, Handler<AsyncResult<Boolean>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("id", id);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "existsJob");
_vertx.eventBus().<Boolean>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService getJobLog(long id, Handler<AsyncResult<JsonArray>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("id", id);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "getJobLog");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService jobRangeByState(String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("state", state);
_json.put("from", from);
_json.put("to", to);
_json.put("order", order);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "jobRangeByState");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body().stream().map(o -> o instanceof Map ? new Job(new JsonObject((Map) o)) : new Job((JsonObject) o)).collect(Collectors.toList())));
}
});
return this;
}
public JobService jobRangeByType(String type, String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
_json.put("state", state);
_json.put("from", from);
_json.put("to", to);
_json.put("order", order);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "jobRangeByType");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body().stream().map(o -> o instanceof Map ? new Job(new JsonObject((Map) o)) : new Job((JsonObject) o)).collect(Collectors.toList())));
}
});
return this;
}
public JobService jobRange(long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("from", from);
_json.put("to", to);
_json.put("order", order);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "jobRange");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body().stream().map(o -> o instanceof Map ? new Job(new JsonObject((Map) o)) : new Job((JsonObject) o)).collect(Collectors.toList())));
}
});
return this;
}
public JobService cardByType(String type, JobState state, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
_json.put("state", state == null ? null : state.toString());
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "cardByType");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService card(JobState state, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("state", state == null ? null : state.toString());
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "card");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService completeCount(String type, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "completeCount");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService failedCount(String type, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "failedCount");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService inactiveCount(String type, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "inactiveCount");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService activeCount(String type, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "activeCount");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService delayedCount(String type, Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("type", type);
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "delayedCount");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
public JobService getAllTypes(Handler<AsyncResult<List<String>>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "getAllTypes");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(convertList(res.result().body().getList())));
}
});
return this;
}
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
_json.put("state", state == null ? null : state.toString());
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "getIdsByState");
_vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(convertList(res.result().body().getList())));
}
});
return this;
}
public JobService getWorkTime(Handler<AsyncResult<Long>> handler) {
if (closed) {
handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
return this;
}
JsonObject _json = new JsonObject();
DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
_deliveryOptions.addHeader("action", "getWorkTime");
_vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> {
if (res.failed()) {
handler.handle(Future.failedFuture(res.cause()));
} else {
handler.handle(Future.succeededFuture(res.result().body()));
}
});
return this;
}
private List<Character> convertToListChar(JsonArray arr) {
List<Character> list = new ArrayList<>();
for (Object obj : arr) {
Integer jobj = (Integer) obj;
list.add((char) (int) jobj);
}
return list;
}
private Set<Character> convertToSetChar(JsonArray arr) {
Set<Character> set = new HashSet<>();
for (Object obj : arr) {
Integer jobj = (Integer) obj;
set.add((char) (int) jobj);
}
return set;
}
private <T> Map<String, T> convertMap(Map map) {
if (map.isEmpty()) {
return (Map<String, T>) map;
}
Object elem = map.values().stream().findFirst().get();
if (!(elem instanceof Map) && !(elem instanceof List)) {
return (Map<String, T>) map;
} else {
Function<Object, T> converter;
if (elem instanceof List) {
converter = object -> (T) new JsonArray((List) object);
} else {
converter = object -> (T) new JsonObject((Map) object);
}
return ((Map<String, T>) map).entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, converter::apply));
}
}
private <T> List<T> convertList(List list) {
if (list.isEmpty()) {
return (List<T>) list;
}
Object elem = list.get(0);
if (!(elem instanceof Map) && !(elem instanceof List)) {
return (List<T>) list;
} else {
Function<Object, T> converter;
if (elem instanceof List) {
converter = object -> (T) new JsonArray((List) object);
} else {
converter = object -> (T) new JsonObject((Map) object);
}
return (List<T>) list.stream().map(converter).collect(Collectors.toList());
}
}
private <T> Set<T> convertSet(List list) {
return new HashSet<T>(convertList(list));
}
} | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/generated/io/vertx/blueprint/kue/service/rxjava/JobService.java | kue-core/src/main/generated/io/vertx/blueprint/kue/service/rxjava/JobService.java | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.blueprint.kue.service.rxjava;
import java.util.Map;
import rx.Observable;
import rx.Single;
import io.vertx.rxjava.core.Vertx;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.core.json.JsonArray;
import java.util.List;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.core.json.JsonObject;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
/**
* Service interface for task operations.
*
* <p/>
* NOTE: This class has been automatically generated from the {@link io.vertx.blueprint.kue.service.JobService original} non RX-ified interface using Vert.x codegen.
*/
@io.vertx.lang.rxjava.RxGen(io.vertx.blueprint.kue.service.JobService.class)
public class JobService {
public static final io.vertx.lang.rxjava.TypeArg<JobService> __TYPE_ARG = new io.vertx.lang.rxjava.TypeArg<>(
obj -> new JobService((io.vertx.blueprint.kue.service.JobService) obj),
JobService::getDelegate
);
private final io.vertx.blueprint.kue.service.JobService delegate;
public JobService(io.vertx.blueprint.kue.service.JobService delegate) {
this.delegate = delegate;
}
public io.vertx.blueprint.kue.service.JobService getDelegate() {
return delegate;
}
/**
* Factory method for creating a {@link io.vertx.blueprint.kue.service.rxjava.JobService} instance.
*
* @param vertx Vertx instance
* @param config configuration
* @return the new {@link io.vertx.blueprint.kue.service.rxjava.JobService} instance
*/
public static JobService create(Vertx vertx, JsonObject config) {
JobService ret = JobService.newInstance(io.vertx.blueprint.kue.service.JobService.create(vertx.getDelegate(), config));
return ret;
}
/**
* Factory method for creating a {@link io.vertx.blueprint.kue.service.rxjava.JobService} service proxy.
* This is useful for doing RPCs.
*
* @param vertx Vertx instance
* @param address event bus address of RPC
* @return the new {@link io.vertx.blueprint.kue.service.rxjava.JobService} service proxy
*/
public static JobService createProxy(Vertx vertx, String address) {
JobService ret = JobService.newInstance(io.vertx.blueprint.kue.service.JobService.createProxy(vertx.getDelegate(), address));
return ret;
}
/**
* Get the certain from backend by id.
* @param id job id
* @param handler async result handler
* @return
*/
public JobService getJob(long id, Handler<AsyncResult<Job>> handler) {
delegate.getJob(id, handler);
return this;
}
/**
* Get the certain from backend by id.
* @param id job id
* @return
*/
public Single<Job> rxGetJob(long id) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
getJob(id, fut);
}));
}
/**
* Remove a job by id.
* @param id job id
* @param handler async result handler
* @return
*/
public JobService removeJob(long id, Handler<AsyncResult<Void>> handler) {
delegate.removeJob(id, handler);
return this;
}
/**
* Remove a job by id.
* @param id job id
* @return
*/
public Single<Void> rxRemoveJob(long id) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
removeJob(id, fut);
}));
}
/**
* Judge whether a job with certain id exists.
* @param id job id
* @param handler async result handler
* @return
*/
public JobService existsJob(long id, Handler<AsyncResult<Boolean>> handler) {
delegate.existsJob(id, handler);
return this;
}
/**
* Judge whether a job with certain id exists.
* @param id job id
* @return
*/
public Single<Boolean> rxExistsJob(long id) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
existsJob(id, fut);
}));
}
/**
* Get job log by id.
* @param id job id
* @param handler async result handler
* @return
*/
public JobService getJobLog(long id, Handler<AsyncResult<JsonArray>> handler) {
delegate.getJobLog(id, handler);
return this;
}
/**
* Get job log by id.
* @param id job id
* @return
*/
public Single<JsonArray> rxGetJobLog(long id) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
getJobLog(id, fut);
}));
}
/**
* Get a list of job in certain state in range (from, to) with order.
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
* @return
*/
public JobService jobRangeByState(String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
delegate.jobRangeByState(state, from, to, order, handler);
return this;
}
/**
* Get a list of job in certain state in range (from, to) with order.
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @return
*/
public Single<List<Job>> rxJobRangeByState(String state, long from, long to, String order) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
jobRangeByState(state, from, to, order, fut);
}));
}
/**
* Get a list of job in certain state and type in range (from, to) with order.
* @param type expected job type
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
* @return
*/
public JobService jobRangeByType(String type, String state, long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
delegate.jobRangeByType(type, state, from, to, order, handler);
return this;
}
/**
* Get a list of job in certain state and type in range (from, to) with order.
* @param type expected job type
* @param state expected job state
* @param from from
* @param to to
* @param order range order
* @return
*/
public Single<List<Job>> rxJobRangeByType(String type, String state, long from, long to, String order) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
jobRangeByType(type, state, from, to, order, fut);
}));
}
/**
* Get a list of job in range (from, to) with order.
* @param from from
* @param to to
* @param order range order
* @param handler async result handler
* @return
*/
public JobService jobRange(long from, long to, String order, Handler<AsyncResult<List<Job>>> handler) {
delegate.jobRange(from, to, order, handler);
return this;
}
/**
* Get a list of job in range (from, to) with order.
* @param from from
* @param to to
* @param order range order
* @return
*/
public Single<List<Job>> rxJobRange(long from, long to, String order) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
jobRange(from, to, order, fut);
}));
}
/**
* Get cardinality by job type and state.
* @param type job type
* @param state job state
* @param handler async result handler
* @return
*/
public JobService cardByType(String type, JobState state, Handler<AsyncResult<Long>> handler) {
delegate.cardByType(type, state, handler);
return this;
}
/**
* Get cardinality by job type and state.
* @param type job type
* @param state job state
* @return
*/
public Single<Long> rxCardByType(String type, JobState state) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
cardByType(type, state, fut);
}));
}
/**
* Get cardinality by job state.
* @param state job state
* @param handler async result handler
* @return
*/
public JobService card(JobState state, Handler<AsyncResult<Long>> handler) {
delegate.card(state, handler);
return this;
}
/**
* Get cardinality by job state.
* @param state job state
* @return
*/
public Single<Long> rxCard(JobState state) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
card(state, fut);
}));
}
/**
* Get cardinality of completed jobs.
* @param type job type; if null, then return global metrics
* @param handler async result handler
* @return
*/
public JobService completeCount(String type, Handler<AsyncResult<Long>> handler) {
delegate.completeCount(type, handler);
return this;
}
/**
* Get cardinality of completed jobs.
* @param type job type; if null, then return global metrics
* @return
*/
public Single<Long> rxCompleteCount(String type) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
completeCount(type, fut);
}));
}
/**
* Get cardinality of failed jobs.
* @param type job type; if null, then return global metrics
* @param handler
* @return
*/
public JobService failedCount(String type, Handler<AsyncResult<Long>> handler) {
delegate.failedCount(type, handler);
return this;
}
/**
* Get cardinality of failed jobs.
* @param type job type; if null, then return global metrics
* @return
*/
public Single<Long> rxFailedCount(String type) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
failedCount(type, fut);
}));
}
/**
* Get cardinality of inactive jobs.
* @param type job type; if null, then return global metrics
* @param handler
* @return
*/
public JobService inactiveCount(String type, Handler<AsyncResult<Long>> handler) {
delegate.inactiveCount(type, handler);
return this;
}
/**
* Get cardinality of inactive jobs.
* @param type job type; if null, then return global metrics
* @return
*/
public Single<Long> rxInactiveCount(String type) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
inactiveCount(type, fut);
}));
}
/**
* Get cardinality of active jobs.
* @param type job type; if null, then return global metrics
* @param handler
* @return
*/
public JobService activeCount(String type, Handler<AsyncResult<Long>> handler) {
delegate.activeCount(type, handler);
return this;
}
/**
* Get cardinality of active jobs.
* @param type job type; if null, then return global metrics
* @return
*/
public Single<Long> rxActiveCount(String type) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
activeCount(type, fut);
}));
}
/**
* Get cardinality of delayed jobs.
* @param type job type; if null, then return global metrics
* @param handler
* @return
*/
public JobService delayedCount(String type, Handler<AsyncResult<Long>> handler) {
delegate.delayedCount(type, handler);
return this;
}
/**
* Get cardinality of delayed jobs.
* @param type job type; if null, then return global metrics
* @return
*/
public Single<Long> rxDelayedCount(String type) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
delayedCount(type, fut);
}));
}
/**
* Get the job types present.
* @param handler async result handler
* @return
*/
public JobService getAllTypes(Handler<AsyncResult<List<String>>> handler) {
delegate.getAllTypes(handler);
return this;
}
/**
* Get the job types present.
* @return
*/
public Single<List<String>> rxGetAllTypes() {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
getAllTypes(fut);
}));
}
/**
* Return job ids with the given .
* @param state job state
* @param handler async result handler
* @return
*/
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) {
delegate.getIdsByState(state, handler);
return this;
}
/**
* Return job ids with the given .
* @param state job state
* @return
*/
public Single<List<Long>> rxGetIdsByState(JobState state) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
getIdsByState(state, fut);
}));
}
/**
* Get queue work time in milliseconds.
* @param handler async result handler
* @return
*/
public JobService getWorkTime(Handler<AsyncResult<Long>> handler) {
delegate.getWorkTime(handler);
return this;
}
/**
* Get queue work time in milliseconds.
* @return
*/
public Single<Long> rxGetWorkTime() {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
getWorkTime(fut);
}));
}
public static JobService newInstance(io.vertx.blueprint.kue.service.JobService arg) {
return arg != null ? new JobService(arg) : null;
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/generated/io/vertx/blueprint/kue/rxjava/CallbackKue.java | kue-core/src/main/generated/io/vertx/blueprint/kue/rxjava/CallbackKue.java | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.blueprint.kue.rxjava;
import java.util.Map;
import rx.Observable;
import rx.Single;
import io.vertx.blueprint.kue.service.rxjava.JobService;
import io.vertx.blueprint.kue.queue.JobState;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import java.util.List;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.core.json.JsonObject;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
/**
* A callback-based {@link io.vertx.blueprint.kue.rxjava.Kue} interface for Vert.x Codegen to support polyglot languages.
*
* <p/>
* NOTE: This class has been automatically generated from the {@link io.vertx.blueprint.kue.CallbackKue original} non RX-ified interface using Vert.x codegen.
*/
@io.vertx.lang.rxjava.RxGen(io.vertx.blueprint.kue.CallbackKue.class)
public class CallbackKue extends JobService {
public static final io.vertx.lang.rxjava.TypeArg<CallbackKue> __TYPE_ARG = new io.vertx.lang.rxjava.TypeArg<>(
obj -> new CallbackKue((io.vertx.blueprint.kue.CallbackKue) obj),
CallbackKue::getDelegate
);
private final io.vertx.blueprint.kue.CallbackKue delegate;
public CallbackKue(io.vertx.blueprint.kue.CallbackKue delegate) {
super(delegate);
this.delegate = delegate;
}
public io.vertx.blueprint.kue.CallbackKue getDelegate() {
return delegate;
}
public static CallbackKue createKue(Vertx vertx, JsonObject config) {
CallbackKue ret = CallbackKue.newInstance(io.vertx.blueprint.kue.CallbackKue.createKue(vertx.getDelegate(), config));
return ret;
}
public Job createJob(String type, JsonObject data) {
Job ret = delegate.createJob(type, data);
return ret;
}
public <R> CallbackKue on(String eventType, Handler<Message<R>> handler) {
delegate.on(eventType, new Handler<io.vertx.core.eventbus.Message<R>>() {
public void handle(io.vertx.core.eventbus.Message<R> event) {
handler.handle(Message.newInstance(event, io.vertx.lang.rxjava.TypeArg.unknown()));
}
});
return this;
}
public CallbackKue saveJob(Job job, Handler<AsyncResult<Job>> handler) {
delegate.saveJob(job, handler);
return this;
}
public Single<Job> rxSaveJob(Job job) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
saveJob(job, fut);
}));
}
public CallbackKue jobProgress(Job job, int complete, int total, Handler<AsyncResult<Job>> handler) {
delegate.jobProgress(job, complete, total, handler);
return this;
}
public Single<Job> rxJobProgress(Job job, int complete, int total) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
jobProgress(job, complete, total, fut);
}));
}
public CallbackKue jobDone(Job job) {
delegate.jobDone(job);
return this;
}
public CallbackKue jobDoneFail(Job job, Throwable ex) {
delegate.jobDoneFail(job, ex);
return this;
}
public CallbackKue process(String type, int n, Handler<Job> handler) {
delegate.process(type, n, handler);
return this;
}
public CallbackKue processBlocking(String type, int n, Handler<Job> handler) {
delegate.processBlocking(type, n, handler);
return this;
}
public static CallbackKue newInstance(io.vertx.blueprint.kue.CallbackKue arg) {
return arg != null ? new CallbackKue(arg) : null;
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-core/src/main/generated/io/vertx/blueprint/kue/queue/JobConverter.java | kue-core/src/main/generated/io/vertx/blueprint/kue/queue/JobConverter.java | /*
* Copyright 2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.vertx.blueprint.kue.queue;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;
/**
* Converter for {@link io.vertx.blueprint.kue.queue.Job}.
*
* NOTE: This class has been automatically generated from the {@link io.vertx.blueprint.kue.queue.Job} original class using Vert.x codegen.
*/
public class JobConverter {
public static void fromJson(JsonObject json, Job obj) {
if (json.getValue("attempts") instanceof Number) {
obj.setAttempts(((Number) json.getValue("attempts")).intValue());
}
if (json.getValue("backoff") instanceof JsonObject) {
obj.setBackoff(((JsonObject) json.getValue("backoff")).copy());
}
if (json.getValue("created_at") instanceof Number) {
obj.setCreated_at(((Number) json.getValue("created_at")).longValue());
}
if (json.getValue("data") instanceof JsonObject) {
obj.setData(((JsonObject) json.getValue("data")).copy());
}
if (json.getValue("delay") instanceof Number) {
obj.setDelay(((Number) json.getValue("delay")).longValue());
}
if (json.getValue("duration") instanceof Number) {
obj.setDuration(((Number) json.getValue("duration")).longValue());
}
if (json.getValue("failed_at") instanceof Number) {
obj.setFailed_at(((Number) json.getValue("failed_at")).longValue());
}
if (json.getValue("id") instanceof Number) {
obj.setId(((Number) json.getValue("id")).longValue());
}
if (json.getValue("max_attempts") instanceof Number) {
obj.setMax_attempts(((Number) json.getValue("max_attempts")).intValue());
}
if (json.getValue("priority") instanceof String) {
obj.setPriority(io.vertx.blueprint.kue.queue.Priority.valueOf((String) json.getValue("priority")));
}
if (json.getValue("progress") instanceof Number) {
obj.setProgress(((Number) json.getValue("progress")).intValue());
}
if (json.getValue("promote_at") instanceof Number) {
obj.setPromote_at(((Number) json.getValue("promote_at")).longValue());
}
if (json.getValue("removeOnComplete") instanceof Boolean) {
obj.setRemoveOnComplete((Boolean) json.getValue("removeOnComplete"));
}
if (json.getValue("result") instanceof JsonObject) {
obj.setResult(((JsonObject) json.getValue("result")).copy());
}
if (json.getValue("started_at") instanceof Number) {
obj.setStarted_at(((Number) json.getValue("started_at")).longValue());
}
if (json.getValue("state") instanceof String) {
obj.setState(io.vertx.blueprint.kue.queue.JobState.valueOf((String) json.getValue("state")));
}
if (json.getValue("ttl") instanceof Number) {
obj.setTtl(((Number) json.getValue("ttl")).intValue());
}
if (json.getValue("type") instanceof String) {
obj.setType((String) json.getValue("type"));
}
if (json.getValue("updated_at") instanceof Number) {
obj.setUpdated_at(((Number) json.getValue("updated_at")).longValue());
}
if (json.getValue("zid") instanceof String) {
obj.setZid((String) json.getValue("zid"));
}
}
public static void toJson(Job obj, JsonObject json) {
if (obj.getAddress_id() != null) {
json.put("address_id", obj.getAddress_id());
}
json.put("attempts", obj.getAttempts());
if (obj.getBackoff() != null) {
json.put("backoff", obj.getBackoff());
}
json.put("created_at", obj.getCreated_at());
if (obj.getData() != null) {
json.put("data", obj.getData());
}
json.put("delay", obj.getDelay());
json.put("duration", obj.getDuration());
json.put("failed_at", obj.getFailed_at());
json.put("id", obj.getId());
json.put("max_attempts", obj.getMax_attempts());
if (obj.getPriority() != null) {
json.put("priority", obj.getPriority().name());
}
json.put("progress", obj.getProgress());
json.put("promote_at", obj.getPromote_at());
json.put("removeOnComplete", obj.isRemoveOnComplete());
if (obj.getResult() != null) {
json.put("result", obj.getResult());
}
json.put("started_at", obj.getStarted_at());
if (obj.getState() != null) {
json.put("state", obj.getState().name());
}
json.put("ttl", obj.getTtl());
if (obj.getType() != null) {
json.put("type", obj.getType());
}
json.put("updated_at", obj.getUpdated_at());
if (obj.getZid() != null) {
json.put("zid", obj.getZid());
}
}
} | java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-example/src/main/java/io/vertx/blueprint/kue/example/ManyJobsProcessingVerticle.java | kue-example/src/main/java/io/vertx/blueprint/kue/example/ManyJobsProcessingVerticle.java | package io.vertx.blueprint.kue.example;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.Priority;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
/**
* Vert.x Blueprint - Job Queue
* Example - illustrates many jobs generating and processing
*
* @author Eric Zhao
*/
public class ManyJobsProcessingVerticle extends AbstractVerticle {
private Kue kue;
@Override
public void start() throws Exception {
// create our job queue
kue = Kue.createQueue(vertx, config());
create().setHandler(r0 -> {
if (r0.succeeded()) {
// process logic start (6 at a time)
kue.process("video conversion", 6, job -> {
int frames = job.getData().getInteger("frames", 100);
next(0, frames, job);
});
// process logic end
} else {
r0.cause().printStackTrace();
}
});
}
private Future<Job> create() {
JsonObject data = new JsonObject()
.put("title", "converting video to avi")
.put("user", 1)
.put("frames", 200);
// create an video conversion job
Job job = kue.createJob("video conversion", data)
.priority(Priority.NORMAL);
vertx.setTimer(2000, l -> create()); // may cause issue
return job.save();
}
// pretend we are doing some work
private void next(int i, int frames, Job job) {
vertx.setTimer(26, r -> {
job.progress(i, frames);
if (i == frames)
job.done();
else
next(i + 1, frames, job);
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-example/src/main/java/io/vertx/blueprint/kue/example/DelayedEmailVerticle.java | kue-example/src/main/java/io/vertx/blueprint/kue/example/DelayedEmailVerticle.java | package io.vertx.blueprint.kue.example;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.Priority;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
/**
* Vert.x Blueprint - Job Queue
* Example - A delayed email processing verticle
* This example shows the delayed jobs
*
* @author Eric Zhao
*/
public class DelayedEmailVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
// create our job queue
Kue kue = Kue.createQueue(vertx, config());
JsonObject data = new JsonObject()
.put("title", "Account renewal required")
.put("to", "qinxin@jianpo.xyz")
.put("template", "renewal-email");
// create a delayed email job
Job email = kue.createJob("email", data)
.setDelay(8888)
.priority(Priority.HIGH)
.onComplete(j -> System.out.println("renewal job completed"));
kue.createJob("email", new JsonObject().put("title", "Account expired")
.put("to", "qinxin@jianpo.xyz")
.put("template", "expired-email"))
.setDelay(26666)
.priority(Priority.HIGH)
.save() // save job
.compose(c -> email.save()) // save another job
.setHandler(sr -> {
if (sr.succeeded()) {
// process emails
kue.processBlocking("email", 10, job -> {
vertx.setTimer(2016, l -> job.done()); // cost 2s to process
});
} else {
sr.cause().printStackTrace();
}
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-example/src/main/java/io/vertx/blueprint/kue/example/LearningVertxVerticle.java | kue-example/src/main/java/io/vertx/blueprint/kue/example/LearningVertxVerticle.java | package io.vertx.blueprint.kue.example;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.Priority;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
/**
* Vert.x Blueprint - Job Queue
* Example - A learning Vert.x process verticle!
* This example shows the job events
*
* @author Eric Zhao
*/
public class LearningVertxVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
// create our job queue
Kue kue = Kue.createQueue(vertx, config());
// consume queue error
kue.on("error", message ->
System.out.println("[Global Error] " + message.body()));
JsonObject data = new JsonObject()
.put("title", "Learning Vert.x")
.put("content", "core");
// we are going to learn Vert.x, so create a job!
Job j = kue.createJob("learn vertx", data)
.priority(Priority.HIGH)
.onComplete(r -> { // on complete handler
System.out.println("Feeling: " + r.getResult().getString("feeling", "none"));
}).onFailure(r -> { // on failure handler
System.out.println("eee...so difficult...");
}).onProgress(r -> { // on progress modifying handler
System.out.println("I love this! My progress => " + r);
});
// save the job
j.save().setHandler(r0 -> {
if (r0.succeeded()) {
// start learning!
kue.processBlocking("learn vertx", 1, job -> {
job.progress(10, 100);
// aha...spend 3 seconds to learn!
vertx.setTimer(3000, r1 -> {
job.setResult(new JsonObject().put("feeling", "amazing and wonderful!")) // set a result to the job
.done(); // finish learning!
});
});
} else {
System.err.println("Wow, something happened: " + r0.cause().getMessage());
}
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
sczyh30/vertx-kue | https://github.com/sczyh30/vertx-kue/blob/12ef851446660a1258ab1e0101779b1e9213ab1e/kue-example/src/main/java/io/vertx/blueprint/kue/example/VideoProcessVerticle.java | kue-example/src/main/java/io/vertx/blueprint/kue/example/VideoProcessVerticle.java | package io.vertx.blueprint.kue.example;
import io.vertx.blueprint.kue.Kue;
import io.vertx.blueprint.kue.queue.Job;
import io.vertx.blueprint.kue.queue.Priority;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
/**
* Vert.x Blueprint - Job Queue
* Example - A video conversion process verticle
*
* @author Eric Zhao
*/
public class VideoProcessVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
// create our job queue
Kue kue = Kue.createQueue(vertx, config());
System.out.println("Creating job: video conversion");
JsonObject data = new JsonObject()
.put("title", "converting video to avi")
.put("user", 1)
.put("frames", 200);
// create an video conversion job
Job job0 = kue.createJob("video conversion", data)
.priority(Priority.NORMAL);
// save the job
job0.save().setHandler(r0 -> {
if (r0.succeeded()) {
// process logic start (3 at a time)
kue.process("video conversion", 3, job -> {
int frames = job.getData().getInteger("frames", 100);
next(0, frames, job);
});
// process logic end
} else {
r0.cause().printStackTrace();
}
});
}
// pretend we are doing some work
private void next(int i, int frames, Job job) {
vertx.setTimer(666, r -> {
job.progress(i, frames);
if (i == frames)
job.done();
else
next(i + 1, frames, job);
});
}
}
| java | Apache-2.0 | 12ef851446660a1258ab1e0101779b1e9213ab1e | 2026-01-05T02:38:17.784929Z | false |
SandroMachado/AndroidTampering | https://github.com/SandroMachado/AndroidTampering/blob/28214cf23291c3c1f3e76ff3d05fb110dc2848e1/app/src/main/java/com/sandro/androidtampering/AndroidTamperingProtection.java | app/src/main/java/com/sandro/androidtampering/AndroidTamperingProtection.java | package com.sandro.androidtampering;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
/**
* Android Tampering Protection have the objective to help the developers to add an extra protection layer to their android applications,
* validating the application signature and the installer.
*/
public class AndroidTamperingProtection {
private static final String PLAY_STORE_PACKAGE = "com.android.vending";
private final Context context;
private final Boolean playStoreOnly;
private final String certificateSignature;
private AndroidTamperingProtection(Builder builder) {
this.context = builder.context;
this.playStoreOnly = builder.playStoreOnly;
this.certificateSignature = builder.certificateSignature;
}
/**
* Validates the APK. This method should return true if the apk is not tampered.
*
* @return a boolean indicating if the APK is valid. It returns true if the APK is valid, not tampered.
*/
public Boolean validate() {
// Check the application installer.
if (this.playStoreOnly && !wasInstalledFromPlayStore(this.context)) {
return false;
}
return isAValidSignature(context, certificateSignature);
}
/**
* Checks if the apk signature is valid.
*
* @param context The context.
* @param certificateSignature The certificate signature.
*
* @return a boolean indicating if the signature is valid.
*/
private static boolean isAValidSignature(Context context, String certificateSignature) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
// The APK is signed with multiple signatures, probably it was tampered.
if (packageInfo.signatures.length > 1) {
return false;
}
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
if (certificateSignature.compareToIgnoreCase(Base64.encodeToString(md.digest(), Base64.DEFAULT)) == 0) {
return true;
}
}
} catch (Exception exception) {
Log.d("TAMPERING_PROTECTION", exception.getStackTrace().toString());
}
return false;
}
/**
* Verifies if the application was installed using the Google Play Store.
*
* @param context The application context.
*
* @return returns a boolean indicating if the application was installed using the Google Play Store.
*/
private static boolean wasInstalledFromPlayStore(final Context context) {
final String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());
return installer != null && installer.startsWith(PLAY_STORE_PACKAGE);
}
/**
* Android Tampering protection builder.
*/
public static class Builder {
private final Context context;
private Boolean playStoreOnly = false;
private final String certificateSignature;
/**
* Constructor.
*
* @param context The application context.
* @param certificateSignature The certificate signature.
*/
public Builder(Context context, String certificateSignature) {
this.context = context;
this.certificateSignature = certificateSignature;
}
/**
* Configures the library to check against installations from outside the Google Play Store. The default is false.
*
* @param installOnlyFromPlayStore A boolean indicating if is to validate the application installer.
*
* @return the builder.
*/
public Builder installOnlyFromPlayStore(Boolean installOnlyFromPlayStore) {
this.playStoreOnly = installOnlyFromPlayStore;
return this;
}
/**
* Builds the Android Tampering Protection.
*
* @return the Android Tampering Protection.
*/
public AndroidTamperingProtection build() {
AndroidTamperingProtection androidTamperingProtection = new AndroidTamperingProtection(this);
return androidTamperingProtection;
}
}
}
| java | MIT | 28214cf23291c3c1f3e76ff3d05fb110dc2848e1 | 2026-01-05T02:38:13.478776Z | false |
SandroMachado/AndroidTampering | https://github.com/SandroMachado/AndroidTampering/blob/28214cf23291c3c1f3e76ff3d05fb110dc2848e1/app/src/main/java/com/sandro/androidtampering/utils/AndroidTamperingProtectionUtils.java | app/src/main/java/com/sandro/androidtampering/utils/AndroidTamperingProtectionUtils.java | package com.sandro.androidtampering.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
/**
* A set of utils for the Android Tampering Protection library.
*/
public class AndroidTamperingProtectionUtils {
/**
* Prints your current certificate signature to the Logcat. Use this method to obtain your certificate signature.
*
* @param context The application context.
*/
public static void getCertificateSignature(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
// The APK is signed with multiple signatures, probably it was tampered.
if (packageInfo.signatures.length > 1) {
return ;
}
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("TAMPERING_PROTECTION", "**" + Base64.encodeToString(md.digest(), Base64.DEFAULT) + "**");
}
} catch (Exception exception) {
Log.d("TAMPERING_PROTECTION", exception.getStackTrace().toString());
}
}
}
| java | MIT | 28214cf23291c3c1f3e76ff3d05fb110dc2848e1 | 2026-01-05T02:38:13.478776Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/ControllerExceptionHandlerTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/ControllerExceptionHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.kafka.streams.errors.StreamsNotStartedException;
import org.apache.kafka.streams.errors.UnknownStateStoreException;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
class ControllerExceptionHandlerTest {
private final ControllerExceptionHandler controllerExceptionHandler = new ControllerExceptionHandler();
@Test
void shouldHandleUnknownStateStoreException() {
UnknownStateStoreException e = new UnknownStateStoreException("message");
ResponseEntity<String> response = controllerExceptionHandler.handleUnknownStateStoreException(e);
assertEquals("message", response.getBody());
assertEquals(404, response.getStatusCode().value());
}
@Test
void shouldHandleStreamsNotStartedException() {
StreamsNotStartedException e = new StreamsNotStartedException("message");
ResponseEntity<String> response = controllerExceptionHandler.handleStreamsNotStartedException(e);
assertEquals("message", response.getBody());
assertEquals(503, response.getStatusCode().value());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/InteractiveQueriesControllerTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/InteractiveQueriesControllerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.KeyValueStoreService;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.TimestampedKeyValueStoreService;
import com.michelin.kstreamplify.service.interactivequeries.window.TimestampedWindowStoreService;
import com.michelin.kstreamplify.service.interactivequeries.window.WindowStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.StreamsMetadata;
import org.apache.kafka.streams.state.HostInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class InteractiveQueriesControllerTest {
@Mock
private StreamsMetadata streamsMetadata;
@Mock
private KeyValueStoreService keyValueService;
@Mock
private TimestampedKeyValueStoreService timestampedKeyValueService;
@Mock
private WindowStoreService windowStoreService;
@Mock
private TimestampedWindowStoreService timestampedWindowStoreService;
@InjectMocks
private InteractiveQueriesController interactiveQueriesController;
@Test
void shouldGetStores() {
when(keyValueService.getStateStores()).thenReturn(Set.of("store1", "store2"));
assertEquals(
Set.of("store1", "store2"),
interactiveQueriesController.getStores().getBody());
}
@Test
void shouldGetStreamsMetadataForStore() {
when(streamsMetadata.stateStoreNames()).thenReturn(Set.of("store"));
when(streamsMetadata.hostInfo()).thenReturn(new HostInfo("host1", 1234));
when(streamsMetadata.topicPartitions()).thenReturn(Set.of(new TopicPartition("topic", 0)));
when(keyValueService.getStreamsMetadataForStore("store")).thenReturn(List.of(streamsMetadata));
List<com.michelin.kstreamplify.store.StreamsMetadata> response =
interactiveQueriesController.getStreamsMetadataForStore("store").getBody();
assertNotNull(response);
assertEquals(streamsMetadata.stateStoreNames(), response.get(0).getStateStoreNames());
assertEquals(
streamsMetadata.hostInfo().host(), response.get(0).getHostInfo().host());
assertEquals(
streamsMetadata.hostInfo().port(), response.get(0).getHostInfo().port());
assertTrue(response.get(0).getTopicPartitions().contains("topic-0"));
}
@Test
void shouldGetAllInKeyValueStore() {
when(keyValueService.getAll("store")).thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses =
interactiveQueriesController.getAllInKeyValueStore("store").getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInKeyValueStoreOnLocalHost() {
when(keyValueService.getAllOnLocalInstance("store"))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInKeyValueStoreOnLocalHost("store")
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInKeyValueStore() {
when(keyValueService.getByKey("store", "key")).thenReturn(new StateStoreRecord("key1", "value1", 1L));
StateStoreRecord response = interactiveQueriesController
.getByKeyInKeyValueStore("store", "key")
.getBody();
assertNotNull(response);
assertEquals("key1", response.getKey());
assertEquals("value1", response.getValue());
assertEquals(1L, response.getTimestamp());
}
@Test
void shouldGetAllInTimestampedKeyValueStore() {
when(timestampedKeyValueService.getAll("store"))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedKeyValueStore("store")
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInTimestampedKeyValueStoreOnLocalHost() {
when(timestampedKeyValueService.getAllOnLocalInstance("store"))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedKeyValueStoreOnLocalHost("store")
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInTimestampedKeyValueStore() {
when(timestampedKeyValueService.getByKey("store", "key"))
.thenReturn(new StateStoreRecord("key1", "value1", 1L));
StateStoreRecord response = interactiveQueriesController
.getByKeyInTimestampedKeyValueStore("store", "key")
.getBody();
assertNotNull(response);
assertEquals("key1", response.getKey());
assertEquals("value1", response.getValue());
assertEquals(1L, response.getTimestamp());
}
@Test
void shouldGetAllInWindowStore() {
when(windowStoreService.getAll(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInWindowStore("store", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInWindowStoreNoStartTimeNorEndTime() {
when(windowStoreService.getAll(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInWindowStore("store", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInWindowStoreOnLocalHost() {
when(windowStoreService.getAllOnLocalInstance(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInWindowStoreOnLocalHost(
"store", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInWindowStoreOnLocalHostNoStartTimeNorEndTime() {
when(windowStoreService.getAllOnLocalInstance(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInWindowStoreOnLocalHost("store", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInWindowStore() {
when(windowStoreService.getByKey(any(), any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getByKeyInWindowStore(
"store", "key", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInWindowStoreNoStartTimeNorEndTime() {
when(windowStoreService.getByKey(any(), any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getByKeyInWindowStore("store", "key", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInTimestampedWindowStore() {
when(timestampedWindowStoreService.getAll(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedWindowStore(
"store", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInTimestampedWindowStoreNoStartTimeNorEndTime() {
when(timestampedWindowStoreService.getAll(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedWindowStore("store", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInTimestampedWindowStoreOnLocalHost() {
when(timestampedWindowStoreService.getAllOnLocalInstance(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedWindowStoreOnLocalHost(
"store", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetAllInTimestampedWindowStoreOnLocalHostNoStartTimeNorEndTime() {
when(timestampedWindowStoreService.getAllOnLocalInstance(any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getAllInTimestampedWindowStoreOnLocalHost("store", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInTimestampedWindowStore() {
when(timestampedWindowStoreService.getByKey(any(), any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getByKeyInTimestampedWindowStore(
"store", "key", Optional.of("1970-01-01T00:00:00Z"), Optional.of("1970-01-01T00:00:00Z"))
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
@Test
void shouldGetByKeyInTimestampedWindowStoreNoStartTimeNorEndTime() {
when(timestampedWindowStoreService.getByKey(any(), any(), any(), any()))
.thenReturn(List.of(new StateStoreRecord("key1", "value1", 1L)));
List<StateStoreRecord> responses = interactiveQueriesController
.getByKeyInTimestampedWindowStore("store", "key", Optional.empty(), Optional.empty())
.getBody();
assertNotNull(responses);
assertEquals("key1", responses.get(0).getKey());
assertEquals("value1", responses.get(0).getValue());
assertEquals(1L, responses.get(0).getTimestamp());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/KubernetesControllerTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/KubernetesControllerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import com.michelin.kstreamplify.service.KubernetesService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ExtendWith(MockitoExtension.class)
class KubernetesControllerTest {
@Mock
private KubernetesService kubernetesService;
@InjectMocks
private KubernetesController kubernetesController;
@Test
void shouldGetReadinessProbe() {
when(kubernetesService.getReadiness()).thenReturn(200);
ResponseEntity<Void> response = kubernetesController.readiness();
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@Test
void shouldGetLivenessProbe() {
when(kubernetesService.getLiveness()).thenReturn(200);
ResponseEntity<Void> response = kubernetesController.liveness();
assertEquals(HttpStatus.OK, response.getStatusCode());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/TopologyControllerTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/controller/TopologyControllerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import com.michelin.kstreamplify.service.TopologyService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ExtendWith(MockitoExtension.class)
class TopologyControllerTest {
@Mock
private TopologyService topologyService;
@InjectMocks
private TopologyController topologyController;
@Test
void shouldGetTopology() {
when(topologyService.getTopology()).thenReturn("Topology");
ResponseEntity<String> response = topologyController.topology();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("Topology", response.getBody());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/WebServicesPathIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/WebServicesPathIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import com.michelin.kstreamplify.context.KafkaStreamsExecutionContext;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsMetadata;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@ActiveProfiles("web-services-path")
@SpringBootTest(webEnvironment = DEFINED_PORT)
class WebServicesPathIntegrationTest extends KafkaIntegrationTest {
@BeforeAll
static void globalSetUp() {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("INPUT_TOPIC", 2),
new TopicPartition("OUTPUT_TOPIC", 2));
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
}
@Test
void shouldInitAndRunWithWebServicesExposedOnCustomPaths() {
assertEquals(KafkaStreams.State.RUNNING, initializer.getKafkaStreams().state());
List<StreamsMetadata> streamsMetadata =
new ArrayList<>(initializer.getKafkaStreams().metadataForAllStreamsClients());
// Assert Kafka Streams initialization
assertEquals("localhost", streamsMetadata.get(0).hostInfo().host());
assertEquals(8001, streamsMetadata.get(0).hostInfo().port());
assertTrue(streamsMetadata.get(0).stateStoreNames().isEmpty());
Set<TopicPartition> topicPartitions = streamsMetadata.get(0).topicPartitions();
assertTrue(Set.of(new TopicPartition("INPUT_TOPIC", 0), new TopicPartition("INPUT_TOPIC", 1))
.containsAll(topicPartitions));
assertEquals("DLQ_TOPIC", KafkaStreamsExecutionContext.getDlqTopicName());
assertEquals(
"org.apache.kafka.common.serialization.Serdes$StringSerde",
KafkaStreamsExecutionContext.getSerdesConfig().get("default.key.serde"));
assertEquals(
"org.apache.kafka.common.serialization.Serdes$StringSerde",
KafkaStreamsExecutionContext.getSerdesConfig().get("default.value.serde"));
assertEquals(
"localhost:8001", KafkaStreamsExecutionContext.getProperties().get("application.server"));
// Assert HTTP probes
ResponseEntity<Void> responseReady =
restTemplate.getForEntity("http://localhost:8001/custom-readiness", Void.class);
assertEquals(200, responseReady.getStatusCode().value());
ResponseEntity<Void> responseLiveness =
restTemplate.getForEntity("http://localhost:8001/custom-liveness", Void.class);
assertEquals(200, responseLiveness.getStatusCode().value());
ResponseEntity<String> responseTopology =
restTemplate.getForEntity("http://localhost:8001/custom-topology", String.class);
assertEquals(200, responseTopology.getStatusCode().value());
assertEquals("""
Topologies:
Sub-topology: 0
Source: KSTREAM-SOURCE-0000000000 (topics: [INPUT_TOPIC])
--> KSTREAM-SINK-0000000001
Sink: KSTREAM-SINK-0000000001 (topic: OUTPUT_TOPIC)
<-- KSTREAM-SOURCE-0000000000
""", responseTopology.getBody());
}
/**
* Kafka Streams starter implementation for integration tests. The topology simply forwards messages from inputTopic
* to outputTopic.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(SpringBootKafkaStreamsInitializerIntegrationTest.KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("INPUT_TOPIC").to("OUTPUT_TOPIC");
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/SpringBootKafkaStreamsInitializerIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/SpringBootKafkaStreamsInitializerIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import com.michelin.kstreamplify.context.KafkaStreamsExecutionContext;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsMetadata;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@SpringBootTest(webEnvironment = DEFINED_PORT)
class SpringBootKafkaStreamsInitializerIntegrationTest extends KafkaIntegrationTest {
@Autowired
private MeterRegistry registry;
@BeforeAll
static void globalSetUp() {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("INPUT_TOPIC", 2),
new TopicPartition("OUTPUT_TOPIC", 2));
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
}
@Test
void shouldStartAndRun() {
assertEquals(KafkaStreams.State.RUNNING, initializer.getKafkaStreams().state());
List<StreamsMetadata> streamsMetadata =
new ArrayList<>(initializer.getKafkaStreams().metadataForAllStreamsClients());
// Assert Kafka Streams initialization
assertEquals("localhost", streamsMetadata.get(0).hostInfo().host());
assertEquals(8000, streamsMetadata.get(0).hostInfo().port());
assertTrue(streamsMetadata.get(0).stateStoreNames().isEmpty());
Set<TopicPartition> topicPartitions = streamsMetadata.get(0).topicPartitions();
assertTrue(Set.of(new TopicPartition("INPUT_TOPIC", 0), new TopicPartition("INPUT_TOPIC", 1))
.containsAll(topicPartitions));
assertEquals("DLQ_TOPIC", KafkaStreamsExecutionContext.getDlqTopicName());
assertEquals(
"org.apache.kafka.common.serialization.Serdes$StringSerde",
KafkaStreamsExecutionContext.getSerdesConfig().get("default.key.serde"));
assertEquals(
"org.apache.kafka.common.serialization.Serdes$StringSerde",
KafkaStreamsExecutionContext.getSerdesConfig().get("default.value.serde"));
assertEquals(
"localhost:8000", KafkaStreamsExecutionContext.getProperties().get("application.server"));
// Assert HTTP probes
ResponseEntity<Void> responseReady = restTemplate.getForEntity("http://localhost:8000/ready", Void.class);
assertEquals(200, responseReady.getStatusCode().value());
ResponseEntity<Void> responseLiveness = restTemplate.getForEntity("http://localhost:8000/liveness", Void.class);
assertEquals(200, responseLiveness.getStatusCode().value());
ResponseEntity<String> responseTopology =
restTemplate.getForEntity("http://localhost:8000/topology", String.class);
assertEquals(200, responseTopology.getStatusCode().value());
assertEquals("""
Topologies:
Sub-topology: 0
Source: KSTREAM-SOURCE-0000000000 (topics: [INPUT_TOPIC])
--> KSTREAM-SINK-0000000001
Sink: KSTREAM-SINK-0000000001 (topic: OUTPUT_TOPIC)
<-- KSTREAM-SOURCE-0000000000
""", responseTopology.getBody());
}
@Test
void shouldRegisterKafkaMetrics() {
// Kafka Streams metrics are registered
assertFalse(registry.getMeters().stream()
.filter(metric -> metric.getId().getName().startsWith("kafka.stream"))
.toList()
.isEmpty());
// Kafka producer metrics are registered
assertFalse(registry.getMeters().stream()
.filter(metric -> metric.getId().getName().startsWith("kafka.producer"))
.toList()
.isEmpty());
// Kafka consumer metrics are registered
assertFalse(registry.getMeters().stream()
.filter(metric -> metric.getId().getName().startsWith("kafka.consumer"))
.toList()
.isEmpty());
}
/**
* Kafka Streams starter implementation for integration tests. The topology simply forwards messages from inputTopic
* to outputTopic.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("INPUT_TOPIC").to("OUTPUT_TOPIC");
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
@Override
public void onStart(KafkaStreams kafkaStreams) {
log.info("Starting Kafka Streams from integration tests!");
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/container/KafkaIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/container/KafkaIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration.container;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import com.michelin.kstreamplify.initializer.KafkaStreamsInitializer;
import java.util.Arrays;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.LagInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.kafka.ConfluentKafkaContainer;
import org.testcontainers.utility.DockerImageName;
/** Base class for Kafka integration tests. */
@Slf4j
public abstract class KafkaIntegrationTest {
protected static final String CONFLUENT_PLATFORM_VERSION = "7.7.0";
protected static final Network NETWORK = Network.newNetwork();
@Autowired
protected KafkaStreamsInitializer initializer;
@Autowired
protected TestRestTemplate restTemplate;
@Container
protected static ConfluentKafkaContainer broker = new ConfluentKafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:" + CONFLUENT_PLATFORM_VERSION))
.withNetwork(NETWORK)
.withNetworkAliases("broker");
@Container
protected static GenericContainer<?> schemaRegistry = new GenericContainer<>(
DockerImageName.parse("confluentinc/cp-schema-registry:" + CONFLUENT_PLATFORM_VERSION))
.dependsOn(broker)
.withNetwork(NETWORK)
.withNetworkAliases("schema-registry")
.withExposedPorts(8081)
.withEnv("SCHEMA_REGISTRY_HOST_NAME", "schema-registry")
.withEnv("SCHEMA_REGISTRY_LISTENERS", "http://0.0.0.0:8081")
.withEnv("SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS", "broker:9093")
.waitingFor(Wait.forHttp("/subjects").forStatusCode(200));
@DynamicPropertySource
static void kafkaProperties(DynamicPropertyRegistry registry) {
registry.add("kafka.properties." + BOOTSTRAP_SERVERS_CONFIG, broker::getBootstrapServers);
registry.add(
"kafka.properties." + SCHEMA_REGISTRY_URL_CONFIG,
() -> "http://" + schemaRegistry.getHost() + ":" + schemaRegistry.getFirstMappedPort());
}
protected static void createTopics(String bootstrapServers, TopicPartition... topicPartitions) {
var newTopics = Arrays.stream(topicPartitions)
.map(topicPartition -> new NewTopic(topicPartition.topic(), topicPartition.partition(), (short) 1))
.toList();
try (var admin = AdminClient.create(Map.of(BOOTSTRAP_SERVERS_CONFIG, bootstrapServers))) {
admin.createTopics(newTopics);
}
}
protected void waitingForKafkaStreamsToStart() throws InterruptedException {
while (!initializer.getKafkaStreams().state().equals(KafkaStreams.State.RUNNING)) {
log.info("Waiting for Kafka Streams to start...");
Thread.sleep(2000); // NOSONAR
}
}
protected void waitingForLocalStoreToReachOffset(Map<String, Map<Integer, Long>> topicPartitionOffset)
throws InterruptedException {
while (hasLag(topicPartitionOffset)) {
log.info(
"Waiting for local stores {} to reach offsets",
topicPartitionOffset.keySet().stream().toList());
Thread.sleep(5000); // NOSONAR
}
}
private boolean hasLag(Map<String, Map<Integer, Long>> topicPartitionOffset) {
Map<String, Map<Integer, LagInfo>> currentLag =
initializer.getKafkaStreams().allLocalStorePartitionLags();
return !topicPartitionOffset.entrySet().stream()
.allMatch(topicPartitionOffsetEntry -> topicPartitionOffsetEntry.getValue().entrySet().stream()
.anyMatch(partitionOffsetEntry -> currentLag
.get(topicPartitionOffsetEntry.getKey())
.get(partitionOffsetEntry.getKey())
.currentOffsetPosition()
== partitionOffsetEntry.getValue()));
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/window/WindowIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/window/WindowIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration.interactivequeries.window;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import static org.springframework.http.HttpMethod.GET;
import com.michelin.kstreamplify.avro.KafkaUserStub;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import com.michelin.kstreamplify.serde.SerdesUtils;
import com.michelin.kstreamplify.service.interactivequeries.window.WindowStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import com.michelin.kstreamplify.store.StreamsMetadata;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.ProcessorSupplier;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@ActiveProfiles("interactive-queries-window")
@SpringBootTest(webEnvironment = DEFINED_PORT)
class WindowIntegrationTest extends KafkaIntegrationTest {
@Autowired
private WindowStoreService windowService;
@BeforeAll
static void globalSetUp() throws ExecutionException, InterruptedException {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("STRING_TOPIC", 3),
new TopicPartition("AVRO_TOPIC", 2));
try (KafkaProducer<String, String> stringKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName()))) {
ProducerRecord<String, String> message = new ProducerRecord<>("STRING_TOPIC", "user", "Doe");
stringKafkaProducer.send(message).get();
}
try (KafkaProducer<String, KafkaUserStub> avroKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
KafkaAvroSerializer.class.getName(),
SCHEMA_REGISTRY_URL_CONFIG,
"http://" + schemaRegistry.getHost() + ":" + schemaRegistry.getFirstMappedPort()))) {
KafkaUserStub kafkaUserStub = KafkaUserStub.newBuilder()
.setId(1L)
.setFirstName("John")
.setLastName("Doe")
.setBirthDate(Instant.parse("2000-01-01T01:00:00Z"))
.build();
ProducerRecord<String, KafkaUserStub> message = new ProducerRecord<>("AVRO_TOPIC", "user", kafkaUserStub);
avroKafkaProducer.send(message).get();
}
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
waitingForLocalStoreToReachOffset(Map.of(
"STRING_STRING_WINDOW_STORE", Map.of(2, 1L),
"STRING_AVRO_WINDOW_STORE", Map.of(0, 1L),
"STRING_AVRO_KV_STORE", Map.of(0, 1L)));
}
@Test
void shouldGetStoresAndStoreMetadata() {
// Get stores
ResponseEntity<List<String>> stores =
restTemplate.exchange("http://localhost:8004/store", GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, stores.getStatusCode().value());
assertNotNull(stores.getBody());
assertTrue(stores.getBody()
.containsAll(
List.of("STRING_STRING_WINDOW_STORE", "STRING_AVRO_WINDOW_STORE", "STRING_AVRO_KV_STORE")));
// Get hosts
ResponseEntity<List<StreamsMetadata>> streamsMetadata = restTemplate.exchange(
"http://localhost:8004/store/metadata/STRING_STRING_WINDOW_STORE",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, streamsMetadata.getStatusCode().value());
assertNotNull(streamsMetadata.getBody());
assertEquals(
Set.of("STRING_STRING_WINDOW_STORE", "STRING_AVRO_WINDOW_STORE", "STRING_AVRO_KV_STORE"),
streamsMetadata.getBody().get(0).getStateStoreNames());
assertEquals("localhost", streamsMetadata.getBody().get(0).getHostInfo().host());
assertEquals(8004, streamsMetadata.getBody().get(0).getHostInfo().port());
assertEquals(
Set.of("AVRO_TOPIC-0", "AVRO_TOPIC-1", "STRING_TOPIC-0", "STRING_TOPIC-1", "STRING_TOPIC-2"),
streamsMetadata.getBody().get(0).getTopicPartitions());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8004/store/window/WRONG_STORE/user,State store WRONG_STORE not found",
"http://localhost:8004/store/window/STRING_STRING_WINDOW_STORE/wrongKey,Key wrongKey not found",
"http://localhost:8004/store/window/WRONG_STORE,State store WRONG_STORE not found"
})
void shouldNotFoundWhenKeyOrStoreNotFound(String url, String message) {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals(message, response.getBody());
}
@Test
void shouldGetErrorWhenQueryingWrongStoreType() {
ResponseEntity<String> response =
restTemplate.getForEntity("http://localhost:8004/store/window/STRING_AVRO_KV_STORE/user", String.class);
assertEquals(400, response.getStatusCode().value());
assertNotNull(response.getBody());
}
@Test
void shouldGetByKeyInStringStringStore() {
ResponseEntity<List<StateStoreRecord>> response = restTemplate.exchange(
"http://localhost:8004/store/window/STRING_STRING_WINDOW_STORE/user",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStore() {
ResponseEntity<List<StateStoreRecord>> response = restTemplate.exchange(
"http://localhost:8004/store/window/STRING_AVRO_WINDOW_STORE/user",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z",
((HashMap<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8004/store/window/STRING_STRING_WINDOW_STORE/user",
"http://localhost:8004/store/window/STRING_AVRO_WINDOW_STORE/user"
})
void shouldNotFoundWhenStartTimeIsTooLate(String url) {
Instant tooLate = Instant.now().plus(Duration.ofDays(1));
ResponseEntity<String> response = restTemplate.getForEntity(url + "?startTime=" + tooLate, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals("Key user not found", response.getBody());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8004/store/window/STRING_STRING_WINDOW_STORE/user",
"http://localhost:8004/store/window/STRING_AVRO_WINDOW_STORE/user"
})
void shouldNotFoundWhenEndTimeIsTooEarly(String url) {
Instant tooEarly = Instant.now().minus(Duration.ofDays(1));
ResponseEntity<String> response = restTemplate.getForEntity(url + "?endTime=" + tooEarly, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals("Key user not found", response.getBody());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8004/store/window/STRING_STRING_WINDOW_STORE",
"http://localhost:8004/store/window/local/STRING_STRING_WINDOW_STORE"
})
void shouldGetAllInStringStringStore(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8004/store/window/STRING_AVRO_WINDOW_STORE",
"http://localhost:8004/store/window/local/STRING_AVRO_WINDOW_STORE"
})
void shouldGetAllFromStringAvroStores(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((Map<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStoreFromService() {
List<StateStoreRecord> stateStoreRecord =
windowService.getByKey("STRING_AVRO_WINDOW_STORE", "user", Instant.EPOCH, Instant.now());
assertEquals("user", stateStoreRecord.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("birthDate"));
assertNull(stateStoreRecord.get(0).getTimestamp());
}
@Test
void shouldGetAllInStringAvroStoreFromService() {
List<StateStoreRecord> stateQueryData =
windowService.getAll("STRING_AVRO_WINDOW_STORE", Instant.EPOCH, Instant.now());
assertEquals("user", stateQueryData.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateQueryData.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("birthDate"));
assertNull(stateQueryData.get(0).getTimestamp());
}
/**
* Kafka Streams starter implementation for integration tests. The topology consumes events from multiple topics and
* stores them in dedicated stores so that they can be queried.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("STRING_TOPIC", Consumed.with(Serdes.String(), Serdes.String()))
.process(new ProcessorSupplier<String, String, String, String>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<WindowStore<String, String>> stringStringWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_STRING_WINDOW_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
Serdes.String());
return Set.of(stringStringWindowStoreBuilder);
}
@Override
public Processor<String, String, String, String> get() {
return new Processor<>() {
private WindowStore<String, String> stringStringWindowStore;
@Override
public void init(ProcessorContext<String, String> context) {
this.stringStringWindowStore = context.getStateStore("STRING_STRING_WINDOW_STORE");
}
@Override
public void process(Record<String, String> message) {
stringStringWindowStore.put(message.key(), message.value(), message.timestamp());
}
};
}
});
streamsBuilder.stream(
"AVRO_TOPIC", Consumed.with(Serdes.String(), SerdesUtils.<KafkaUserStub>getValueSerdes()))
.process(new ProcessorSupplier<String, KafkaUserStub, String, KafkaUserStub>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<WindowStore<String, KafkaUserStub>> stringAvroWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_AVRO_WINDOW_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
SerdesUtils.getValueSerdes());
StoreBuilder<KeyValueStore<String, KafkaUserStub>> stringAvroKeyValueStoreBuilder =
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("STRING_AVRO_KV_STORE"),
Serdes.String(),
SerdesUtils.getValueSerdes());
return Set.of(stringAvroWindowStoreBuilder, stringAvroKeyValueStoreBuilder);
}
@Override
public Processor<String, KafkaUserStub, String, KafkaUserStub> get() {
return new Processor<>() {
private WindowStore<String, KafkaUserStub> stringAvroWindowStore;
private KeyValueStore<String, KafkaUserStub> stringAvroKeyValueStore;
@Override
public void init(ProcessorContext<String, KafkaUserStub> context) {
this.stringAvroWindowStore = context.getStateStore("STRING_AVRO_WINDOW_STORE");
this.stringAvroKeyValueStore = context.getStateStore("STRING_AVRO_KV_STORE");
}
@Override
public void process(Record<String, KafkaUserStub> message) {
stringAvroWindowStore.put(message.key(), message.value(), message.timestamp());
stringAvroKeyValueStore.put(message.key(), message.value());
}
};
}
});
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
@Override
public void onStart(KafkaStreams kafkaStreams) {
kafkaStreams.cleanUp();
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/window/TimestampedWindowIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/window/TimestampedWindowIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration.interactivequeries.window;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import static org.springframework.http.HttpMethod.GET;
import com.michelin.kstreamplify.avro.KafkaUserStub;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import com.michelin.kstreamplify.serde.SerdesUtils;
import com.michelin.kstreamplify.service.interactivequeries.window.WindowStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import com.michelin.kstreamplify.store.StreamsMetadata;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.ProcessorSupplier;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@ActiveProfiles("interactive-queries-timestamped-window")
@SpringBootTest(webEnvironment = DEFINED_PORT)
class TimestampedWindowIntegrationTest extends KafkaIntegrationTest {
@Autowired
private WindowStoreService windowService;
@BeforeAll
static void globalSetUp() throws ExecutionException, InterruptedException {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("STRING_TOPIC", 3),
new TopicPartition("AVRO_TOPIC", 2));
try (KafkaProducer<String, String> stringKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName()))) {
ProducerRecord<String, String> message = new ProducerRecord<>("STRING_TOPIC", "user", "Doe");
stringKafkaProducer.send(message).get();
}
try (KafkaProducer<String, KafkaUserStub> avroKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
KafkaAvroSerializer.class.getName(),
SCHEMA_REGISTRY_URL_CONFIG,
"http://" + schemaRegistry.getHost() + ":" + schemaRegistry.getFirstMappedPort()))) {
KafkaUserStub kafkaUserStub = KafkaUserStub.newBuilder()
.setId(1L)
.setFirstName("John")
.setLastName("Doe")
.setBirthDate(Instant.parse("2000-01-01T01:00:00Z"))
.build();
ProducerRecord<String, KafkaUserStub> message = new ProducerRecord<>("AVRO_TOPIC", "user", kafkaUserStub);
avroKafkaProducer.send(message).get();
}
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
waitingForLocalStoreToReachOffset(Map.of(
"STRING_STRING_TIMESTAMPED_STORE", Map.of(2, 1L),
"STRING_AVRO_TIMESTAMPED_STORE", Map.of(0, 1L),
"STRING_AVRO_KV_STORE", Map.of(0, 1L)));
}
@Test
void shouldGetStoresAndStoreMetadata() {
// Get stores
ResponseEntity<List<String>> stores =
restTemplate.exchange("http://localhost:8005/store", GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, stores.getStatusCode().value());
assertNotNull(stores.getBody());
assertTrue(stores.getBody()
.containsAll(List.of(
"STRING_STRING_TIMESTAMPED_STORE", "STRING_AVRO_TIMESTAMPED_STORE", "STRING_AVRO_KV_STORE")));
// Get hosts
ResponseEntity<List<StreamsMetadata>> streamsMetadata = restTemplate.exchange(
"http://localhost:8005/store/metadata/STRING_STRING_TIMESTAMPED_STORE",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, streamsMetadata.getStatusCode().value());
assertNotNull(streamsMetadata.getBody());
assertEquals(
Set.of("STRING_STRING_TIMESTAMPED_STORE", "STRING_AVRO_TIMESTAMPED_STORE", "STRING_AVRO_KV_STORE"),
streamsMetadata.getBody().get(0).getStateStoreNames());
assertEquals("localhost", streamsMetadata.getBody().get(0).getHostInfo().host());
assertEquals(8005, streamsMetadata.getBody().get(0).getHostInfo().port());
assertEquals(
Set.of("AVRO_TOPIC-0", "AVRO_TOPIC-1", "STRING_TOPIC-0", "STRING_TOPIC-1", "STRING_TOPIC-2"),
streamsMetadata.getBody().get(0).getTopicPartitions());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8005/store/window/WRONG_STORE/user,State store WRONG_STORE not found",
"http://localhost:8005/store/window/STRING_STRING_TIMESTAMPED_STORE/wrongKey,Key wrongKey not found",
"http://localhost:8005/store/window/WRONG_STORE,State store WRONG_STORE not found"
})
void shouldNotFoundWhenKeyOrStoreNotFound(String url, String message) {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals(message, response.getBody());
}
@Test
void shouldGetErrorWhenQueryingWrongStoreType() {
ResponseEntity<String> response =
restTemplate.getForEntity("http://localhost:8005/store/window/STRING_AVRO_KV_STORE/user", String.class);
assertEquals(400, response.getStatusCode().value());
assertNotNull(response.getBody());
}
@Test
void shouldGetByKeyInStringStringStore() {
ResponseEntity<List<StateStoreRecord>> response = restTemplate.exchange(
"http://localhost:8005/store/window/STRING_STRING_TIMESTAMPED_STORE/user",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStore() {
ResponseEntity<List<StateStoreRecord>> response = restTemplate.exchange(
"http://localhost:8005/store/window/STRING_AVRO_TIMESTAMPED_STORE/user",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((HashMap<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z",
((HashMap<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8005/store/window/STRING_STRING_TIMESTAMPED_STORE/user",
"http://localhost:8005/store/window/STRING_AVRO_TIMESTAMPED_STORE/user"
})
void shouldNotFoundWhenStartTimeIsTooLate(String url) {
Instant tooLate = Instant.now().plus(Duration.ofDays(1));
ResponseEntity<String> response = restTemplate.getForEntity(url + "?startTime=" + tooLate, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals("Key user not found", response.getBody());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8005/store/window/STRING_STRING_TIMESTAMPED_STORE/user",
"http://localhost:8005/store/window/STRING_AVRO_TIMESTAMPED_STORE/user"
})
void shouldNotFoundWhenEndTimeIsTooEarly(String url) {
Instant tooEarly = Instant.now().minus(Duration.ofDays(1));
ResponseEntity<String> response = restTemplate.getForEntity(url + "?endTime=" + tooEarly, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals("Key user not found", response.getBody());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8005/store/window/STRING_STRING_TIMESTAMPED_STORE",
"http://localhost:8005/store/window/local/STRING_STRING_TIMESTAMPED_STORE"
})
void shouldGetAllInStringStringStore(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8005/store/window/STRING_AVRO_TIMESTAMPED_STORE",
"http://localhost:8005/store/window/local/STRING_AVRO_TIMESTAMPED_STORE"
})
void shouldGetAllFromStringAvroStores(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((Map<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStoreFromService() {
List<StateStoreRecord> stateStoreRecord =
windowService.getByKey("STRING_AVRO_TIMESTAMPED_STORE", "user", Instant.EPOCH, Instant.now());
assertEquals("user", stateStoreRecord.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) stateStoreRecord.get(0).getValue()).get("birthDate"));
assertNull(stateStoreRecord.get(0).getTimestamp());
}
@Test
void shouldGetAllInStringAvroStoreFromService() {
List<StateStoreRecord> stateQueryData =
windowService.getAll("STRING_AVRO_TIMESTAMPED_STORE", Instant.EPOCH, Instant.now());
assertEquals("user", stateQueryData.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateQueryData.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("birthDate"));
assertNull(stateQueryData.get(0).getTimestamp());
}
/**
* Kafka Streams starter implementation for integration tests. The topology consumes events from multiple topics and
* stores them in dedicated stores so that they can be queried.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("STRING_TOPIC", Consumed.with(Serdes.String(), Serdes.String()))
.process(new ProcessorSupplier<String, String, String, String>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<WindowStore<String, String>> stringStringWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_STRING_TIMESTAMPED_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
Serdes.String());
return Set.of(stringStringWindowStoreBuilder);
}
@Override
public Processor<String, String, String, String> get() {
return new Processor<>() {
private WindowStore<String, String> stringStringWindowStore;
@Override
public void init(ProcessorContext<String, String> context) {
this.stringStringWindowStore =
context.getStateStore("STRING_STRING_TIMESTAMPED_STORE");
}
@Override
public void process(Record<String, String> message) {
stringStringWindowStore.put(message.key(), message.value(), message.timestamp());
}
};
}
});
streamsBuilder.stream(
"AVRO_TOPIC", Consumed.with(Serdes.String(), SerdesUtils.<KafkaUserStub>getValueSerdes()))
.process(new ProcessorSupplier<String, KafkaUserStub, String, KafkaUserStub>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<WindowStore<String, KafkaUserStub>> stringAvroWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_AVRO_TIMESTAMPED_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
SerdesUtils.getValueSerdes());
StoreBuilder<KeyValueStore<String, KafkaUserStub>> stringAvroKeyValueStoreBuilder =
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("STRING_AVRO_KV_STORE"),
Serdes.String(),
SerdesUtils.getValueSerdes());
return Set.of(stringAvroWindowStoreBuilder, stringAvroKeyValueStoreBuilder);
}
@Override
public Processor<String, KafkaUserStub, String, KafkaUserStub> get() {
return new Processor<>() {
private WindowStore<String, KafkaUserStub> stringAvroWindowStore;
private KeyValueStore<String, KafkaUserStub> stringAvroKeyValueStore;
@Override
public void init(ProcessorContext<String, KafkaUserStub> context) {
this.stringAvroWindowStore = context.getStateStore("STRING_AVRO_TIMESTAMPED_STORE");
this.stringAvroKeyValueStore = context.getStateStore("STRING_AVRO_KV_STORE");
}
@Override
public void process(Record<String, KafkaUserStub> message) {
stringAvroWindowStore.put(message.key(), message.value(), message.timestamp());
stringAvroKeyValueStore.put(message.key(), message.value());
}
};
}
});
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
@Override
public void onStart(KafkaStreams kafkaStreams) {
kafkaStreams.cleanUp();
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/keyvalue/TimestampedKeyValueIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/keyvalue/TimestampedKeyValueIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration.interactivequeries.keyvalue;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import static org.springframework.http.HttpMethod.GET;
import com.michelin.kstreamplify.avro.KafkaUserStub;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import com.michelin.kstreamplify.serde.SerdesUtils;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.TimestampedKeyValueStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import com.michelin.kstreamplify.store.StreamsMetadata;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.ProcessorSupplier;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.TimestampedKeyValueStore;
import org.apache.kafka.streams.state.ValueAndTimestamp;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@ActiveProfiles("interactive-queries-timestamped-key-value")
@SpringBootTest(webEnvironment = DEFINED_PORT)
class TimestampedKeyValueIntegrationTest extends KafkaIntegrationTest {
@Autowired
private TimestampedKeyValueStoreService timestampedKeyValueService;
@BeforeAll
static void globalSetUp() throws ExecutionException, InterruptedException {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("STRING_TOPIC", 3),
new TopicPartition("AVRO_TOPIC", 2));
try (KafkaProducer<String, String> stringKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName()))) {
ProducerRecord<String, String> message = new ProducerRecord<>("STRING_TOPIC", "user", "Doe");
stringKafkaProducer.send(message).get();
}
try (KafkaProducer<String, KafkaUserStub> avroKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
KafkaAvroSerializer.class.getName(),
SCHEMA_REGISTRY_URL_CONFIG,
"http://" + schemaRegistry.getHost() + ":" + schemaRegistry.getFirstMappedPort()))) {
KafkaUserStub kafkaUserStub = KafkaUserStub.newBuilder()
.setId(1L)
.setFirstName("John")
.setLastName("Doe")
.setBirthDate(Instant.parse("2000-01-01T01:00:00Z"))
.build();
ProducerRecord<String, KafkaUserStub> message = new ProducerRecord<>("AVRO_TOPIC", "user", kafkaUserStub);
avroKafkaProducer.send(message).get();
}
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
waitingForLocalStoreToReachOffset(Map.of(
"STRING_STRING_TIMESTAMPED_STORE", Map.of(2, 1L),
"STRING_AVRO_TIMESTAMPED_STORE", Map.of(0, 1L),
"STRING_AVRO_WINDOW_STORE", Map.of(0, 1L)));
}
@Test
void shouldGetStoresAndStoreMetadata() {
// Get stores
ResponseEntity<List<String>> stores =
restTemplate.exchange("http://localhost:8003/store", GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, stores.getStatusCode().value());
assertNotNull(stores.getBody());
assertTrue(stores.getBody()
.containsAll(List.of(
"STRING_STRING_TIMESTAMPED_STORE",
"STRING_AVRO_TIMESTAMPED_STORE",
"STRING_AVRO_WINDOW_STORE")));
// Get hosts
ResponseEntity<List<StreamsMetadata>> streamsMetadata = restTemplate.exchange(
"http://localhost:8003/store/metadata/STRING_STRING_TIMESTAMPED_STORE",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, streamsMetadata.getStatusCode().value());
assertNotNull(streamsMetadata.getBody());
assertEquals(
Set.of("STRING_STRING_TIMESTAMPED_STORE", "STRING_AVRO_TIMESTAMPED_STORE", "STRING_AVRO_WINDOW_STORE"),
streamsMetadata.getBody().get(0).getStateStoreNames());
assertEquals("localhost", streamsMetadata.getBody().get(0).getHostInfo().host());
assertEquals(8003, streamsMetadata.getBody().get(0).getHostInfo().port());
assertEquals(
Set.of("AVRO_TOPIC-0", "AVRO_TOPIC-1", "STRING_TOPIC-0", "STRING_TOPIC-1", "STRING_TOPIC-2"),
streamsMetadata.getBody().get(0).getTopicPartitions());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8003/store/key-value/timestamped/WRONG_STORE/user,State store WRONG_STORE not found",
"http://localhost:8003/store/key-value/timestamped/STRING_STRING_TIMESTAMPED_STORE/wrongKey,Key wrongKey not found",
"http://localhost:8003/store/key-value/timestamped/WRONG_STORE,State store WRONG_STORE not found"
})
void shouldNotFoundWhenKeyOrStoreNotFound(String url, String message) {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals(message, response.getBody());
}
@Test
void shouldGetErrorWhenQueryingWrongStoreType() {
ResponseEntity<String> response = restTemplate.getForEntity(
"http://localhost:8003/store/key-value/timestamped/STRING_AVRO_WINDOW_STORE/user", String.class);
assertEquals(400, response.getStatusCode().value());
assertNotNull(response.getBody());
}
@Test
void shouldGetByKeyInStringStringStore() {
ResponseEntity<StateStoreRecord> response = restTemplate.getForEntity(
"http://localhost:8003/store/key-value/timestamped/STRING_STRING_TIMESTAMPED_STORE/user",
StateStoreRecord.class);
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().getKey());
assertEquals("Doe", response.getBody().getValue());
assertNotNull(response.getBody().getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStore() {
ResponseEntity<StateStoreRecord> response = restTemplate.getForEntity(
"http://localhost:8003/store/key-value/timestamped/STRING_AVRO_TIMESTAMPED_STORE/user",
StateStoreRecord.class);
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().getKey());
assertEquals(1, ((HashMap<?, ?>) response.getBody().getValue()).get("id"));
assertEquals("John", ((HashMap<?, ?>) response.getBody().getValue()).get("firstName"));
assertEquals("Doe", ((HashMap<?, ?>) response.getBody().getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((HashMap<?, ?>) response.getBody().getValue()).get("birthDate"));
assertNotNull(response.getBody().getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8003/store/key-value/timestamped/STRING_STRING_TIMESTAMPED_STORE",
"http://localhost:8003/store/key-value/timestamped/local/STRING_STRING_TIMESTAMPED_STORE"
})
void shouldGetAllInStringStringStore(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNotNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8003/store/key-value/timestamped/STRING_AVRO_TIMESTAMPED_STORE",
"http://localhost:8003/store/key-value/timestamped/local/STRING_AVRO_TIMESTAMPED_STORE"
})
void shouldGetAllFromStringAvroStores(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((Map<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNotNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStoreFromService() {
StateStoreRecord stateStoreRecord =
timestampedKeyValueService.getByKey("STRING_AVRO_TIMESTAMPED_STORE", "user");
assertEquals("user", stateStoreRecord.getKey());
assertEquals(1L, ((Map<?, ?>) stateStoreRecord.getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateStoreRecord.getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateStoreRecord.getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateStoreRecord.getValue()).get("birthDate"));
assertNotNull(stateStoreRecord.getTimestamp());
}
@Test
void shouldGetAllInStringAvroStoreFromService() {
List<StateStoreRecord> stateQueryData = timestampedKeyValueService.getAll("STRING_AVRO_TIMESTAMPED_STORE");
assertEquals("user", stateQueryData.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateQueryData.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("birthDate"));
assertNotNull(stateQueryData.get(0).getTimestamp());
}
/**
* Kafka Streams starter implementation for integration tests. The topology consumes events from multiple topics and
* stores them in dedicated stores so that they can be queried.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("STRING_TOPIC", Consumed.with(Serdes.String(), Serdes.String()))
.process(new ProcessorSupplier<String, String, String, String>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<TimestampedKeyValueStore<String, String>> stringStringKeyValueStoreBuilder =
Stores.timestampedKeyValueStoreBuilder(
Stores.persistentTimestampedKeyValueStore(
"STRING_STRING_TIMESTAMPED_STORE"),
Serdes.String(),
Serdes.String());
return Set.of(stringStringKeyValueStoreBuilder);
}
@Override
public Processor<String, String, String, String> get() {
return new Processor<>() {
private TimestampedKeyValueStore<String, String> stringStringKeyValueStore;
@Override
public void init(ProcessorContext<String, String> context) {
this.stringStringKeyValueStore =
context.getStateStore("STRING_STRING_TIMESTAMPED_STORE");
}
@Override
public void process(Record<String, String> message) {
stringStringKeyValueStore.put(
message.key(),
ValueAndTimestamp.make(message.value(), message.timestamp()));
}
};
}
});
streamsBuilder.stream(
"AVRO_TOPIC", Consumed.with(Serdes.String(), SerdesUtils.<KafkaUserStub>getValueSerdes()))
.process(new ProcessorSupplier<String, KafkaUserStub, String, KafkaUserStub>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<TimestampedKeyValueStore<String, KafkaUserStub>>
stringAvroKeyValueStoreBuilder = Stores.timestampedKeyValueStoreBuilder(
Stores.persistentTimestampedKeyValueStore("STRING_AVRO_TIMESTAMPED_STORE"),
Serdes.String(),
SerdesUtils.getValueSerdes());
StoreBuilder<WindowStore<String, KafkaUserStub>> stringAvroWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_AVRO_WINDOW_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
SerdesUtils.getValueSerdes());
return Set.of(stringAvroKeyValueStoreBuilder, stringAvroWindowStoreBuilder);
}
@Override
public Processor<String, KafkaUserStub, String, KafkaUserStub> get() {
return new Processor<>() {
private TimestampedKeyValueStore<String, KafkaUserStub> stringAvroKeyValueStore;
private WindowStore<String, KafkaUserStub> stringAvroWindowStore;
@Override
public void init(ProcessorContext<String, KafkaUserStub> context) {
this.stringAvroKeyValueStore =
context.getStateStore("STRING_AVRO_TIMESTAMPED_STORE");
this.stringAvroWindowStore = context.getStateStore("STRING_AVRO_WINDOW_STORE");
}
@Override
public void process(Record<String, KafkaUserStub> message) {
stringAvroKeyValueStore.put(
message.key(),
ValueAndTimestamp.make(message.value(), message.timestamp()));
stringAvroWindowStore.put(message.key(), message.value(), message.timestamp());
}
};
}
});
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
@Override
public void onStart(KafkaStreams kafkaStreams) {
kafkaStreams.cleanUp();
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/keyvalue/KeyValueIntegrationTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/integration/interactivequeries/keyvalue/KeyValueIntegrationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.integration.interactivequeries.keyvalue;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.streams.StreamsConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT;
import static org.springframework.http.HttpMethod.GET;
import com.michelin.kstreamplify.avro.KafkaUserStub;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.integration.container.KafkaIntegrationTest;
import com.michelin.kstreamplify.serde.SerdesUtils;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.KeyValueStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import com.michelin.kstreamplify.store.StreamsMetadata;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.processor.api.Processor;
import org.apache.kafka.streams.processor.api.ProcessorContext;
import org.apache.kafka.streams.processor.api.ProcessorSupplier;
import org.apache.kafka.streams.processor.api.Record;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.streams.state.WindowStore;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.testcontainers.junit.jupiter.Testcontainers;
@Slf4j
@Testcontainers
@ActiveProfiles("interactive-queries-key-value")
@SpringBootTest(webEnvironment = DEFINED_PORT)
class KeyValueIntegrationTest extends KafkaIntegrationTest {
@Autowired
private KeyValueStoreService keyValueService;
@BeforeAll
static void globalSetUp() throws ExecutionException, InterruptedException {
createTopics(
broker.getBootstrapServers(),
new TopicPartition("STRING_TOPIC", 3),
new TopicPartition("AVRO_TOPIC", 2));
try (KafkaProducer<String, String> stringKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName()))) {
ProducerRecord<String, String> message = new ProducerRecord<>("STRING_TOPIC", "user", "Doe");
stringKafkaProducer.send(message).get();
}
try (KafkaProducer<String, KafkaUserStub> avroKafkaProducer = new KafkaProducer<>(Map.of(
BOOTSTRAP_SERVERS_CONFIG,
broker.getBootstrapServers(),
KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class.getName(),
VALUE_SERIALIZER_CLASS_CONFIG,
KafkaAvroSerializer.class.getName(),
SCHEMA_REGISTRY_URL_CONFIG,
"http://" + schemaRegistry.getHost() + ":" + schemaRegistry.getFirstMappedPort()))) {
KafkaUserStub kafkaUserStub = KafkaUserStub.newBuilder()
.setId(1L)
.setFirstName("John")
.setLastName("Doe")
.setBirthDate(Instant.parse("2000-01-01T01:00:00Z"))
.build();
ProducerRecord<String, KafkaUserStub> message = new ProducerRecord<>("AVRO_TOPIC", "user", kafkaUserStub);
avroKafkaProducer.send(message).get();
}
}
@BeforeEach
void setUp() throws InterruptedException {
waitingForKafkaStreamsToStart();
waitingForLocalStoreToReachOffset(Map.of(
"STRING_STRING_KV_STORE", Map.of(2, 1L),
"STRING_AVRO_KV_STORE", Map.of(0, 1L),
"STRING_AVRO_WINDOW_STORE", Map.of(0, 1L)));
}
@Test
void shouldGetStoresAndStoreMetadata() {
// Get stores
ResponseEntity<List<String>> stores =
restTemplate.exchange("http://localhost:8002/store", GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, stores.getStatusCode().value());
assertNotNull(stores.getBody());
assertTrue(stores.getBody()
.containsAll(List.of("STRING_STRING_KV_STORE", "STRING_AVRO_KV_STORE", "STRING_AVRO_WINDOW_STORE")));
// Get hosts
ResponseEntity<List<StreamsMetadata>> streamsMetadata = restTemplate.exchange(
"http://localhost:8002/store/metadata/STRING_STRING_KV_STORE",
GET,
null,
new ParameterizedTypeReference<>() {});
assertEquals(200, streamsMetadata.getStatusCode().value());
assertNotNull(streamsMetadata.getBody());
assertEquals(
Set.of("STRING_STRING_KV_STORE", "STRING_AVRO_KV_STORE", "STRING_AVRO_WINDOW_STORE"),
streamsMetadata.getBody().get(0).getStateStoreNames());
assertEquals("localhost", streamsMetadata.getBody().get(0).getHostInfo().host());
assertEquals(8002, streamsMetadata.getBody().get(0).getHostInfo().port());
assertEquals(
Set.of("AVRO_TOPIC-0", "AVRO_TOPIC-1", "STRING_TOPIC-0", "STRING_TOPIC-1", "STRING_TOPIC-2"),
streamsMetadata.getBody().get(0).getTopicPartitions());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8002/store/key-value/WRONG_STORE/user,State store WRONG_STORE not found",
"http://localhost:8002/store/key-value/STRING_STRING_KV_STORE/wrongKey,Key wrongKey not found",
"http://localhost:8002/store/key-value/WRONG_STORE,State store WRONG_STORE not found"
})
void shouldNotFoundWhenKeyOrStoreNotFound(String url, String message) {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertEquals(404, response.getStatusCode().value());
assertEquals(message, response.getBody());
}
@Test
void shouldGetErrorWhenQueryingWrongStoreType() {
ResponseEntity<String> response = restTemplate.getForEntity(
"http://localhost:8002/store/key-value/STRING_AVRO_WINDOW_STORE/user", String.class);
assertEquals(400, response.getStatusCode().value());
assertNotNull(response.getBody());
}
@Test
void shouldGetByKeyInStringStringStore() {
ResponseEntity<StateStoreRecord> response = restTemplate.getForEntity(
"http://localhost:8002/store/key-value/STRING_STRING_KV_STORE/user", StateStoreRecord.class);
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().getKey());
assertEquals("Doe", response.getBody().getValue());
assertNull(response.getBody().getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStore() {
ResponseEntity<StateStoreRecord> response = restTemplate.getForEntity(
"http://localhost:8002/store/key-value/STRING_AVRO_KV_STORE/user", StateStoreRecord.class);
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().getKey());
assertEquals(1, ((HashMap<?, ?>) response.getBody().getValue()).get("id"));
assertEquals("John", ((HashMap<?, ?>) response.getBody().getValue()).get("firstName"));
assertEquals("Doe", ((HashMap<?, ?>) response.getBody().getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((HashMap<?, ?>) response.getBody().getValue()).get("birthDate"));
assertNull(response.getBody().getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8002/store/key-value/STRING_STRING_KV_STORE",
"http://localhost:8002/store/key-value/local/STRING_STRING_KV_STORE"
})
void shouldGetAllInStringStringStore(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals("Doe", response.getBody().get(0).getValue());
assertNull(response.getBody().get(0).getTimestamp());
}
@ParameterizedTest
@CsvSource({
"http://localhost:8002/store/key-value/STRING_AVRO_KV_STORE",
"http://localhost:8002/store/key-value/local/STRING_AVRO_KV_STORE"
})
void shouldGetAllFromStringAvroStores(String url) {
ResponseEntity<List<StateStoreRecord>> response =
restTemplate.exchange(url, GET, null, new ParameterizedTypeReference<>() {});
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
assertEquals("user", response.getBody().get(0).getKey());
assertEquals(1, ((Map<?, ?>) response.getBody().get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) response.getBody().get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) response.getBody().get(0).getValue()).get("lastName"));
assertEquals(
"2000-01-01T01:00:00Z", ((Map<?, ?>) response.getBody().get(0).getValue()).get("birthDate"));
assertNull(response.getBody().get(0).getTimestamp());
}
@Test
void shouldGetByKeyInStringAvroStoreFromService() {
StateStoreRecord stateStoreRecord = keyValueService.getByKey("STRING_AVRO_KV_STORE", "user");
assertEquals("user", stateStoreRecord.getKey());
assertEquals(1L, ((Map<?, ?>) stateStoreRecord.getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateStoreRecord.getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateStoreRecord.getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateStoreRecord.getValue()).get("birthDate"));
assertNull(stateStoreRecord.getTimestamp());
}
@Test
void shouldGetAllInStringAvroStoreFromService() {
List<StateStoreRecord> stateQueryData = keyValueService.getAll("STRING_AVRO_KV_STORE");
assertEquals("user", stateQueryData.get(0).getKey());
assertEquals(1L, ((Map<?, ?>) stateQueryData.get(0).getValue()).get("id"));
assertEquals("John", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("firstName"));
assertEquals("Doe", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("lastName"));
assertEquals("2000-01-01T01:00:00Z", ((Map<?, ?>) stateQueryData.get(0).getValue()).get("birthDate"));
assertNull(stateQueryData.get(0).getTimestamp());
}
/**
* Kafka Streams starter implementation for integration tests. The topology consumes events from multiple topics and
* stores them in dedicated stores so that they can be queried.
*/
@Slf4j
@SpringBootApplication
static class KafkaStreamsStarterStub extends KafkaStreamsStarter {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamsStarterStub.class, args);
}
@Override
public void topology(StreamsBuilder streamsBuilder) {
streamsBuilder.stream("STRING_TOPIC", Consumed.with(Serdes.String(), Serdes.String()))
.process(new ProcessorSupplier<String, String, String, String>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<KeyValueStore<String, String>> stringStringKeyValueStoreBuilder =
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("STRING_STRING_KV_STORE"),
Serdes.String(),
Serdes.String());
return Set.of(stringStringKeyValueStoreBuilder);
}
@Override
public Processor<String, String, String, String> get() {
return new Processor<>() {
private KeyValueStore<String, String> stringStringKeyValueStore;
@Override
public void init(ProcessorContext<String, String> context) {
this.stringStringKeyValueStore = context.getStateStore("STRING_STRING_KV_STORE");
}
@Override
public void process(Record<String, String> message) {
stringStringKeyValueStore.put(message.key(), message.value());
}
};
}
});
streamsBuilder.stream(
"AVRO_TOPIC", Consumed.with(Serdes.String(), SerdesUtils.<KafkaUserStub>getValueSerdes()))
.process(new ProcessorSupplier<String, KafkaUserStub, String, KafkaUserStub>() {
@Override
public Set<StoreBuilder<?>> stores() {
StoreBuilder<KeyValueStore<String, KafkaUserStub>> stringAvroKeyValueStoreBuilder =
Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("STRING_AVRO_KV_STORE"),
Serdes.String(),
SerdesUtils.getValueSerdes());
StoreBuilder<WindowStore<String, KafkaUserStub>> stringAvroWindowStoreBuilder =
Stores.windowStoreBuilder(
Stores.persistentWindowStore(
"STRING_AVRO_WINDOW_STORE",
Duration.ofMinutes(5),
Duration.ofMinutes(1),
false),
Serdes.String(),
SerdesUtils.getValueSerdes());
return Set.of(stringAvroKeyValueStoreBuilder, stringAvroWindowStoreBuilder);
}
@Override
public Processor<String, KafkaUserStub, String, KafkaUserStub> get() {
return new Processor<>() {
private KeyValueStore<String, KafkaUserStub> stringAvroKeyValueStore;
private WindowStore<String, KafkaUserStub> stringAvroWindowStore;
@Override
public void init(ProcessorContext<String, KafkaUserStub> context) {
this.stringAvroKeyValueStore = context.getStateStore("STRING_AVRO_KV_STORE");
this.stringAvroWindowStore = context.getStateStore("STRING_AVRO_WINDOW_STORE");
}
@Override
public void process(Record<String, KafkaUserStub> message) {
stringAvroKeyValueStore.put(message.key(), message.value());
stringAvroWindowStore.put(message.key(), message.value(), message.timestamp());
}
};
}
});
}
@Override
public String dlqTopic() {
return "DLQ_TOPIC";
}
@Override
public void onStart(KafkaStreams kafkaStreams) {
kafkaStreams.cleanUp();
}
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/initializer/SpringBootKafkaStreamsInitializerTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/initializer/SpringBootKafkaStreamsInitializerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.initializer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.michelin.kstreamplify.context.KafkaStreamsExecutionContext;
import com.michelin.kstreamplify.property.KafkaProperties;
import java.util.Properties;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ConfigurableApplicationContext;
@ExtendWith(MockitoExtension.class)
class SpringBootKafkaStreamsInitializerTest {
@Mock
private ConfigurableApplicationContext applicationContext;
@Mock
private KafkaStreamsStarter kafkaStreamsStarter;
@Mock
private KafkaProperties kafkaProperties;
@InjectMocks
private SpringBootKafkaStreamsInitializer initializer;
@Test
void shouldStartProperties() {
Properties properties = new Properties();
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "appId");
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
properties.put("prefix.self", "abc.");
when(kafkaProperties.asProperties()).thenReturn(properties);
initializer.initProperties();
assertEquals(kafkaStreamsStarter, initializer.getKafkaStreamsStarter());
assertNotNull(initializer.getKafkaProperties());
assertEquals("abc.", KafkaStreamsExecutionContext.getPrefix());
assertEquals(
"abc.appId", KafkaStreamsExecutionContext.getProperties().get(StreamsConfig.APPLICATION_ID_CONFIG));
}
@Test
void shouldCloseSpringBootContextOnUncaughtException() {
Properties properties = new Properties();
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "appId");
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
properties.put("prefix.self", "abc.");
when(kafkaProperties.asProperties()).thenReturn(properties);
initializer.initProperties();
StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse response =
initializer.onStreamsUncaughtException(new RuntimeException("Unexpected test exception"));
assertEquals(StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT, response);
verify(applicationContext).close();
}
@Test
void shouldCloseSpringBootContextOnChangeState() {
initializer.onStateChange(KafkaStreams.State.ERROR, KafkaStreams.State.RUNNING);
verify(applicationContext).close();
}
@Test
void shouldNotCloseSpringBootContextOnChangeStateNotError() {
initializer.onStateChange(KafkaStreams.State.REBALANCING, KafkaStreams.State.RUNNING);
verify(applicationContext, never()).close();
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/opentelemetry/OpenTelemetryConfigTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/opentelemetry/OpenTelemetryConfigTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.opentelemetry;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
/** The OpenTelemetry configuration test class. */
@ExtendWith(MockitoExtension.class)
class OpenTelemetryConfigTest {
@Test
void shouldNotAddTagsToMetricsWhenNull() {
OpenTelemetryConfig openTelemetryConfig = new OpenTelemetryConfig(null);
MeterRegistryCustomizer<MeterRegistry> customizer = openTelemetryConfig.addTagsOnMetrics();
MeterRegistry meterRegistry = new OpenTelemetryMeterRegistry();
customizer.customize(meterRegistry);
meterRegistry.counter("fakeCounterMetric");
assertEquals(
"fakeCounterMetric", meterRegistry.getMeters().get(0).getId().getName());
assertTrue(meterRegistry.getMeters().get(0).getId().getTags().isEmpty());
}
@Test
void shouldNotAddTagsToMetricsWhenEmpty() {
OpenTelemetryConfig openTelemetryConfig = new OpenTelemetryConfig(EMPTY);
MeterRegistryCustomizer<MeterRegistry> customizer = openTelemetryConfig.addTagsOnMetrics();
MeterRegistry meterRegistry = new OpenTelemetryMeterRegistry();
customizer.customize(meterRegistry);
meterRegistry.counter("fakeCounterMetric");
assertEquals(
"fakeCounterMetric", meterRegistry.getMeters().get(0).getId().getName());
assertTrue(meterRegistry.getMeters().get(0).getId().getTags().isEmpty());
}
@Test
void shouldAddTagsToMetricsWhenOpenTelemetryRegistry() {
OpenTelemetryConfig openTelemetryConfig = new OpenTelemetryConfig("tagName=tagValue,tagName2=tagValue2");
MeterRegistryCustomizer<MeterRegistry> customizer = openTelemetryConfig.addTagsOnMetrics();
MeterRegistry meterRegistry = new OpenTelemetryMeterRegistry();
customizer.customize(meterRegistry);
meterRegistry.counter("fakeCounterMetric");
assertEquals(
"fakeCounterMetric", meterRegistry.getMeters().get(0).getId().getName());
assertEquals(
Tag.of("tagName", "tagValue"),
meterRegistry.getMeters().get(0).getId().getTags().get(0));
assertEquals(
Tag.of("tagName2", "tagValue2"),
meterRegistry.getMeters().get(0).getId().getTags().get(1));
}
@Test
void shouldNotAddTagsToMetricsWhenNotOpenTelemetryRegistry() {
OpenTelemetryConfig openTelemetryConfig = new OpenTelemetryConfig("tagName=tagValue,tagName2=tagValue2");
MeterRegistryCustomizer<MeterRegistry> customizer = openTelemetryConfig.addTagsOnMetrics();
MeterRegistry meterRegistry = new SimpleMeterRegistry();
customizer.customize(meterRegistry);
meterRegistry.counter("fakeCounterMetric");
assertEquals(
"fakeCounterMetric", meterRegistry.getMeters().get(0).getId().getName());
assertTrue(meterRegistry.getMeters().get(0).getId().getTags().isEmpty());
}
static class OpenTelemetryMeterRegistry extends SimpleMeterRegistry {
// Empty class to mock OpenTelemetryMeterRegistry
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/property/KafkaPropertiesTest.java | kstreamplify-spring-boot/src/test/java/com/michelin/kstreamplify/property/KafkaPropertiesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.property;
import static org.apache.kafka.streams.StreamsConfig.APPLICATION_ID_CONFIG;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Map;
import org.junit.jupiter.api.Test;
class KafkaPropertiesTest {
private final KafkaProperties kafkaProperties = new KafkaProperties();
@Test
void shouldLoadProperties() {
Map<String, String> props = Map.of(APPLICATION_ID_CONFIG, "appId");
kafkaProperties.setProperties(props);
assertTrue(kafkaProperties.getProperties().containsKey(APPLICATION_ID_CONFIG));
assertTrue(kafkaProperties.getProperties().containsValue("appId"));
assertTrue(kafkaProperties.asProperties().containsKey(APPLICATION_ID_CONFIG));
assertTrue(kafkaProperties.asProperties().containsValue("appId"));
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/TopologyController.java | kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/TopologyController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.service.TopologyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/** Kafka Streams controller for topology. */
@RestController
@ConditionalOnBean(KafkaStreamsStarter.class)
@Tag(name = "Topology", description = "Topology Controller")
public class TopologyController {
private final TopologyService topologyService;
/**
* Constructor.
*
* @param topologyService The topology service
*/
public TopologyController(TopologyService topologyService) {
this.topologyService = topologyService;
}
/**
* Get the Kafka Streams topology.
*
* @return The Kafka Streams topology
*/
@Operation(summary = "Get the Kafka Streams topology")
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
@GetMapping("/${topology.path:topology}")
public ResponseEntity<String> topology() {
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(topologyService.getTopology());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/InteractiveQueriesController.java | kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/InteractiveQueriesController.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import com.michelin.kstreamplify.initializer.KafkaStreamsStarter;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.KeyValueStoreService;
import com.michelin.kstreamplify.service.interactivequeries.keyvalue.TimestampedKeyValueStoreService;
import com.michelin.kstreamplify.service.interactivequeries.window.TimestampedWindowStoreService;
import com.michelin.kstreamplify.service.interactivequeries.window.WindowStoreService;
import com.michelin.kstreamplify.store.StateStoreRecord;
import com.michelin.kstreamplify.store.StreamsMetadata;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** Kafka Streams controller for store. */
@RestController
@RequestMapping("/store")
@ConditionalOnBean(KafkaStreamsStarter.class)
@Tag(name = "Interactive Queries", description = "Interactive Queries Controller")
public class InteractiveQueriesController {
private final KeyValueStoreService keyValueService;
private final TimestampedKeyValueStoreService timestampedKeyValueService;
private final WindowStoreService windowStoreService;
private final TimestampedWindowStoreService timestampedWindowStoreService;
/**
* Constructor.
*
* @param keyValueService The key-value store service
* @param timestampedKeyValueService The timestamped key-value store service
* @param windowStoreService The window store service
* @param timestampedWindowStoreService The timestamped window store service
*/
public InteractiveQueriesController(
KeyValueStoreService keyValueService,
TimestampedKeyValueStoreService timestampedKeyValueService,
WindowStoreService windowStoreService,
TimestampedWindowStoreService timestampedWindowStoreService) {
this.keyValueService = keyValueService;
this.timestampedKeyValueService = timestampedKeyValueService;
this.windowStoreService = windowStoreService;
this.timestampedWindowStoreService = timestampedWindowStoreService;
}
/**
* Get the stores.
*
* @return The stores
*/
@Operation(summary = "Get the state stores.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = Set.class))
}),
})
@GetMapping
public ResponseEntity<Set<String>> getStores() {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(keyValueService.getStateStores());
}
/**
* Get the hosts of the store.
*
* @param store The store
* @return The hosts
*/
@Operation(summary = "Get the streams metadata for a store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = StreamsMetadata.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/metadata/{store}")
public ResponseEntity<List<StreamsMetadata>> getStreamsMetadataForStore(@PathVariable("store") final String store) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(keyValueService.getStreamsMetadataForStore(store).stream()
.map(streamsMetadata -> new StreamsMetadata(
streamsMetadata.stateStoreNames(),
streamsMetadata.hostInfo(),
streamsMetadata.topicPartitions()))
.toList());
}
/**
* Get all records from the key-value store.
*
* @param store The store
* @return The values
*/
@Operation(summary = "Get all records from a key-value store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/key-value/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInKeyValueStore(@PathVariable("store") String store) {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(keyValueService.getAll(store));
}
/**
* Get all records from the key-value store on the local instance.
*
* @param store The store
* @return The values
*/
@Operation(summary = "Get all records from a key-value store on the local instance.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/key-value/local/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInKeyValueStoreOnLocalHost(
@PathVariable("store") String store) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(keyValueService.getAllOnLocalInstance(store));
}
/**
* Get the record by key from the key-value store.
*
* @param store The store
* @param key The key
* @return The value
*/
@Operation(summary = "Get a record by key from a key-value store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = StateStoreRecord.class))
}),
@ApiResponse(
responseCode = "404",
description = "Key not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping("/key-value/{store}/{key}")
public ResponseEntity<StateStoreRecord> getByKeyInKeyValueStore(
@PathVariable("store") String store, @PathVariable("key") String key) {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(keyValueService.getByKey(store, key));
}
/**
* Get all records from the timestamped key-value store.
*
* @param store The store
* @return The values
*/
@Operation(summary = "Get all records from a timestamped key-value store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/key-value/timestamped/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInTimestampedKeyValueStore(
@PathVariable("store") String store) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(timestampedKeyValueService.getAll(store));
}
/**
* Get all records from the timestamped key-value store on the local instance.
*
* @param store The store
* @return The values
*/
@Operation(summary = "Get all records from a timestamped key-value store on the local instance.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/key-value/timestamped/local/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInTimestampedKeyValueStoreOnLocalHost(
@PathVariable("store") String store) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(timestampedKeyValueService.getAllOnLocalInstance(store));
}
/**
* Get the record by key from the timestamped key-value store.
*
* @param store The store
* @param key The key
* @return The value
*/
@Operation(summary = "Get a record by key from a timestamped key-value store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = StateStoreRecord.class))
}),
@ApiResponse(
responseCode = "404",
description = "Key not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping("/key-value/timestamped/{store}/{key}")
public ResponseEntity<StateStoreRecord> getByKeyInTimestampedKeyValueStore(
@PathVariable("store") String store, @PathVariable("key") String key) {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(timestampedKeyValueService.getByKey(store, key));
}
/**
* Get all records from the window store.
*
* @param store The store
* @param startTime The start time
* @param endTime The end time
* @return The values
*/
@Operation(summary = "Get all records from a window store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/window/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInWindowStore(
@PathVariable("store") String store,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(windowStoreService.getAll(store, instantFrom, instantTo));
}
/**
* Get all records from the window store on the local instance.
*
* @param store The store
* @param startTime The start time
* @param endTime The end time
* @return The values
*/
@Operation(summary = "Get all records from a window store on the local instance.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/window/local/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInWindowStoreOnLocalHost(
@PathVariable("store") String store,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(windowStoreService.getAllOnLocalInstance(store, instantFrom, instantTo));
}
/**
* Get the record by key from the window store.
*
* @param store The store
* @param key The key
* @param startTime The start time
* @param endTime The end time
* @return The value
*/
@Operation(summary = "Get a record by key from a window store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = StateStoreRecord.class))
}),
@ApiResponse(
responseCode = "404",
description = "Key not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping("/window/{store}/{key}")
public ResponseEntity<List<StateStoreRecord>> getByKeyInWindowStore(
@PathVariable("store") String store,
@PathVariable("key") String key,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(windowStoreService.getByKey(store, key, instantFrom, instantTo));
}
/**
* Get all records from the timestamped window store.
*
* @param store The store
* @param startTime The start time
* @param endTime The end time
* @return The values
*/
@Operation(summary = "Get all records from a timestamped window store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/window/timestamped/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInTimestampedWindowStore(
@PathVariable("store") String store,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(timestampedWindowStoreService.getAll(store, instantFrom, instantTo));
}
/**
* Get all records from the timestamped window store on the local instance.
*
* @param store The store
* @param startTime The start time
* @param endTime The end time
* @return The values
*/
@Operation(summary = "Get all records from a timestamped window store on the local instance.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = List.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping(value = "/window/timestamped/local/{store}")
public ResponseEntity<List<StateStoreRecord>> getAllInTimestampedWindowStoreOnLocalHost(
@PathVariable("store") String store,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(timestampedWindowStoreService.getAllOnLocalInstance(store, instantFrom, instantTo));
}
/**
* Get the record by key from the timestamped window store.
*
* @param store The store
* @param key The key
* @param startTime The start time
* @param endTime The end time
* @return The value
*/
@Operation(summary = "Get a record by key from a timestamped window store.")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "OK",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = StateStoreRecord.class))
}),
@ApiResponse(
responseCode = "404",
description = "Key not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "404",
description = "Store not found",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
@ApiResponse(
responseCode = "503",
description = "Kafka Streams not running",
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
schema = @Schema(implementation = String.class))
}),
})
@GetMapping("/window/timestamped/{store}/{key}")
public ResponseEntity<List<StateStoreRecord>> getByKeyInTimestampedWindowStore(
@PathVariable("store") String store,
@PathVariable("key") String key,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("startTime") Optional<String> startTime,
@Parameter(description = "1970-01-01T01:01:01Z") @RequestParam("endTime") Optional<String> endTime) {
Instant instantFrom = startTime.map(Instant::parse).orElse(Instant.EPOCH);
Instant instantTo = endTime.map(Instant::parse).orElse(Instant.now());
return ResponseEntity.ok()
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | true |
michelin/kstreamplify | https://github.com/michelin/kstreamplify/blob/7b912c3bc711629f1745ae4a60bffeaed649d07a/kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/ControllerExceptionHandler.java | kstreamplify-spring-boot/src/main/java/com/michelin/kstreamplify/controller/ControllerExceptionHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.michelin.kstreamplify.controller;
import com.michelin.kstreamplify.exception.UnknownKeyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.errors.StreamsNotStartedException;
import org.apache.kafka.streams.errors.UnknownStateStoreException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/** Controller exception handler. */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler {
/** Constructor. */
public ControllerExceptionHandler() {
// Default constructor
}
/**
* Handle the unknown state store exception.
*
* @param e The exception
* @return The response entity
*/
@ExceptionHandler(UnknownStateStoreException.class)
public ResponseEntity<String> handleUnknownStateStoreException(UnknownStateStoreException e) {
log.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
/**
* Handle the stream not started exception.
*
* @param e The exception
* @return The response entity
*/
@ExceptionHandler(StreamsNotStartedException.class)
public ResponseEntity<String> handleStreamsNotStartedException(StreamsNotStartedException e) {
log.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(e.getMessage());
}
/**
* Handle the unknown key exception.
*
* @param e The exception
* @return The response entity
*/
@ExceptionHandler(UnknownKeyException.class)
public ResponseEntity<String> handleUnknownKeyException(UnknownKeyException e) {
log.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
/**
* Handle the illegal argument exception.
*
* @param e The exception
* @return The response entity
*/
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
log.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
| java | Apache-2.0 | 7b912c3bc711629f1745ae4a60bffeaed649d07a | 2026-01-05T02:38:06.284501Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.