Merge remote-tracking branch 'origin/master'

This commit is contained in:
slavisa-baeldung 2016-10-10 11:59:05 +02:00
commit d011f2b70c
21 changed files with 335 additions and 150 deletions

View File

@ -107,17 +107,13 @@ public class FileOperationsTest {
}
private String readFromInputStream(InputStream inputStream) throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder resultStringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line);
resultStringBuilder.append("\n");
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return resultStringBuilder.toString();
}
}

View File

@ -0,0 +1 @@
hello world

View File

@ -1,45 +1,172 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import play.mvc.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import model.Student;
import play.test.*;
import play.data.DynamicForm;
import play.data.validation.ValidationError;
import play.data.validation.Constraints.RequiredValidator;
import play.i18n.Lang;
import play.libs.F;
import play.libs.F.*;
import play.twirl.api.Content;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
/**
*
* Simple (JUnit) tests that can call all parts of a play app.
* If you are interested in mocking a whole application, see the wiki for more details.
*
*/
public class ApplicationTest {
@Test
public void simpleCheck() {
int a = 1 + 1;
assertEquals(2, a);
}
@Test
public void renderTemplate() {
Content html = views.html.index.render("Your new application is ready.");
assertEquals("text/html", html.contentType());
assertTrue(html.body().contains("Your new application is ready."));
}
public class ApplicationTest{
private static final String BASE_URL = "http://localhost:9000";
@Test
public void testInServer() throws Exception {
TestServer server = testServer(3333);
running(server, () -> {
try {
WSClient ws = play.libs.ws.WS.newClient(3333);
CompletionStage<WSResponse> completionStage = ws.url("/").get();
WSResponse response = completionStage.toCompletableFuture().get();
ws.close();
assertEquals(OK, response.getStatus());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
});
}
@Test
public void whenCreatesRecord_thenCorrect() {
Student student = new Student("jody", "west", 50);
JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student)));
assertTrue(obj.getBoolean("isSuccessfull"));
JSONObject body = obj.getJSONObject("body");
assertEquals(student.getAge(), body.getInt("age"));
assertEquals(student.getFirstName(), body.getString("firstName"));
assertEquals(student.getLastName(), body.getString("lastName"));
}
@Test
public void whenDeletesCreatedRecord_thenCorrect() {
Student student = new Student("Usain", "Bolt", 25);
JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
int id = ob1.getInt("id");
JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
assertTrue(obj1.getBoolean("isSuccessfull"));
makeRequest(BASE_URL + "/" + id, "DELETE", null);
JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject()));
assertFalse(obj2.getBoolean("isSuccessfull"));
}
@Test
public void whenUpdatesCreatedRecord_thenCorrect() {
Student student = new Student("john", "doe", 50);
JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body");
assertEquals(student.getAge(), body1.getInt("age"));
int newAge = 60;
body1.put("age", newAge);
JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body");
assertFalse(student.getAge() == body2.getInt("age"));
assertTrue(newAge == body2.getInt("age"));
}
@Test
public void whenGetsAllRecords_thenCorrect() {
Student student1 = new Student("jane", "daisy", 50);
Student student2 = new Student("john", "daniel", 60);
Student student3 = new Student("don", "mason", 55);
Student student4 = new Student("scarlet", "ohara", 90);
makeRequest(BASE_URL, "POST", new JSONObject(student1));
makeRequest(BASE_URL, "POST", new JSONObject(student2));
makeRequest(BASE_URL, "POST", new JSONObject(student3));
makeRequest(BASE_URL, "POST", new JSONObject(student4));
JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null));
assertTrue(objects.getBoolean("isSuccessfull"));
JSONArray array = objects.getJSONArray("body");
assertTrue(array.length() >= 4);
}
public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) {
URL url = null;
try {
url = new URL(myUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream dos = null;
int respCode = 0;
String inputString = null;
try {
conn.setRequestMethod(httpMethod);
if (Arrays.asList("POST", "PUT").contains(httpMethod)) {
String params = parameters.toString();
conn.setDoOutput(true);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(params);
dos.flush();
dos.close();
}
respCode = conn.getResponseCode();
if (respCode != 200 && respCode != 201) {
String error = inputStreamToString(conn.getErrorStream());
return error;
}
inputString = inputStreamToString(conn.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return inputString;
}
public static String inputStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

View File

@ -1,25 +0,0 @@
import org.junit.*;
import play.mvc.*;
import play.test.*;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
import static org.fluentlenium.core.filter.FilterConstructor.*;
public class IntegrationTest {
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> {
browser.goTo("http://localhost:3333");
assertTrue(browser.pageSource().contains("Your new application is ready."));
});
}
}

View File

@ -26,6 +26,12 @@
<artifactId>activemq-all</artifactId>
<version>${activemq.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -36,8 +42,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
@ -52,6 +58,16 @@
</plugin>
</plugins>
</pluginManagement>
<finalName>spring-jms</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<finalName>spring-jms</finalName>
</build>
</project>

View File

@ -18,6 +18,6 @@ public class Employee {
}
public String toString() {
return "Person: name(" + name + "), age(" + age + ")";
return "Employee: name(" + name + "), age(" + age + ")";
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.spring.jms;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.net.URI;
public class SampleJMSExample {
public static void main(String[] args) throws Exception {
BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:61616)"));
broker.start();
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}

View File

@ -1,17 +1,18 @@
package com.baeldung.spring.jms;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.*;
import javax.jms.Queue;
import java.util.HashMap;
import java.util.Map;
public class SampleJmsMessageSender {
private JmsTemplate jmsTemplate;
private Queue queue;
public void createJmsTemplate(ConnectionFactory cf) {
this.jmsTemplate = new JmsTemplate(cf);
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public void setQueue(Queue queue) {
@ -19,10 +20,14 @@ public class SampleJmsMessageSender {
}
public void simpleSend() {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("hello queue world");
}
});
jmsTemplate.send(queue, s -> s.createTextMessage("hello queue world"));
}
public void sendMessage(final Employee employee) {
System.out.println("Jms Message Sender : " + employee);
Map<String, Object> map = new HashMap<>();
map.put("name", employee.getName());
map.put("age", employee.getAge());
this.jmsTemplate.convertAndSend(map);
}
}

View File

@ -1,18 +1,25 @@
package com.baeldung.spring.jms;
import org.springframework.jms.core.JmsTemplate;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.Map;
public class SampleListener implements MessageListener {
private String textMessage;
public JmsTemplate getJmsTemplate() {
return getJmsTemplate();
}
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
textMessage = ((TextMessage) message).getText();
String msg = ((TextMessage) message).getText();
System.out.println("Message has been consumed : " + msg);
} catch (JMSException ex) {
throw new RuntimeException(ex);
}
@ -20,4 +27,9 @@ public class SampleListener implements MessageListener {
throw new IllegalArgumentException("Message Error");
}
}
public Employee receiveMessage() throws JMSException {
Map map = (Map) getJmsTemplate().receiveAndConvert();
return new Employee((String) map.get("name"), (Integer) map.get("age"));
}
}

View File

@ -11,10 +11,10 @@ import javax.jms.Session;
public class SampleMessageConverter implements MessageConverter {
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
Employee person = (Employee) object;
Employee employee = (Employee) object;
MapMessage message = session.createMapMessage();
message.setString("name", person.getName());
message.setInt("age", person.getAge());
message.setString("name", employee.getName());
message.setInt("age", employee.getAge());
return message;
}

View File

@ -0,0 +1,18 @@
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xmlns:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Embedded ActiveMQ Broker -->
<amq:broker id="broker" useJmx="false" persistent="false">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:61616" />
</amq:transportConnectors>
</amq:broker>
</beans>

View File

@ -3,16 +3,27 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="messageDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="messageQueue1" />
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="receiveTimeout" value="10000" />
</bean>
<bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg index="0" value="tcp://localhost:61616" />
</bean>
<!-- ConnectionFactory Definition -->
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>
<bean id="destinationQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="IN_QUEUE" />
</bean>
<!-- JmsTemplate Definition -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="destinationQueue" />
</bean>
<bean id="SampleJmsMessageSender" class="com.baeldung.spring.jms.SampleJmsMessageSender">
<property name="destination" ref="messageDestination" />
<property name="queue" ref="destinationQueue" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
@ -23,8 +34,7 @@
<bean id="jmsContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="messageDestination" />
<property name="destinationName" value="IN_QUEUE" />
<property name="messageListener" ref="messageListener" />
<property name="jmsTemplate" ref="jmsTemplate" />
</bean>
</beans>

View File

@ -0,0 +1,25 @@
package com.baeldung.spring.jms;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DefaultTextMessageSenderTest {
private static SampleJmsMessageSender messageProducer;
@SuppressWarnings("resource")
@BeforeClass
public static void setUp() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
}
@Test
public void testSimpleSend() {
messageProducer.simpleSend();
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.spring.jms;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MapMessageConvertAndSendTest {
private static SampleJmsMessageSender messageProducer;
@SuppressWarnings("resource")
@BeforeClass
public static void setUp() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
}
@Test
public void testSendMessage() {
messageProducer.sendMessage(new Employee("JavaDeveloper2", 22));
}
}

View File

@ -2,7 +2,7 @@ package com.baeldung.wicket.examples;
import org.apache.wicket.markup.html.WebPage;
public class Examples extends WebPage {
public class HelloWorld extends WebPage {
private static final long serialVersionUID = 1L;

View File

@ -4,15 +4,14 @@ import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
import com.baeldung.wicket.examples.cafeaddress.CafeAddress;
import com.baeldung.wicket.examples.helloworld.HelloWorld;
public class ExamplesApplication extends WebApplication {
public class HelloWorldApplication extends WebApplication {
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage() {
return Examples.class;
return HelloWorld.class;
}
/**

View File

@ -1,10 +1,5 @@
package com.baeldung.wicket.examples.cafeaddress;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.WebPage;
@ -13,29 +8,29 @@ import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class CafeAddress extends WebPage {
private static final long serialVersionUID = 1L;
String selectedCafe;
Address address;
Map<String, Address> cafeNamesAndAddresses = new HashMap<>();
private String selectedCafe;
private Address address;
private Map<String, Address> cafeNamesAndAddresses = new HashMap<>();
public CafeAddress(final PageParameters parameters) {
super(parameters);
initCafes();
ArrayList<String> cafeNames = new ArrayList<>(this.cafeNamesAndAddresses.keySet());
this.selectedCafe = cafeNames.get(0);
this.address = new Address(this.cafeNamesAndAddresses.get(this.selectedCafe).getAddress());
ArrayList<String> cafeNames = new ArrayList<>(cafeNamesAndAddresses.keySet());
selectedCafe = cafeNames.get(0);
address = new Address(cafeNamesAndAddresses.get(selectedCafe).getAddress());
final Label addressLabel = new Label("address", new PropertyModel<String>(this.address, "address"));
addressLabel.setOutputMarkupId(true);
final DropDownChoice<String> cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<String>(this, "selectedCafe"), cafeNames);
final DropDownChoice<String> cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<>(this, "selectedCafe"), cafeNames);
cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
String name = (String) cafeDropdown.getDefaultModel().getObject();
@ -61,11 +56,11 @@ public class CafeAddress extends WebPage {
this.sAddress = address;
}
public String getAddress() {
String getAddress() {
return this.sAddress;
}
public void setAddress(String address) {
void setAddress(String address) {
this.sAddress = address;
}
}

View File

@ -4,9 +4,6 @@ import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
public class HelloWorld extends WebPage {
private static final long serialVersionUID = 1L;
public HelloWorld() {
add(new Label("hello", "Hello World!"));
}

View File

@ -9,15 +9,15 @@ public class TestHomePage {
@Before
public void setUp() {
tester = new WicketTester(new ExamplesApplication());
tester = new WicketTester(new HelloWorldApplication());
}
@Test
public void whenPageInvoked_thanRenderedOK() {
//start and render the test page
tester.startPage(Examples.class);
tester.startPage(HelloWorld.class);
//assert rendered page class
tester.assertRenderedPage(Examples.class);
tester.assertRenderedPage(HelloWorld.class);
}
}

View File

@ -21,7 +21,7 @@
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>com.baeldung.wicket.examples.ExamplesApplication</param-value>
<param-value>com.baeldung.wicket.examples.HelloWorldApplication</param-value>
</init-param>
</filter>