[BAEL-16663] - Split or move spring-mvc-java module
This commit is contained in:
@@ -1,54 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Component
|
||||
@Aspect
|
||||
public class LoggingAspect {
|
||||
|
||||
private static Logger logger = Logger.getLogger(LoggingAspect.class.getName());
|
||||
|
||||
private ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
|
||||
@Override
|
||||
protected SimpleDateFormat initialValue() {
|
||||
return new SimpleDateFormat("[yyyy-mm-dd hh:mm:ss:SSS]");
|
||||
}
|
||||
};
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))")
|
||||
public void repositoryMethods() {
|
||||
}
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && @annotation(com.baeldung.aop.annotations.Loggable)")
|
||||
public void loggableMethods() {
|
||||
}
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && @args(com.baeldung.aop.annotations.Entity)")
|
||||
public void methodsAcceptingEntities() {
|
||||
}
|
||||
|
||||
@Before("repositoryMethods()")
|
||||
public void logMethodCall(JoinPoint jp) {
|
||||
String methodName = jp.getSignature().getName();
|
||||
logger.info(sdf.get().format(new Date()) + methodName);
|
||||
}
|
||||
|
||||
@Before("loggableMethods()")
|
||||
public void logMethod(JoinPoint jp) {
|
||||
String methodName = jp.getSignature().getName();
|
||||
logger.info("Executing method: " + methodName);
|
||||
}
|
||||
|
||||
@Before("methodsAcceptingEntities()")
|
||||
public void logMethodAcceptionEntityAnnotatedBean(JoinPoint jp) {
|
||||
logger.info("Accepting beans with @Entity annotation: " + jp.getArgs()[0]);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
public class PerformanceAspect {
|
||||
|
||||
private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))")
|
||||
public void repositoryClassMethods() {
|
||||
}
|
||||
|
||||
@Around("repositoryClassMethods()")
|
||||
public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
|
||||
long start = System.nanoTime();
|
||||
Object retval = pjp.proceed();
|
||||
long end = System.nanoTime();
|
||||
String methodName = pjp.getSignature().getName();
|
||||
logger.info("Execution of " + methodName + " took " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
|
||||
return retval;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import com.baeldung.events.FooCreationEvent;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Aspect
|
||||
public class PublishingAspect {
|
||||
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
|
||||
@Autowired
|
||||
public void setEventPublisher(ApplicationEventPublisher eventPublisher) {
|
||||
this.eventPublisher = eventPublisher;
|
||||
}
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))")
|
||||
public void repositoryMethods() {
|
||||
}
|
||||
|
||||
@Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.create*(Long,..))")
|
||||
public void firstLongParamMethods() {
|
||||
}
|
||||
|
||||
@Pointcut("repositoryMethods() && firstLongParamMethods()")
|
||||
public void entityCreationMethods() {
|
||||
}
|
||||
|
||||
@AfterReturning(value = "entityCreationMethods()", returning = "entity")
|
||||
public void logMethodCall(JoinPoint jp, Object entity) throws Throwable {
|
||||
eventPublisher.publishEvent(new FooCreationEvent(entity));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.aop.annotations;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Entity {
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.aop.annotations;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Loggable {
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.dao;
|
||||
|
||||
import com.baeldung.aop.annotations.Loggable;
|
||||
import com.baeldung.model.Foo;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class FooDao {
|
||||
|
||||
public String findById(Long id) {
|
||||
return "Bazz";
|
||||
}
|
||||
|
||||
@Loggable
|
||||
public Foo create(Long id, String name) {
|
||||
return new Foo(id, name);
|
||||
}
|
||||
|
||||
public Foo merge(Foo foo) {
|
||||
return foo;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.baeldung.events;
|
||||
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
|
||||
public class FooCreationEvent extends ApplicationEvent {
|
||||
|
||||
public FooCreationEvent(Object source) {
|
||||
super(source);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.events;
|
||||
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Component
|
||||
public class FooCreationEventListener implements ApplicationListener<FooCreationEvent> {
|
||||
|
||||
private static Logger logger = Logger.getLogger(FooCreationEventListener.class.getName());
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(FooCreationEvent event) {
|
||||
logger.info("Created foo instance: " + event.getSource().toString());
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import com.baeldung.aop.annotations.Entity;
|
||||
|
||||
@Entity
|
||||
public class Foo {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Foo(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}';
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Message {
|
||||
|
||||
private String from;
|
||||
private String text;
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class OutputMessage {
|
||||
|
||||
private String from;
|
||||
private String text;
|
||||
private String time;
|
||||
|
||||
public OutputMessage(final String from, final String text, final String time) {
|
||||
|
||||
this.from = from;
|
||||
this.text = text;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.spring.web.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(final MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(final StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/chat");
|
||||
registry.addEndpoint("/chat").withSockJS();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.spring.web.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketSendToUserConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic/", "/queue/");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/greeting").setHandshakeHandler(new DefaultHandshakeHandler() {
|
||||
|
||||
//Get sessionId from request and set it in Map attributes
|
||||
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
|
||||
Map attributes) throws Exception {
|
||||
if (request instanceof ServletServerHttpRequest) {
|
||||
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
|
||||
HttpSession session = servletRequest.getServletRequest().getSession();
|
||||
attributes.put("sessionId", session.getId());
|
||||
}
|
||||
return true;
|
||||
}}).withSockJS();
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import com.baeldung.model.Message;
|
||||
import com.baeldung.model.OutputMessage;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.SendTo;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
@Controller
|
||||
public class ChatController {
|
||||
|
||||
@MessageMapping("/chat")
|
||||
@SendTo("/topic/messages")
|
||||
public OutputMessage send(final Message message) throws Exception {
|
||||
|
||||
final String time = new SimpleDateFormat("HH:mm").format(new Date());
|
||||
return new OutputMessage(message.getFrom(), message.getText(), time);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.baeldung.web.controller;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.simp.annotation.SendToUser;
|
||||
import org.springframework.stereotype.Controller;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
@Controller
|
||||
public class WebsocketSendToUserController {
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
@MessageMapping("/message")
|
||||
@SendToUser("/queue/reply")
|
||||
public String processMessageFromClient(@Payload String message, Principal principal) throws Exception {
|
||||
return gson.fromJson(message, Map.class).get("name").toString();
|
||||
}
|
||||
|
||||
@MessageExceptionHandler
|
||||
@SendToUser("/queue/errors")
|
||||
public String handleException(Throwable exception) {
|
||||
return exception.getMessage();
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<?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:aop="http://www.springframework.org/schema/aop"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/aop
|
||||
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
|
||||
|
||||
<bean id="perfomanceMeter" class="com.baeldung.aop.PerformanceAspect"/>
|
||||
<bean id="fooDao" class="com.baeldung.dao.FooDao"/>
|
||||
|
||||
<aop:config>
|
||||
<aop:pointcut id="anyDaoMethod" expression="@target(org.springframework.stereotype.Repository)"/>
|
||||
<aop:aspect ref="perfomanceMeter">
|
||||
<aop:around method="measureMethodExecutionTime" pointcut-ref="anyDaoMethod"/>
|
||||
</aop:aspect>
|
||||
</aop:config>
|
||||
</beans>
|
||||
@@ -1,88 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Chat WebSocket</title>
|
||||
|
||||
<script src="./js/sockjs-0.3.4.js"></script>
|
||||
<script src="./js/stomp.js"></script>
|
||||
|
||||
<script type="text/javascript">
|
||||
|
||||
var stompClient = null;
|
||||
|
||||
function setConnected(connected) {
|
||||
|
||||
document.getElementById('connect').disabled = connected;
|
||||
document.getElementById('disconnect').disabled = !connected;
|
||||
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
|
||||
document.getElementById('response').innerHTML = '';
|
||||
}
|
||||
|
||||
function connect() {
|
||||
|
||||
var socket = new SockJS('/spring-mvc-java/chat');
|
||||
stompClient = Stomp.over(socket);
|
||||
|
||||
stompClient.connect({}, function(frame) {
|
||||
|
||||
setConnected(true);
|
||||
console.log('Connected: ' + frame);
|
||||
stompClient.subscribe('/topic/messages', function(messageOutput) {
|
||||
|
||||
showMessageOutput(JSON.parse(messageOutput.body));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
|
||||
if(stompClient != null) {
|
||||
stompClient.disconnect();
|
||||
}
|
||||
|
||||
setConnected(false);
|
||||
console.log("Disconnected");
|
||||
}
|
||||
|
||||
function sendMessage() {
|
||||
|
||||
var from = document.getElementById('from').value;
|
||||
var text = document.getElementById('text').value;
|
||||
stompClient.send("/app/chat", {}, JSON.stringify({'from':from, 'text':text}));
|
||||
}
|
||||
|
||||
function showMessageOutput(messageOutput) {
|
||||
|
||||
var response = document.getElementById('response');
|
||||
var p = document.createElement('p');
|
||||
p.style.wordWrap = 'break-word';
|
||||
p.appendChild(document.createTextNode(messageOutput.from + ": " + messageOutput.text + " (" + messageOutput.time + ")"));
|
||||
response.appendChild(p);
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</head>
|
||||
|
||||
<body onload="disconnect()">
|
||||
|
||||
<div>
|
||||
|
||||
|
||||
<div>
|
||||
<input type="text" id="from" placeholder="Choose a nickname"/>
|
||||
</div>
|
||||
<br />
|
||||
<div>
|
||||
<button id="connect" onclick="connect();">Connect</button>
|
||||
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
|
||||
</div>
|
||||
<br />
|
||||
<div id="conversationDiv">
|
||||
<input type="text" id="text" placeholder="Write a message..."/>
|
||||
<button id="sendMessage" onclick="sendMessage();">Send</button>
|
||||
<p id="response"></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,475 +0,0 @@
|
||||
// Generated by CoffeeScript 1.7.1
|
||||
|
||||
/*
|
||||
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
|
||||
|
||||
Copyright (C) 2010-2013 [Jeff Mesnil](http://jmesnil.net/)
|
||||
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
|
||||
*/
|
||||
|
||||
(function() {
|
||||
var Byte, Client, Frame, Stomp,
|
||||
__hasProp = {}.hasOwnProperty,
|
||||
__slice = [].slice;
|
||||
|
||||
Byte = {
|
||||
LF: '\x0A',
|
||||
NULL: '\x00'
|
||||
};
|
||||
|
||||
Frame = (function() {
|
||||
var unmarshallSingle;
|
||||
|
||||
function Frame(command, headers, body) {
|
||||
this.command = command;
|
||||
this.headers = headers != null ? headers : {};
|
||||
this.body = body != null ? body : '';
|
||||
}
|
||||
|
||||
Frame.prototype.toString = function() {
|
||||
var lines, name, value, _ref;
|
||||
lines = [this.command];
|
||||
_ref = this.headers;
|
||||
for (name in _ref) {
|
||||
if (!__hasProp.call(_ref, name)) continue;
|
||||
value = _ref[name];
|
||||
lines.push("" + name + ":" + value);
|
||||
}
|
||||
if (this.body) {
|
||||
lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));
|
||||
}
|
||||
lines.push(Byte.LF + this.body);
|
||||
return lines.join(Byte.LF);
|
||||
};
|
||||
|
||||
Frame.sizeOfUTF8 = function(s) {
|
||||
if (s) {
|
||||
return encodeURI(s).split(/%..|./).length - 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
unmarshallSingle = function(data) {
|
||||
var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
|
||||
divider = data.search(RegExp("" + Byte.LF + Byte.LF));
|
||||
headerLines = data.substring(0, divider).split(Byte.LF);
|
||||
command = headerLines.shift();
|
||||
headers = {};
|
||||
trim = function(str) {
|
||||
return str.replace(/^\s+|\s+$/g, '');
|
||||
};
|
||||
_ref = headerLines.reverse();
|
||||
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
||||
line = _ref[_i];
|
||||
idx = line.indexOf(':');
|
||||
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
|
||||
}
|
||||
body = '';
|
||||
start = divider + 2;
|
||||
if (headers['content-length']) {
|
||||
len = parseInt(headers['content-length']);
|
||||
body = ('' + data).substring(start, start + len);
|
||||
} else {
|
||||
chr = null;
|
||||
for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
|
||||
chr = data.charAt(i);
|
||||
if (chr === Byte.NULL) {
|
||||
break;
|
||||
}
|
||||
body += chr;
|
||||
}
|
||||
}
|
||||
return new Frame(command, headers, body);
|
||||
};
|
||||
|
||||
Frame.unmarshall = function(datas) {
|
||||
var data;
|
||||
return (function() {
|
||||
var _i, _len, _ref, _results;
|
||||
_ref = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));
|
||||
_results = [];
|
||||
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
||||
data = _ref[_i];
|
||||
if ((data != null ? data.length : void 0) > 0) {
|
||||
_results.push(unmarshallSingle(data));
|
||||
}
|
||||
}
|
||||
return _results;
|
||||
})();
|
||||
};
|
||||
|
||||
Frame.marshall = function(command, headers, body) {
|
||||
var frame;
|
||||
frame = new Frame(command, headers, body);
|
||||
return frame.toString() + Byte.NULL;
|
||||
};
|
||||
|
||||
return Frame;
|
||||
|
||||
})();
|
||||
|
||||
Client = (function() {
|
||||
var now;
|
||||
|
||||
function Client(ws) {
|
||||
this.ws = ws;
|
||||
this.ws.binaryType = "arraybuffer";
|
||||
this.counter = 0;
|
||||
this.connected = false;
|
||||
this.heartbeat = {
|
||||
outgoing: 10000,
|
||||
incoming: 10000
|
||||
};
|
||||
this.maxWebSocketFrameSize = 16 * 1024;
|
||||
this.subscriptions = {};
|
||||
}
|
||||
|
||||
Client.prototype.debug = function(message) {
|
||||
var _ref;
|
||||
return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;
|
||||
};
|
||||
|
||||
now = function() {
|
||||
return Date.now || new Date().valueOf;
|
||||
};
|
||||
|
||||
Client.prototype._transmit = function(command, headers, body) {
|
||||
var out;
|
||||
out = Frame.marshall(command, headers, body);
|
||||
if (typeof this.debug === "function") {
|
||||
this.debug(">>> " + out);
|
||||
}
|
||||
while (true) {
|
||||
if (out.length > this.maxWebSocketFrameSize) {
|
||||
this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
|
||||
out = out.substring(this.maxWebSocketFrameSize);
|
||||
if (typeof this.debug === "function") {
|
||||
this.debug("remaining = " + out.length);
|
||||
}
|
||||
} else {
|
||||
return this.ws.send(out);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype._setupHeartbeat = function(headers) {
|
||||
var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
|
||||
if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {
|
||||
return;
|
||||
}
|
||||
_ref1 = (function() {
|
||||
var _i, _len, _ref1, _results;
|
||||
_ref1 = headers['heart-beat'].split(",");
|
||||
_results = [];
|
||||
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
|
||||
v = _ref1[_i];
|
||||
_results.push(parseInt(v));
|
||||
}
|
||||
return _results;
|
||||
})(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
|
||||
if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
|
||||
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
|
||||
if (typeof this.debug === "function") {
|
||||
this.debug("send PING every " + ttl + "ms");
|
||||
}
|
||||
this.pinger = Stomp.setInterval(ttl, (function(_this) {
|
||||
return function() {
|
||||
_this.ws.send(Byte.LF);
|
||||
return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
|
||||
};
|
||||
})(this));
|
||||
}
|
||||
if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
|
||||
ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
|
||||
if (typeof this.debug === "function") {
|
||||
this.debug("check PONG every " + ttl + "ms");
|
||||
}
|
||||
return this.ponger = Stomp.setInterval(ttl, (function(_this) {
|
||||
return function() {
|
||||
var delta;
|
||||
delta = now() - _this.serverActivity;
|
||||
if (delta > ttl * 2) {
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug("did not receive server activity for the last " + delta + "ms");
|
||||
}
|
||||
return _this.ws.close();
|
||||
}
|
||||
};
|
||||
})(this));
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype._parseConnect = function() {
|
||||
var args, connectCallback, errorCallback, headers;
|
||||
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
|
||||
headers = {};
|
||||
switch (args.length) {
|
||||
case 2:
|
||||
headers = args[0], connectCallback = args[1];
|
||||
break;
|
||||
case 3:
|
||||
if (args[1] instanceof Function) {
|
||||
headers = args[0], connectCallback = args[1], errorCallback = args[2];
|
||||
} else {
|
||||
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
|
||||
break;
|
||||
default:
|
||||
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
|
||||
}
|
||||
return [headers, connectCallback, errorCallback];
|
||||
};
|
||||
|
||||
Client.prototype.connect = function() {
|
||||
var args, errorCallback, headers, out;
|
||||
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
|
||||
out = this._parseConnect.apply(this, args);
|
||||
headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
|
||||
if (typeof this.debug === "function") {
|
||||
this.debug("Opening Web Socket...");
|
||||
}
|
||||
this.ws.onmessage = (function(_this) {
|
||||
return function(evt) {
|
||||
var arr, c, client, data, frame, messageID, onreceive, subscription, _i, _len, _ref, _results;
|
||||
data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {
|
||||
var _i, _len, _results;
|
||||
_results = [];
|
||||
for (_i = 0, _len = arr.length; _i < _len; _i++) {
|
||||
c = arr[_i];
|
||||
_results.push(String.fromCharCode(c));
|
||||
}
|
||||
return _results;
|
||||
})()).join('')) : evt.data;
|
||||
_this.serverActivity = now();
|
||||
if (data === Byte.LF) {
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug("<<< PONG");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug("<<< " + data);
|
||||
}
|
||||
_ref = Frame.unmarshall(data);
|
||||
_results = [];
|
||||
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
|
||||
frame = _ref[_i];
|
||||
switch (frame.command) {
|
||||
case "CONNECTED":
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug("connected to server " + frame.headers.server);
|
||||
}
|
||||
_this.connected = true;
|
||||
_this._setupHeartbeat(frame.headers);
|
||||
_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
|
||||
break;
|
||||
case "MESSAGE":
|
||||
subscription = frame.headers.subscription;
|
||||
onreceive = _this.subscriptions[subscription] || _this.onreceive;
|
||||
if (onreceive) {
|
||||
client = _this;
|
||||
messageID = frame.headers["message-id"];
|
||||
frame.ack = function(headers) {
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
return client.ack(messageID, subscription, headers);
|
||||
};
|
||||
frame.nack = function(headers) {
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
return client.nack(messageID, subscription, headers);
|
||||
};
|
||||
_results.push(onreceive(frame));
|
||||
} else {
|
||||
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
|
||||
}
|
||||
break;
|
||||
case "RECEIPT":
|
||||
_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
|
||||
break;
|
||||
case "ERROR":
|
||||
_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
|
||||
break;
|
||||
default:
|
||||
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
|
||||
}
|
||||
}
|
||||
return _results;
|
||||
};
|
||||
})(this);
|
||||
this.ws.onclose = (function(_this) {
|
||||
return function() {
|
||||
var msg;
|
||||
msg = "Whoops! Lost connection to " + _this.ws.url;
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug(msg);
|
||||
}
|
||||
_this._cleanUp();
|
||||
return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
|
||||
};
|
||||
})(this);
|
||||
return this.ws.onopen = (function(_this) {
|
||||
return function() {
|
||||
if (typeof _this.debug === "function") {
|
||||
_this.debug('Web Socket Opened...');
|
||||
}
|
||||
headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
|
||||
headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
|
||||
return _this._transmit("CONNECT", headers);
|
||||
};
|
||||
})(this);
|
||||
};
|
||||
|
||||
Client.prototype.disconnect = function(disconnectCallback) {
|
||||
this._transmit("DISCONNECT");
|
||||
this.ws.onclose = null;
|
||||
this.ws.close();
|
||||
this._cleanUp();
|
||||
return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
|
||||
};
|
||||
|
||||
Client.prototype._cleanUp = function() {
|
||||
this.connected = false;
|
||||
if (this.pinger) {
|
||||
Stomp.clearInterval(this.pinger);
|
||||
}
|
||||
if (this.ponger) {
|
||||
return Stomp.clearInterval(this.ponger);
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype.send = function(destination, headers, body) {
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
if (body == null) {
|
||||
body = '';
|
||||
}
|
||||
headers.destination = destination;
|
||||
return this._transmit("SEND", headers, body);
|
||||
};
|
||||
|
||||
Client.prototype.subscribe = function(destination, callback, headers) {
|
||||
var client;
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
if (!headers.id) {
|
||||
headers.id = "sub-" + this.counter++;
|
||||
}
|
||||
headers.destination = destination;
|
||||
this.subscriptions[headers.id] = callback;
|
||||
this._transmit("SUBSCRIBE", headers);
|
||||
client = this;
|
||||
return {
|
||||
id: headers.id,
|
||||
unsubscribe: function() {
|
||||
return client.unsubscribe(headers.id);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Client.prototype.unsubscribe = function(id) {
|
||||
delete this.subscriptions[id];
|
||||
return this._transmit("UNSUBSCRIBE", {
|
||||
id: id
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.begin = function(transaction) {
|
||||
var client, txid;
|
||||
txid = transaction || "tx-" + this.counter++;
|
||||
this._transmit("BEGIN", {
|
||||
transaction: txid
|
||||
});
|
||||
client = this;
|
||||
return {
|
||||
id: txid,
|
||||
commit: function() {
|
||||
return client.commit(txid);
|
||||
},
|
||||
abort: function() {
|
||||
return client.abort(txid);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Client.prototype.commit = function(transaction) {
|
||||
return this._transmit("COMMIT", {
|
||||
transaction: transaction
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.abort = function(transaction) {
|
||||
return this._transmit("ABORT", {
|
||||
transaction: transaction
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.ack = function(messageID, subscription, headers) {
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
headers["message-id"] = messageID;
|
||||
headers.subscription = subscription;
|
||||
return this._transmit("ACK", headers);
|
||||
};
|
||||
|
||||
Client.prototype.nack = function(messageID, subscription, headers) {
|
||||
if (headers == null) {
|
||||
headers = {};
|
||||
}
|
||||
headers["message-id"] = messageID;
|
||||
headers.subscription = subscription;
|
||||
return this._transmit("NACK", headers);
|
||||
};
|
||||
|
||||
return Client;
|
||||
|
||||
})();
|
||||
|
||||
Stomp = {
|
||||
VERSIONS: {
|
||||
V1_0: '1.0',
|
||||
V1_1: '1.1',
|
||||
V1_2: '1.2',
|
||||
supportedVersions: function() {
|
||||
return '1.1,1.0';
|
||||
}
|
||||
},
|
||||
client: function(url, protocols) {
|
||||
var klass, ws;
|
||||
if (protocols == null) {
|
||||
protocols = ['v10.stomp', 'v11.stomp'];
|
||||
}
|
||||
klass = Stomp.WebSocketClass || WebSocket;
|
||||
ws = new klass(url, protocols);
|
||||
return new Client(ws);
|
||||
},
|
||||
over: function(ws) {
|
||||
return new Client(ws);
|
||||
},
|
||||
Frame: Frame
|
||||
};
|
||||
|
||||
if (typeof window !== "undefined" && window !== null) {
|
||||
Stomp.setInterval = function(interval, f) {
|
||||
return window.setInterval(f, interval);
|
||||
};
|
||||
Stomp.clearInterval = function(id) {
|
||||
return window.clearInterval(id);
|
||||
};
|
||||
window.Stomp = Stomp;
|
||||
} else if (typeof exports !== "undefined" && exports !== null) {
|
||||
exports.Stomp = Stomp;
|
||||
} else {
|
||||
self.Stomp = Stomp;
|
||||
}
|
||||
|
||||
}).call(this);
|
||||
@@ -1,24 +0,0 @@
|
||||
function connect() {
|
||||
var socket = new WebSocket('ws://localhost:8080/greeting');
|
||||
ws = Stomp.over(socket);
|
||||
|
||||
ws.connect({}, function(frame) {
|
||||
ws.subscribe("/user/queue/errors", function(message) {
|
||||
alert("Error " + message.body);
|
||||
});
|
||||
|
||||
ws.subscribe("/user/queue/reply", function(message) {
|
||||
alert("Message " + message.body);
|
||||
});
|
||||
}, function(error) {
|
||||
alert("STOMP error " + error);
|
||||
});
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
if (ws != null) {
|
||||
ws.close();
|
||||
}
|
||||
setConnected(false);
|
||||
console.log("Disconnected");
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.config.TestConfig;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class})
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import com.baeldung.config.TestConfig;
|
||||
import com.baeldung.dao.FooDao;
|
||||
import com.baeldung.model.Foo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.core.IsCollectionContaining.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopLoggingIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
messages = new ArrayList<>();
|
||||
|
||||
logEventHandler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
messages.add(record.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SecurityException {
|
||||
}
|
||||
};
|
||||
|
||||
Logger logger = Logger.getLogger(LoggingAspect.class.getName());
|
||||
logger.addHandler(logEventHandler);
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private FooDao dao;
|
||||
|
||||
private Handler logEventHandler;
|
||||
|
||||
private List<String> messages;
|
||||
|
||||
@Test
|
||||
public void givenLoggingAspect_whenCallDaoMethod_thenBeforeAdviceIsCalled() {
|
||||
dao.findById(1L);
|
||||
assertThat(messages, hasSize(1));
|
||||
|
||||
String logMessage = messages.get(0);
|
||||
Pattern pattern = Pattern.compile("^\\[\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}\\]findById$");
|
||||
assertTrue(pattern.matcher(logMessage).matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggingAspect_whenCallLoggableAnnotatedMethod_thenMethodIsLogged() {
|
||||
dao.create(42L, "baz");
|
||||
assertThat(messages, hasItem("Executing method: create"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoggingAspect_whenCallMethodAcceptingAnnotatedArgument_thenArgumentIsLogged() {
|
||||
Foo foo = new Foo(42L, "baz");
|
||||
dao.merge(foo);
|
||||
assertThat(messages, hasItem("Accepting beans with @Entity annotation: " + foo));
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import com.baeldung.config.TestConfig;
|
||||
import com.baeldung.dao.FooDao;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopPerformanceIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
logEventHandler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
messages.add(record.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SecurityException {
|
||||
}
|
||||
};
|
||||
|
||||
messages = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private FooDao dao;
|
||||
|
||||
private Handler logEventHandler;
|
||||
|
||||
private List<String> messages;
|
||||
|
||||
@Test
|
||||
public void givenPerformanceAspect_whenCallDaoMethod_thenPerformanceMeasurementAdviceIsCalled() {
|
||||
Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
|
||||
logger.addHandler(logEventHandler);
|
||||
|
||||
final String entity = dao.findById(1L);
|
||||
assertThat(entity, notNullValue());
|
||||
assertThat(messages, hasSize(1));
|
||||
|
||||
String logMessage = messages.get(0);
|
||||
Pattern pattern = Pattern.compile("Execution of findById took \\d+ ms");
|
||||
assertTrue(pattern.matcher(logMessage).matches());
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import com.baeldung.config.TestConfig;
|
||||
import com.baeldung.dao.FooDao;
|
||||
import com.baeldung.events.FooCreationEventListener;
|
||||
import com.baeldung.model.Foo;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class AopPublishingIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
logEventHandler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
messages.add(record.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SecurityException {
|
||||
}
|
||||
};
|
||||
|
||||
messages = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private FooDao dao;
|
||||
|
||||
private Handler logEventHandler;
|
||||
|
||||
private List<String> messages;
|
||||
|
||||
@Test
|
||||
public void givenPublishingAspect_whenCallCreate_thenCreationEventIsPublished() {
|
||||
Logger logger = Logger.getLogger(FooCreationEventListener.class.getName());
|
||||
logger.addHandler(logEventHandler);
|
||||
|
||||
dao.create(1L, "Bar");
|
||||
|
||||
String logMessage = messages.get(0);
|
||||
Pattern pattern = Pattern.compile("Created foo instance: " + Pattern.quote(new Foo(1L, "Bar").toString()));
|
||||
assertTrue(pattern.matcher(logMessage).matches());
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package com.baeldung.aop;
|
||||
|
||||
import com.baeldung.dao.FooDao;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration("/com/baeldung/aop/beans.xml")
|
||||
public class AopXmlConfigPerformanceIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
logEventHandler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
messages.add(record.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SecurityException {
|
||||
}
|
||||
};
|
||||
|
||||
messages = new ArrayList<>();
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private FooDao dao;
|
||||
|
||||
private Handler logEventHandler;
|
||||
|
||||
private List<String> messages;
|
||||
|
||||
@Test
|
||||
public void givenPerformanceAspect_whenCallDaoMethod_thenPerformanceMeasurementAdviceIsCalled() {
|
||||
Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
|
||||
logger.addHandler(logEventHandler);
|
||||
|
||||
final String entity = dao.findById(1L);
|
||||
assertThat(entity, notNullValue());
|
||||
assertThat(messages, hasSize(1));
|
||||
|
||||
String logMessage = messages.get(0);
|
||||
Pattern pattern = Pattern.compile("Execution of findById took \\d+ ms");
|
||||
assertTrue(pattern.matcher(logMessage).matches());
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.dao", "com.baeldung.aop", "com.baeldung.events" })
|
||||
@EnableAspectJAutoProxy
|
||||
public class TestConfig {
|
||||
}
|
||||
Reference in New Issue
Block a user