Not receiving ack in this storm topology? - apache-storm

I am new with storm, and I am running a toplogy
public class FakeCallLogReaderSpout implements IRichSpout {
//Create instance for SpoutOutputCollector which passes tuples to bolt.
private SpoutOutputCollector collector;
private boolean completed = false;
//Create instance for TopologyContext which contains topology data.
private TopologyContext context;
//Create instance for Random class.
private Random randomGenerator = new Random();
private Integer idx = 0;
#Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
this.context = context;
this.collector = collector;
}
#Override
public void nextTuple() {
if(this.idx <= 1000) {
List<String> mobileNumbers = new ArrayList<String>();
mobileNumbers.add("1234123401");
mobileNumbers.add("1234123402");
mobileNumbers.add("1234123403");
mobileNumbers.add("1234123404");
Integer localIdx = 0;
while(localIdx++ < 100 && this.idx++ < 1000) {
String fromMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
String toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
while(fromMobileNumber == toMobileNumber) {
toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
}
Integer duration = randomGenerator.nextInt(60);
this.collector.emit(new Values(fromMobileNumber, toMobileNumber, duration),duration);
}
}
}
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("from", "to", "duration"));
}
//Override all the interface methods
#Override
public void close() {}
public boolean isDistributed() {
return false;
}
#Override
public void activate() {}
#Override
public void deactivate() {}
#Override
public void ack(Object msgId) {
System.out.println(msgId);
}
#Override
public void fail(Object msgId) {}
#Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
//Create a class CallLogCreatorBolt which implement IRichBolt interface
public class CallLogCreatorBolt implements IRichBolt {
//Create instance for OutputCollector which collects and emits tuples to produce output
private OutputCollector collector;
#Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
#Override
public void execute(Tuple tuple) {
String from = tuple.getString(0);
String to = tuple.getString(1);
Integer duration = tuple.getInteger(2);
collector.emit(new Values(from + " - " + to, duration));
}
#Override
public void cleanup() {}
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("call", "duration"));
}
#Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
public class CallLogCounterBolt implements IRichBolt {
Map<String, Integer> counterMap;
private OutputCollector collector;
#Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.counterMap = new HashMap<String, Integer>();
this.collector = collector;
}
#Override
public void execute(Tuple tuple) {
String call = tuple.getString(0);
Integer duration = tuple.getInteger(1);
if(!counterMap.containsKey(call)){
counterMap.put(call, 1);
}else{
Integer c = counterMap.get(call) + 1;
counterMap.put(call, c);
}
collector.ack(tuple);
}
#Override
public void cleanup() {
for(Map.Entry<String, Integer> entry:counterMap.entrySet()){
System.out.println(entry.getKey()+" : " + entry.getValue());
}
}
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("call"));
}
#Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
I am calling collector.ack(tuple) from CallLogCounterBolt, the but ack is not getting called.
Does anybody have any idea why it is not getting called?
Also if drop the ack altogether from the code, what impact will it have?

You need to anchor and ack tuple in each bolt. I guess your topology is like FakeCallLogReaderSpout => CallLogCreatorBolt=> CallLogCounterBolt. Thus, in CallLogCreatorBolt you should do
collector.emit(tuple, new Values(from + " - " + to, duration));
collector.ack();
Read https://storm.apache.org/releases/0.10.0/Guaranteeing-message-processing.html for more details.

Related

How to properly inject ViewResolver?

I'm trying to implement this solution but ViewResolver is not injected and it's null. I'm using Spring boot 2.x
get contents of processed JSP into spring controller without using HttpClient?
I already researched online and read documentation.
How do I properly inject the ViewResolver so the solution works?
#Service
public class SpringUtils {
private static final Logger LOG = Logger.getLogger(SpringUtils.class);
#Autowired private ViewResolver viewResolver;
#Autowired private LocaleResolver localeResolver;
public String renderView(HttpServletRequest request, ModelAndView mav) {
try {
View view = viewResolver.resolveViewName(mav.getViewName(), localeResolver.resolveLocale(request));
HttpServletResponse localResponse = new MyHttpServletResponseWrapper(new DummyResponse());
view.render(mav.getModel(), request, localResponse);
return localResponse.toString();
} catch (Exception e) {
return "";
}
}
public boolean doesViewExist(HttpServletRequest request, String viewName) {
try {
if (viewResolver.resolveViewName(viewName, localeResolver.resolveLocale(request)) != null) {
return true;
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return false;
}
static class MyHttpServletResponseWrapper extends HttpServletResponseWrapper {
private StringWriter sw = new StringWriter();
public MyHttpServletResponseWrapper(HttpServletResponse response) {
super(response);
}
public PrintWriter getWriter() throws IOException {
return new PrintWriter(sw);
}
public ServletOutputStream getOutputStream() throws IOException {
throw new UnsupportedOperationException();
}
public String toString() {
return sw.toString();
}
}
}
Dummy Response
public class DummyResponse implements HttpServletResponse {
public DummyResponse() {
}
public void setAppCommitted(boolean appCommitted) {}
public boolean isAppCommitted() { return false; }
public int getContentCount() { return -1; }
public boolean getIncluded() { return false; }
public void setIncluded(boolean included) {}
public String getInfo() { return null; }
public ServletResponse getResponse() { return null; }
public OutputStream getStream() { return null; }
public void setStream(OutputStream stream) {}
public void setSuspended(boolean suspended) {}
public boolean isSuspended() { return false; }
public void setError() {}
public boolean isError() { return false; }
public ServletOutputStream createOutputStream() throws IOException {
return null;
}
public void finishResponse() throws IOException {}
public int getContentLength() { return -1; }
public String getContentType() { return null; }
public PrintWriter getReporter() { return null; }
public void recycle() {}
public void write(int b) throws IOException {}
public void write(byte b[]) throws IOException {}
public void write(byte b[], int off, int len) throws IOException {}
public void flushBuffer() throws IOException {}
public int getBufferSize() { return -1; }
public String getCharacterEncoding() { return null; }
public void setCharacterEncoding(String charEncoding) {}
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
public Locale getLocale() { return null; }
public PrintWriter getWriter() throws IOException { return null; }
public boolean isCommitted() { return false; }
public void reset() {}
public void resetBuffer() {}
public void setBufferSize(int size) {}
public void setContentLength(int length) {}
public void setContentType(String type) {}
public void setLocale(Locale locale) {}
public Cookie[] getCookies() { return null; }
public String getHeader(String name) { return null; }
public Collection<String> getHeaders(String arg0) { return null; }
public Collection<String> getHeaderNames() { return null; };
public String[] getHeaderValues(String name) { return null; }
public String getMessage() { return null; }
public int getStatus() { return -1; }
public void reset(int status, String message) {}
public void addCookie(Cookie cookie) {}
public void addDateHeader(String name, long value) {}
public void addHeader(String name, String value) {}
public void addIntHeader(String name, int value) {}
public boolean containsHeader(String name) { return false; }
public String encodeRedirectURL(String url) { return null; }
public String encodeRedirectUrl(String url) { return null; }
public String encodeURL(String url) { return null; }
public String encodeUrl(String url) { return null; }
public void sendAcknowledgement() throws IOException {}
public void sendError(int status) throws IOException {}
public void sendError(int status, String message) throws IOException {}
public void sendRedirect(String location) throws IOException {}
public void setDateHeader(String name, long value) {}
public void setHeader(String name, String value) {}
public void setIntHeader(String name, int value) {}
public void setStatus(int status) {}
public void setStatus(int status, String message) {}
}

How to iterate through all the items in a list using Observables

I am learning how to use rxjava. As shown in the code below, I have List<List<Person>> what i am planning to do is to iterate throught all the lists of Person
and to display how many object of type Person in each list.
I coded the following:
.map(p->p.get(0).getName().map(r->r.toUpperCase()).orElse("NULL_VALUE"))
but as you see i always reference the item number 0. how can i reference all the items in the list as if I am using for-loop as folows:
for (int i = 0; i< length; i++)
p.get(i)
i hope my question is clear.
thanks in advance
code:
public static void main(String[] args) {
Observable<List<Person>> observables = Observable.create(e-> {
for(List<Person> p : Main.getPersons()) {
e.onNext(p);
}
e.onComplete();
});
observables
.map(p->p.get(0).getName().map(r->r.toUpperCase()).orElse("NULL_VALUE"))
.doOnNext(r->System.out.println("r: " + r))
.observeOn(Schedulers.io())
.subscribe(new Observer() {
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("onCompleted");
}
#Override
public void onError(Throwable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onNext(Object arg0) {
// TODO Auto-generated method stub
System.out.println("onNextFromObserver: " + arg0);
}
#Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
}
});
}
private static <T> Observable<T> toObservable(T s) {
return Observable.just(s);
}
private static List<List<Person>> getPersons() {
return Arrays.asList(
Arrays.asList(new Person("Sanna1", 59, "EGY"), new Person(null, 59, "EGY"), new Person("Sanna3", 59, null)),
Arrays.asList(new Person("Mohamed1", 59, "EGY"), new Person(null, 59, "EGY")),
Arrays.asList(new Person("Ahmed1", 44, "QTR"), new Person("Ahmed2", 44, "QTR"), new Person(null, null, "QTR")),
Arrays.asList(new Person("Fatma", 29, "KSA")),
Arrays.asList(new Person("Lobna", 24, "EGY")));
}
}
Person
public class Person {
private String name = null;
private String address = null;
private int age;
private Optional<String> optName= null;
private Optional<Integer> optAge= null;
private Optional<String> optAddress = null;
public Person(String name, Integer age, String address) {
this.optName = Optional.ofNullable(name);
this.optAge = Optional.ofNullable(age);
this.optAddress = Optional.ofNullable(address);
}
public Optional<String> getName() {
return optName;
}
public void setName(String name) {
this.optName = Optional.ofNullable(name);
}
public Optional<String> getAddress() {
return this.optAddress;
}
public void setAddress(String address) {
this.optAddress = Optional.ofNullable(address);
}
public Optional<Integer> getAge() {
return this.optAge;
}
public void setAge(int age) {
this.optAge = Optional.ofNullable(age);
}
}
update
public static void main(String[] args) {
Observable<List<Person>> observables =
Observable.fromIterable(Main.getPersons());
observables
//.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.concatMap(list->Observable.fromIterable(list)
.map(p->p.getName()
.map(r->r.toUpperCase()).orElse("NULL_VALUE")))
.observeOn(Schedulers.io())
.blockingSubscribe(new Observer<String>() {
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("onComplete: ");
}
#Override
public void onError(Throwable arg0) {
// TODO Auto-generated method stub
System.out.println("onError: ");
}
#Override
public void onNext(Object arg0) {
// TODO Auto-generated method stub
System.out.println("onNext: ");
}
#Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
System.out.println("onSubscribe: ");
}
});
}
Use fromIterables and concatMap:
public static void main(String[] args) {
Observable<List<Person>> observables =
Observable.fromIterable(Main.getPersons());
observables
.concatMap(personList ->
Observable.fromIterable(personList)
.map(aPerson ->
aPerson.getName()
.map(name -> name.toUpperCase()).orElse("NULL_VALUE")
)
)
.doOnNext(aName -> System.out.println("aName: " + aName))
.observeOn(Schedulers.io())
.blockingSubscribe(new Observer<String>() {
#Override
public void onComplete() {
System.out.println("onCompleted");
}
#Override
public void onError(Throwable ex) {
ex.printStackTrace();
}
#Override
public void onNext(String item) {
System.out.println("onNextFromObserver: " + item);
}
#Override
public void onSubscribe(Disposable disposable) {
}
});
}

Apache storm: tick tuple not working

In my Storm based application I need to query oracle table periodically So I thought to use Tick tuple of storm. But it's not giving correct result and tick tuple is not producing.
My storm version is 1.0.1.2.5.3.0-37
I tried as below,
Added getComponentConfiguration method in bolt as http://www.michael-noll.com/blog/2013/01/18/implementing-real-time-trending-topics-in-storm/ link but tick tuple is not generating.
So I changed the code and used Config from topology for generating tick tuple.I refer https://www.safaribooksonline.com/blog/2014/01/06/multi-threading-storm/ link but here I got tick tuple only once.
Below is my code of tick tuple with bolt,
public class TickTupleBolt implements IRichBolt{
private OutputCollector collector = null;
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(TickTupleBolt.class);
public void prepare(Map stormConf, TopologyContext context,OutputCollector collector) {
this.collector = collector;
}
public void execute(Tuple tuple) {
LOG.info("Start of TickTupleBolt.execute");
try {
if (isTickTuple(tuple)) {
//if(tuple.getSourceStreamId().equals("__tick")){
LOG.info("**got tick tuple");
}else{
LOG.info("not got tick tuple");
}
} catch (Exception e) {
LOG.error("Bolt execute error: {}", e);
collector.reportError(e);
}
LOG.info("End of TickTupleBolt.execute");
}
public void cleanup() {
// TODO Auto-generated method stub
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
// TODO Auto-generated method stub
}
public Map<String, Object> getComponentConfiguration() {
// configure how often a tick tuple will be sent to our bolt
Map<String, Object> conf = new HashMap<String, Object>();
conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, 1);
return conf;
}
protected boolean isTickTuple(Tuple tuple) {
return tuple.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID)
&& tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID);
}
}
I got one link Tick Tuple not functioning in apache storm 0.9.4 but there is no answer.
So can any body please let me know,
How to implement tick tuple in Storm
Is there any other way (apart from tick tuple) to do periodic job in storm
UPDATE - Topology Code
My Topology builder,
public class Topology {
private static final Logger LOG = LoggerFactory.getLogger(Topology.class);
public static StormTopology buildTopology() {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("tickspout", new TickTupleSpout());
builder.setBolt("tickbolt", new TickTupleBolt()).shuffleGrouping("tickspout");
return builder.createTopology();
}
public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, AuthorizationException {
Config conf = new Config();
//conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, 5);//tried it also
conf.setDebug(true);
//conf.setNumWorkers(2);
StormSubmitter.submitTopology(args[0], conf, buildTopology());
}
}
UPDATE - Spout Code
public class TickTupleSpout extends BaseRichSpout{
private static final Logger LOG = LoggerFactory.getLogger(TickTupleSpout.class);
private static final long serialVersionUID = 1L;
private SpoutOutputCollector collector;
public TickTupleSpout() {
}
public void open(Map conf, TopologyContext context,
SpoutOutputCollector collector) {
// TODO Auto-generated method stub
LOG.info("Start of TickTupleSpout.Open");
this.collector = collector;
LOG.info("End of TickTupleSpout.Open");
}
public void nextTuple() {
LOG.info("Start of TickTupleSpout.nextTuple");
this.collector.emit(new Values("0");//just send dummy value
LOG.info("End of TickTupleSpout.nextTuple");
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("breachdata"));
}
//public Map<String, Object> getComponentConfiguration() {
//Config conf = new Config();
//int tickFrequencyInSeconds = 5;
//conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, tickFrequencyInSeconds);
//return conf;
//}
}
Thanks.

Spring Batch how to regroup/aggregate user datas into a single object

I am trying to transform user operations (like purshases) into a user summary class (expenses by user). A user can have multiple operations but only one summary. I cannot sum purshases in the reader because I need a processor to reject some operation depending to another service.
So some code :
class UserOperation {
String userId;
Integer price;
}
class UserSummary {
String userId;
Long sum;
}
#Bean
public Step retrieveOobClientStep1(StepBuilderFactory stepBuilderFactory, ItemReader<UserOperation> userInformationJdbcCursorItemReader, ItemProcessor<UserOperation, UserSummary> userInformationsProcessor, ItemWriter<UserSummary> flatFileWriter) {
return stepBuilderFactory.get("Step1").<UserOperation, UserSummary>chunk(100) // chunck result that need to be aggregated... not good
.reader(userInformationJdbcCursorItemReader) // read all user operations from DB
.processor(userInformationsProcessor) // I need to reject or not some operations - but here 1 operation = 1 summary that is not good
.writer(flatFileWriter) // write result into flat file
.build();
}
I thing that ItemReader/ItemProcessor/ItemWriter is for single item processing.
But how to regroup multiples records into a single object using Spring Batch ? only Tasklet ?
Possibility but cause problems with small commit interval :
public class UserSummaryAggregatorItemStreamWriter implements ItemStreamWriter<UserSummary>, InitializingBean {
private ItemStreamWriter<UserSummary> delegate;
#Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(delegate, "'delegate' may not be null.");
}
public void setDelegate(ItemStreamWriter<UserSummary> delegate) {
this.delegate = delegate;
}
#Override
public void write(List<? extends UserSummary> items) throws Exception {
Map<String, UserSummary> userSummaryMap = new HashMap<String, UserSummary>();
// Aggregate
for (UserSummary item : items) {
UserSummary savedUserSummary = userSummaryMap.get(item.getUserId());
if (savedUserSummary != null) {
savedUserSummary.incrementSum(item.getSum()); // sum
} else {
savedUserSummary = item;
}
userSummaryMap.put(item.getSubscriptionCode(), savedUserSummary);
}
Collection<UserSummary> values = userSummaryMap.values();
if(values != null) {
delegate.write(new ArrayList<UserSummary>(values));
}
}
#Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
delegate.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
delegate.update(executionContext);
}
#Override
public void close() throws ItemStreamException {
delegate.close();
}
}

window scope in spring?

i was wondering about the spring scope equivalent to window scope ?
according to the documentation here
http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch04s04.html
i couldn't find any, so if there's a custom scope equivalent, can anyone please tell me, thanks.
EDIT: example of window scope in JSF
http://icefaces-showcase.icesoft.org/showcase.jsf?grp=compatMenu&exp=popup
One possible approach is having a session scoped bean that holds all the window sessions, and a window custom scope that access to the corresponding bean through that session scoped bean.
The required classes are:
Window Session
public class WindowSession {
private Map<String, Map<String,Object>> scopeMap = new HashMap<String, Map<String,Object>>();
private Map<String, Boolean> validSessions = new HashMap<String, Boolean>();
public WindowSession() {
super();
}
public Map<String, Map<String, Object>> getScopeMap() {
return scopeMap;
}
public void setScopeMap(Map<String, Map<String, Object>> scopeMap) {
this.scopeMap = scopeMap;
}
public Map<String, Boolean> getValidSessions() {
return validSessions;
}
public void setValidSessions(Map<String, Boolean> validSessions) {
this.validSessions = validSessions;
}
}
WindowIdContext
#Service
#Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class WindowIdContext {
public static final String DEFAULT_SESSION_ID = "";
private String id = DEFAULT_SESSION_ID;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getQueryParamWithSessionId() {
if (DEFAULT_SESSION_ID.equals(id)) {
return "";
}
return "?" + WindowScope.WINDOW_ID_PARAM + "=" + id;
}
}
WindowSessionContext
#Service
#Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class WindowSessionContext {
private static SecureRandom random = new SecureRandom();
private WindowSession windowSession = new WindowSession();
#Autowired
private WindowIdContext windowIdContext;
public WindowSessionContext() {
windowSession.getValidSessions().put(WindowIdContext.DEFAULT_SESSION_ID, false);
}
public Object getObject(String name, ObjectFactory<?> objectFactory) {
String sessionId = windowIdContext.getId();
synchronized(this) {
if (!windowSession.getValidSessions().containsKey(sessionId)) {
windowSession.getValidSessions().put(sessionId, false);
}
Map<String,Object> sessionMap = windowSession.getScopeMap().get(sessionId);
if (sessionMap == null) {
sessionMap = new HashMap<String,Object>();
windowSession.getScopeMap().put(sessionId, sessionMap);
}
Object object = sessionMap.get(name);
if (object == null) {
object = objectFactory.getObject();
sessionMap.put(name, object);
}
return object;
}
}
public Object removeObject(String name) {
String sessionId = windowIdContext.getId();
synchronized(this) {
Map<String,Object> sessionMap = windowSession.getScopeMap().get(sessionId);
if (sessionMap == null) {
return null;
}
Object object = sessionMap.remove(name);
return object;
}
}
public String addSession() {
synchronized(this) {
String sessionId;
do {
sessionId = new BigInteger(130, random).toString(32);
} while (windowSession.getValidSessions().containsKey(sessionId));
windowSession.getValidSessions().put(sessionId, false);
return sessionId;
}
}
public void removeSession() {
String sessionId = windowIdContext.getId();
synchronized(this) {
windowSession.getScopeMap().remove(sessionId);
windowSession.getValidSessions().remove(sessionId);
}
}
public boolean isSessionValid(String sessionId) {
Boolean inUse = windowSession.getValidSessions().get(sessionId);
return inUse != null;
}
public boolean isSessionInUse(String sessionId) {
Boolean inUse = windowSession.getValidSessions().get(sessionId);
return inUse == true;
}
public synchronized boolean invalidateSession(String sessionId) {
Boolean valid = windowSession.getValidSessions().get(sessionId);
if (valid == null) {
return false;
}
if (sessionId.equals(WindowIdContext.DEFAULT_SESSION_ID)) {
windowSession.getValidSessions().put(sessionId, false);
} else {
windowSession.getValidSessions().remove(sessionId);
}
windowSession.getScopeMap().remove(sessionId);
for (Entry<String,Boolean> validSession : windowSession.getValidSessions().entrySet()) {
if (validSession.getValue() == true) {
return false;
}
}
return true;
}
public synchronized void setSessionInUse(String sessionId) {
windowSession.getValidSessions().put(sessionId, true);
}
public int getCount() {
return windowSession.getValidSessions().size();
}
}
WindowScope
public class WindowScope implements Scope {
private final int scope;
private static final int WINDOW_SCOPE = 40;
public static final String NAME = "window";
public static final String WINDOW_ID_PARAM = "windowid";
private ServletContext servletContext = null;
public WindowScope(ServletContext sc) {
servletContext = sc;
this.scope = WINDOW_SCOPE;
}
#Override
public Object get(String name, ObjectFactory<?> objectFactory) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
WindowSessionContext windowSessionContext = applicationContext.getBean(WindowSessionContext.class);
return windowSessionContext.getObject(name, objectFactory);
}
#Override
public Object remove(String name) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
WindowSessionContext windowSessionContext = applicationContext.getBean(WindowSessionContext.class);
return windowSessionContext.removeObject(name);
}
#Override
public String getConversationId() {
return RequestContextHolder.currentRequestAttributes().getSessionId();
}
#Override
public void registerDestructionCallback(String arg0, Runnable arg1) {
}
#Override
public Object resolveContextualObject(String key) {
return null;
}
protected int getScope() {
return this.scope;
}
}
WindowScopeFilter
#Component("windowScopeFilter")
public class WindowScopeFilter implements Filter {
#Autowired
private WindowSessionContext windowSessionContext;
#Autowired
private WindowIdContext windowIdContext;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
String sessionId = httpRequest.getParameter(WindowScope.WINDOW_ID_PARAM);
if (sessionId != null) {
if (windowSessionContext.isSessionValid(sessionId)) {
windowIdContext.setId(sessionId);
} else {
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} else {
windowSessionContext.setSessionInUse(WindowIdContext.DEFAULT_SESSION_ID);
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
}
}
WindowScopeListener
#Component
public class WindowScopeListener implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
WebApplicationContext applicationContext = (WebApplicationContext)event.getApplicationContext();
Scope windowScope = new WindowScope(applicationContext.getServletContext());
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
beanFactory.registerScope("window", windowScope);
}
}
Source with complete source code: http://notwithoutmycode.com/post/window/scope/in/spring

Resources