Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
178aa88
Moved code from spring-boot to testing-modules/mockito
priyeshmashelkar Jul 6, 2018
8e3fdf0
Merge branch 'master' of https://github.com/priyeshmashelkar/tutorials
priyeshmashelkar Jul 6, 2018
14a571a
[BAEL-1835] Creating empty Maven Java project with compiler plugin
Jul 6, 2018
3a9ca3b
[BAEL-1835] Adding dummy application and Java service
Jul 6, 2018
0810f9f
[BAEL-1835] Added packaging jar to pom
Jul 6, 2018
2059cb1
[BAEL-1835] Updated pom to handle Kotlin and Java sources compiling
Jul 6, 2018
b9e6222
[BAEL-1835] Added dummy KotlinService
Jul 7, 2018
60702c1
[BAEL-1835] Fixing indent and organization
Jul 7, 2018
41b8473
Merge remote-tracking branch 'eugenp/master'
Doha2012 Jul 7, 2018
a373d08
BAEL-1691 comparing embedded servlet containers in spring boot
chrisoberle Jul 8, 2018
9b27ab5
upgrade to spring boot 2
Doha2012 Jul 9, 2018
66f2263
add new is to string test
lor6 Jul 9, 2018
5abfd44
fix parent
Doha2012 Jul 9, 2018
b7b6eca
BAEL-1911 - Spring Session with JDBC
aravind-r-ranganathan Jul 10, 2018
0ad3423
how to trigger and stop scheduled batch job (#4671)
mmchsusan Jul 10, 2018
f959cbe
Merge pull request #4672 from Doha2012/master
lor6 Jul 10, 2018
d9d8f16
Fixed spring-mvc-java, spring-cloud-rest-discovery-server apache-solr…
amit2103 Jul 10, 2018
fed95f4
Merge branch 'master' into master
lor6 Jul 10, 2018
30fef21
Merge pull request #4649 from FDPro/master
lor6 Jul 10, 2018
6444267
PR for last fixes after editors review (#4678)
cmlavila Jul 10, 2018
c3cc97e
Merge pull request #4675 from eugenp/is-string
lor6 Jul 10, 2018
2022b7f
Merge pull request #4665 from chrisoberle/master
thombergs Jul 10, 2018
a3f6ad6
Renamed unit test
priyeshmashelkar Jul 10, 2018
cab2e35
Merge pull request #4682 from priyeshmashelkar/master
thombergs Jul 11, 2018
7ab2a2c
moven kotlin-maven project
lor6 Jul 11, 2018
1a6c4e8
Merge pull request #4685 from eugenp/BAEL-1835-v2
lor6 Jul 11, 2018
2c1fe27
BAEL-1795 add link back to article (#4684)
KevinGilmore Jul 11, 2018
5c7c8f4
BAEL-1911 - Spring Session with JDBC
aravind-r-ranganathan Jul 10, 2018
04084e3
Merge branch 'master' of https://github.com/aravindram87/tutorials-1
aravind-r-ranganathan Jul 12, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import org.junit.Before;
import org.junit.Test;

public class SolrJavaIntegrationTest {
public class SolrJavaLiveTest {

private SolrJavaIntegration solrJavaIntegration;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
Expand Down Expand Up @@ -111,6 +113,19 @@ public final void givenUsingCommonsIoWithCopy_whenConvertingAnInputStreamToAStri

assertThat(writer.toString(), equalTo(originalString));
}

@Test
public final void givenUsingTempFile_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());

// When
Path tempFile = java.nio.file.Files.createTempDirectory("").resolve(UUID.randomUUID().toString() + ".tmp");
java.nio.file.Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
String result = new String(java.nio.file.Files.readAllBytes(tempFile));

assertThat(result, equalTo(originalString));
}

// tests - InputStream to byte[]

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.baeldung.mavenjavakotlin;

import com.baeldung.mavenjavakotlin.services.JavaService;
import com.baeldung.mavenjavakotlin.services.KotlinService;

public class Application {

private static final String JAVA = "java";
private static final String KOTLIN = "kotlin";

public static void main(String[] args) {
String language = args[0];
switch (language) {
case JAVA:
new JavaService().sayHello();
break;
case KOTLIN:
new KotlinService().sayHello();
break;
default:
// Do nothing
break;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.baeldung.mavenjavakotlin.services;

public class JavaService {

public void sayHello() {
System.out.println("Java says 'Hello World!'");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.baeldung.mavenjavakotlin.services

class KotlinService {

fun sayHello() {
System.out.println("Kotlin says 'Hello World!'")
}

}
21 changes: 21 additions & 0 deletions ejb/wildfly/wildfly-mdb/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>widlfly-mdb</artifactId>

<parent>
<groupId>com.baeldung.wildfly</groupId>
<artifactId>wildfly-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>

<dependencies>
<!-- Dependency for java ee -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.baeldung.wildfly.mdb;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
* Message-Driven Bean implementation class for: ReadMessageMDB
*/
@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName = "destination", propertyValue = "tutorialQueue"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class ReadMessageMDB implements MessageListener {

public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("Message received: " + textMessage.getText());
} catch (JMSException e) {
System.out.println("Error while trying to consume messages: " + e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package baeldung.com.example.servlet;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/SendMessageServlet")
public class SendMessageServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String text = req.getParameter("text") != null ? req.getParameter("text") : "Hello World";

try (
Context ic = new InitialContext();

ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
Queue queue = (Queue) ic.lookup("queue/tutorialQueue");

Connection connection = cf.createConnection();
) {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer publisher = session.createProducer(queue);

connection.start();

TextMessage message = session.createTextMessage(text);
publisher.send(message);

} catch (NamingException | JMSException e) {
res.getWriter().println("Error while trying to send <" + text + "> message: " + e.getMessage());
}

res.getWriter().println("Message sent: " + text);
}

}
1 change: 1 addition & 0 deletions javax-servlets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file)
- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response)
- [Java EE Servlet Exception Handling](http://www.baeldung.com/servlet-exceptions)
- [Context and Servlet Initialization Parameters](http://www.baeldung.com/context-servlet-initialization-param)
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<context:annotation-config />
<context:component-scan base-package="org.baeldung.persistence" />
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
<context:property-placeholder location="classpath:persistence-h2.properties"/>



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>

<context:property-placeholder location="classpath:persistence-mysql.properties"/>
<context:property-placeholder location="classpath:persistence-h2.properties"/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@
<module>java-ee-8-security-api</module>
<module>spring-webflux-amqp</module>
<module>antlr</module>
<module>maven-archetype</module>
<module>maven-archetype</module>
<module>apache-meecrowave</module>
</modules>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package org.baeldung.batchscheduler;

import java.util.Date;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;

import org.baeldung.batchscheduler.model.Book;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.ScheduledMethodRunnable;

@Configuration
@EnableBatchProcessing
@EnableScheduling
public class SpringBatchScheduler {

private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class);

private AtomicBoolean enabled = new AtomicBoolean(true);

private Date currentLaunchDate;

private final Map<Object, ScheduledFuture<?>> scheduledTasks = new IdentityHashMap<>();

@Autowired
private JobBuilderFactory jobBuilderFactory;

@Autowired
private StepBuilderFactory stepBuilderFactory;

@Scheduled(fixedRate = 2000)
public void launchJob() throws Exception {
Date date = new Date();
logger.debug("scheduler starts at " + date);
if (enabled.get()) {
currentLaunchDate = date;
JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", currentLaunchDate)
.toJobParameters());
logger.debug("Batch job ends with status as " + jobExecution.getStatus());
}
logger.debug("scheduler ends ");
}

public Date getCurrentLaunchDate() {
return currentLaunchDate;
}

public void stop() {
enabled.set(false);
}

public void start() {
enabled.set(true);
}

@Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}

private class CustomTaskScheduler extends ThreadPoolTaskScheduler {

private static final long serialVersionUID = -7142624085505040603L;

@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);

ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);

return future;
}

}

public void cancelFutureSchedulerTasks() {
scheduledTasks.forEach((k, v) -> {
if (k instanceof SpringBatchScheduler) {
v.cancel(false);
}
});
}

@Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(readBooks())
.build();
}

@Bean
public JobLauncher jobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}

@Bean
public JobRepository jobRepository() throws Exception {
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean();
factory.setTransactionManager(new ResourcelessTransactionManager());
return (JobRepository) factory.getObject();
}

@Bean
protected Step readBooks() {
return stepBuilderFactory.get("readBooks")
.<Book, Book> chunk(2)
.reader(reader())
.writer(writer())
.build();
}

@Bean
public FlatFileItemReader<Book> reader() {
return new FlatFileItemReaderBuilder<Book>().name("bookItemReader")
.resource(new ClassPathResource("books.csv"))
.delimited()
.names(new String[] { "id", "name" })
.fieldSetMapper(new BeanWrapperFieldSetMapper<Book>() {
{
setTargetType(Book.class);
}
})
.build();
}

@Bean
public ItemWriter<Book> writer() {
return new ItemWriter<Book>() {

@Override
public void write(List<? extends Book> items) throws Exception {
logger.debug("writer..." + items.size());
for (Book item : items) {
logger.debug(item.toString());
}

}
};
}

}
Loading