Skip to content

Instantly share code, notes, and snippets.

@huntc
Created May 3, 2011 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huntc/954260 to your computer and use it in GitHub Desktop.
Save huntc/954260 to your computer and use it in GitHub Desktop.
test-gemfire-project
.classpath
.project
.settings
target
BACKUP*
DRLK*
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gfe="http://www.springframework.org/schema/gemfire"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/gemfire http://www.springframework.org/schema/gemfire/spring-gemfire-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<gfe:cache />
<!-- Don't know how to configure this region with no-ack. -->
<!-- <gfe:replicated-region id="Product"> </gfe:replicated-region> -->
<gfe:partitioned-region id="Customer"
persistent="false" copies="1" />
<gfe:partitioned-region id="BillingDetails"
persistent="false" copies="1" colocated-with="Customer">
<gfe:partition-resolver ref="customerPartitionResolver" />
</gfe:partitioned-region>
<gfe:partitioned-region id="CustomerProduct"
persistent="false" copies="1" colocated-with="Customer">
<gfe:partition-resolver ref="customerPartitionResolver" />
</gfe:partitioned-region>
<bean id="customerPartitionResolver" class="gemfire.training.CustomerPartitionResolver" />
<bean id="commandProcessor" class="gemfire.training.CommandProcessor">
<property name="region" ref="Customer" />
</bean>
</beans>
package gemfire.training;
public class BillingDetails implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CustomerId: ").append(getCustomerId()).append(", ");
sb.append("StatusCode: ").append(getStatusCode());
return sb.toString();
}
private String customerId;
private String statusCode;
private String billingDetailsId;
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getStatusCode() {
return this.statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getBillingDetailsId() {
return this.billingDetailsId;
}
public void setBillingDetailsId(String id) {
this.billingDetailsId = id;
}
}
package gemfire.training;
import java.io.Serializable;
public class BillingDetailsKey implements Serializable {
private static final long serialVersionUID = 1L;
final String customerId;
final String billingDetailsKey;
public BillingDetailsKey(String customerId, String billingDetailsKey) {
super();
this.customerId = customerId;
this.billingDetailsKey = billingDetailsKey;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BillingDetailsKey other = (BillingDetailsKey) obj;
if (billingDetailsKey == null) {
if (other.billingDetailsKey != null)
return false;
} else if (!billingDetailsKey.equals(other.billingDetailsKey))
return false;
return true;
}
public String getBillingDetailsKey() {
return billingDetailsKey;
}
public String getCustomerId() {
return customerId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((billingDetailsKey == null) ? 0 : billingDetailsKey
.hashCode());
return result;
}
@Override
public String toString() {
return "BillingDetailsKey [customerId=" + customerId
+ ", billingDetailsKey=" + billingDetailsKey + "]";
}
}
package gemfire.training;
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import com.gemstone.gemfire.cache.query.FunctionDomainException;
import com.gemstone.gemfire.cache.query.NameResolutionException;
import com.gemstone.gemfire.cache.query.QueryInvocationTargetException;
import com.gemstone.gemfire.cache.query.TypeMismatchException;
/**
* Entity processing and interpreting shell commands.
*
* @author Costin Leau
*/
public class CommandProcessor {
private class Task implements Runnable {
@Override
public void run() {
System.out.println("Hello World!");
System.out.println("Want to interact with the world ? ...");
System.out.println(help);
System.out.print("-> ");
System.out.flush();
FunctionService.registerFunction(new JSExecutor());
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
try {
while (threadActive) {
if (br.ready()) {
try {
System.out.println(process(br.readLine()));
} catch (Exception ex) {
System.out.println("Error executing last command "
+ ex.getMessage());
ex.printStackTrace();
}
System.out.print("-> ");
System.out.flush();
}
}
} catch (IOException ioe) {
// just ignore any exceptions
log.error("Caught exception while processing commands ", ioe);
}
}
}
private static final Pattern COM = Pattern
.compile("query|exit|help|size|clear|keys|values|map|containsKey|containsValue|get|remove|put|js");
private static final Log log = LogFactory.getLog(CommandProcessor.class);
private static String help = initHelp();
private static String EMPTY = "";
private static String initHelp() {
return "Figure it out";
}
boolean threadActive;
private Thread thread;
Region<String, Customer> region;
void awaitCommands() throws Exception {
thread.join();
}
public Region<String, Customer> getRegion() {
return region;
}
String process(final String line) throws FunctionDomainException,
TypeMismatchException, NameResolutionException,
QueryInvocationTargetException {
final Scanner sc = new Scanner(line);
if (!sc.hasNext(COM)) {
return "Invalid command - type 'help' for supported operations";
}
String command = sc.next();
String arg1 = (sc.hasNext() ? sc.next() : null);
String arg2 = (sc.hasNext() ? sc.next() : null);
// query shortcut
if ("query".equalsIgnoreCase(command)) {
String query = line.trim().substring(command.length());
return region.query(query).toString();
}
// parse commands w/o arguments
if ("exit".equalsIgnoreCase(command)) {
threadActive = false;
return "Node exiting...";
}
if ("help".equalsIgnoreCase(command)) {
return help;
}
if ("size".equalsIgnoreCase(command)) {
return EMPTY + region.size();
}
if ("clear".equalsIgnoreCase(command)) {
region.clear();
return "Clearing grid..";
}
if ("keys".equalsIgnoreCase(command)) {
return region.keySet().toString();
}
if ("values".equalsIgnoreCase(command)) {
return region.values().toString();
}
if ("map".equalsIgnoreCase(command)) {
Set<Entry<String, Customer>> entrySet = region.entrySet();
if (entrySet.size() == 0)
return "[]";
StringBuilder sb = new StringBuilder();
for (Entry<String, Customer> entry : entrySet) {
sb.append("[");
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
sb.append("] ");
}
return sb.toString();
}
// commands w/ 1 arg
if ("containsKey".equalsIgnoreCase(command)) {
return EMPTY + region.containsKey(arg1);
}
if ("containsValue".equalsIgnoreCase(command)) {
return EMPTY + region.containsValue(arg1);
}
if ("get".equalsIgnoreCase(command)) {
return region.get(arg1).toString();
}
if ("remove".equalsIgnoreCase(command)) {
return region.remove(arg1).toString();
}
if ("js".equalsIgnoreCase(command)) {
StringBuilder script = new StringBuilder(arg1);
script.append(" ");
script.append(arg2);
while (sc.hasNext()) {
script.append(" ");
script.append(sc.next());
}
ResultCollector<?, ?> resultCollector = FunctionService
.onRegion(region).withArgs(script.toString())
.execute("gemfire.training.JSExecutor");
return resultCollector.getResult().toString();
}
// commands w/ 2 args
if ("put".equalsIgnoreCase(command)) {
Customer customer = new Customer();
customer.setCustomerId(arg1);
customer.setName(arg2);
customer.setUsername(arg1);
Customer oldCustomer = region.put(arg1, customer);
if (oldCustomer != null) {
return oldCustomer.toString();
} else {
return "Nothing returned.";
}
}
sc.close();
return "unknown command - run 'help' for available commands";
}
@Inject
public void setRegion(Region<String, Customer> region) {
this.region = region;
}
void start() {
if (thread == null) {
threadActive = true;
thread = new Thread(new Task(), "cmd-processor");
thread.start();
}
}
void stop() throws Exception {
threadActive = false;
thread.join(3 * 100);
}
}
package gemfire.training;
import java.util.HashSet;
public class Customer implements java.io.Serializable {
private String customerId;
private String username;
private String name;
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String id) {
this.customerId = id;
}
private BillingDetails billingDetails;
private java.util.Set<ProductOrder> productOrders;
public BillingDetails getBillingDetails() {
return billingDetails;
}
public void setBillingDetails(BillingDetails billingDetails) {
this.billingDetails = billingDetails;
}
public java.util.Set<ProductOrder> getProductOrders() {
return this.productOrders;
}
public void setProductOrders(java.util.Set<ProductOrder> productOrders) {
this.productOrders = productOrders;
}
public void addProductOrder(ProductOrder po)
{
if (this.productOrders == null)
{
this.productOrders = new HashSet<ProductOrder>();
}
this.productOrders.add(po);
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
private static final long serialVersionUID = 1L;
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: ").append(getCustomerId()).append(", ");
sb.append("Name: ").append(getName()).append(", ");
sb.append("Billing Details Status: ").append(getBillingDetails() == null ? "null" : getBillingDetails().getStatusCode()).append(", ");
sb.append("ProductOrders: ").append(getProductOrders() == null ? "null" : getProductOrders().size()).append(", ");
return sb.toString();
}
}
package gemfire.training;
import java.io.Serializable;
import java.util.Properties;
import com.gemstone.gemfire.cache.Declarable;
import com.gemstone.gemfire.cache.EntryOperation;
import com.gemstone.gemfire.cache.PartitionResolver;
public class CustomerPartitionResolver implements
PartitionResolver<Serializable, Object>, Declarable {
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public Serializable getRoutingObject(EntryOperation<Serializable, Object> eo) {
//
Serializable key = eo.getKey();
if (key instanceof String) {
// This is a customerId key for a Customer Entry
return key;
} else if (key instanceof BillingDetailsKey) {
return ((BillingDetailsKey) key).getCustomerId();
} else if (key instanceof ProductOrderKey) {
return ((ProductOrderKey) key).getCustomerId();
}
return null;
}
@Override
public void init(Properties arg0) {
// TODO Auto-generated method stub
}
}
#locators=loz.local[55221]
locators=127.0.0.1[55221]
mcast-port=0
license-file=/Applications/GemFire6514/gemfireLicense.zip
statistic-archive-file=/tmp/b.tmp
statistic-sampling-enabled=true
enable-time-statistics=true
package gemfire.training;
import java.io.Serializable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.gemstone.gemfire.cache.execute.FunctionAdapter;
import com.gemstone.gemfire.cache.execute.FunctionContext;
import com.gemstone.gemfire.cache.execute.RegionFunctionContext;
public class JSExecutor extends FunctionAdapter {
private static final long serialVersionUID = 1L;
@Override
public void execute(FunctionContext fc) {
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
String script = (String) fc.getArguments();
RegionFunctionContext rfc = (RegionFunctionContext) fc;
Object region = Context.javaToJS(rfc.getDataSet(), scope);
ScriptableObject.putProperty(scope, "region", region);
Serializable result = (Serializable) cx.evaluateString(scope,
script, getId(), 1, null);
fc.getResultSender().lastResult(result);
} finally {
Context.exit();
}
}
@Override
public String getId() {
return getClass().getName();
}
}
package gemfire.training;
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import org.junit.Test;
import com.gemstone.gemfire.cache.execute.FunctionContext;
import com.gemstone.gemfire.cache.execute.ResultSender;
public class JSExecutorTest {
@Test
public void testExecute() {
JSExecutor jsExecutor = new JSExecutor();
FunctionContext fc = new FunctionContext() {
@Override
public Serializable getArguments() {
return "1 + 1;";
}
@Override
public String getFunctionId() {
return null;
}
@SuppressWarnings("unchecked")
@Override
public <T extends Serializable> ResultSender<T> getResultSender() {
return (ResultSender<T>) new ResultSender<Integer>() {
@Override
public void lastResult(Integer result) {
assertEquals(Integer.valueOf(2), result);
}
@Override
public void sendException(Throwable arg0) {
}
@Override
public void sendResult(Integer arg0) {
}
};
}
@Override
public boolean isPossibleDuplicate() {
return false;
}
};
jsExecutor.execute(fc);
}
}
package gemfire.training;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String... args) throws Exception {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
ctx.registerShutdownHook();
CommandProcessor processor = ctx.getBean(CommandProcessor.class);
processor.start();
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test-gemfire-project</groupId>
<artifactId>test-gemfire-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<compiler-plugin-version>2.3.2</compiler-plugin-version>
<dependency-plugin-version>2.2</dependency-plugin-version>
<failsafe-plugin-version>2.8.1</failsafe-plugin-version>
<gfe-version>
1.0.2.BUILD-SNAPSHOT</gfe-version>
<java-version>1.6</java-version>
<javax.inject-version>1</javax.inject-version>
<junit-version>4.7</junit-version>
<rhino-version>1.7R2</rhino-version>
<slf4j-version>1.5.10</slf4j-version>
<spring-version>3.0.4.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data.gemfire</groupId>
<artifactId>spring-gemfire</artifactId>
<version>${gfe-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>${rhino-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin-version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${dependency-plugin-version}</version>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${failsafe-plugin-version}</version>
<configuration>
<forkMode>always</forkMode>
<systemPropertyVariables>
<!-- Required. See https://jira.springsource.org/browse/SGF-26 -->
<gemfire.disableShutdownHook>true</gemfire.disableShutdownHook>
</systemPropertyVariables>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<!-- For testing against latest Spring snapshots -->
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://maven.springframework.org/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<!-- For developing against latest Spring milestones -->
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://maven.springframework.org/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
package gemfire.training;
import java.math.BigDecimal;
import java.util.Set;
public class Product implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String productId;
private String name;
private String description;
private BigDecimal price;
private Boolean inStock;
private Set<ProductOrder> productOrders;
public String getProductId() {
return this.productId;
}
public void setProductId(String id) {
this.productId = id;
}
public Set<ProductOrder> getProductOrders() {
return this.productOrders;
}
public void setProductOrders(Set<ProductOrder> productOrders) {
this.productOrders = productOrders;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Boolean getInStock() {
return this.inStock;
}
public boolean isInStock() {
return this.inStock != null && this.inStock;
}
public void setInStock(Boolean inStock) {
this.inStock = inStock;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ProductOrders: ").append(getProductOrders() == null ? "null" : getProductOrders().size()).append(", ");
sb.append("Name: ").append(getName()).append(", ");
sb.append("Description: ").append(getDescription()).append(", ");
sb.append("Price: ").append(getPrice()).append(", ");
sb.append("InStock: ").append(getInStock());
return sb.toString();
}
}
package gemfire.training;
public class ProductOrder implements java.io.Serializable {
public ProductOrder(String customerId, String productId,
String productOrderId) {
super();
this.customerId = customerId;
this.productId = productId;
this.productOrderId = productOrderId;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CustomerId: ").append(getCustomerId()).append(", ");
sb.append("ProductId: ").append(getProductId());
return sb.toString();
}
private static final long serialVersionUID = 1L;
private String customerId;
private String productId;
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getProductId() {
return this.productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
private String productOrderId;
public String getProductOrderId() {
return this.productOrderId;
}
public void setProductOrderId(String id) {
this.productOrderId = id;
}
}
package gemfire.training;
import java.io.Serializable;
public class ProductOrderKey implements Serializable {
private static final long serialVersionUID = 1L;
final String customerId;
final String productOrderKey;
public ProductOrderKey(String customerId, String productOrderKey) {
super();
this.customerId = customerId;
this.productOrderKey = productOrderKey;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductOrderKey other = (ProductOrderKey) obj;
if (productOrderKey == null) {
if (other.productOrderKey != null)
return false;
} else if (!productOrderKey.equals(other.productOrderKey))
return false;
return true;
}
public String getCustomerId() {
return customerId;
}
public String getProductOrderKey() {
return productOrderKey;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((productOrderKey == null) ? 0 : productOrderKey.hashCode());
return result;
}
@Override
public String toString() {
return "ProductOrderKey [customerId=" + customerId
+ ", productOrderKey=" + productOrderKey + "]";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment