Spring batch job parameters - configuration

My Spring batch configuration is below:
#Configuration
public class SampleConfiguration1 {
#Autowired
protected JobBuilderFactory jobBuilderFactory;
#Autowired
protected StepBuilderFactory stepBuilderFactory;
#Bean
public Job job1() throws Exception {
//how can I get job parameters here
return jobBuilderFactory.get("job1")
.start(step1())
.next(step2())
.build();
}
#Bean
public Step step1() {}
#Bean
public Step step2() {}
}
My application
#EnableBatchProcessing
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
When I run my job like below:
java -jar sample.jar parameterkey=parameterValue
My question is how can I get job parameters in job1()? thanks

Related

How to rollback Rabbit-mq message after Junit test?

When you test your code, you send a message to rabbit-mq. How do you get the message back when the test is over?
public interface RabbitProducer {
String OUTPUT = "rabbitmq_producer_channel";
#Output(OUTPUT)
MessageChannel output();
}
public class SysGroupServiceImpl {
#Autowired
private RabbitProducer rabbitProducer;
#Override
public Result remove(Collection<? extends Serializable> idList) {
rabbitProducer.output().send(MessageBuilder.withPayload(idList)
.setHeader("x-delay", 5000)
.setHeader("MessageType", "GroupBatchDelete").build());
return Result.booleanResult(true);
}
}
#SpringBootTest
#Transactional
#Rollback
public class SysGroupServiceTest {
#Autowired
private SysGroupService sysGroupService;
#Test
void removeTest(){
sysGroupService.remove(Stream.of("1").collect(Collectors.toList()));
}
}
I use Spring Cloud Stream to be compatible with RabbitMQ, and all the relevant code is there.Is there a way to mock this out?I tried the following scheme, but due to X-dealy, I got this error:No exchange type x-delayed-message
<dependency>
<groupId>com.github.fridujo</groupId>
<artifactId>rabbitmq-mock</artifactId>
</dependency>
#Component
public class RabbitMqMock {
#Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(MockConnectionFactoryFactory.build());
}
}
I know little about mocks. Can mocks create an X-delay exchange?

How to write proper JUnit test case rest controllers

I want to write JUnit test case rest controller using mockito framework. I want to know how to write test cases for http request like get and post. Also how to test api which uploads a document.
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
#RunWith(MockitoJUnitRunner.class)
#WebMvcTest
#AutoConfigureMockMvc
public class ControllerTest {
#Autowired
private MockMvc mvc;
#Mock
Service service;
#InjectMocks
private Controller controller;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
mvc = MockMvcBuilders.standaloneSetup(marketplaceCatalogController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
#Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
}).build();
}
#Test
public void testGetMethod() throws Exception {
when(service.getMethod(Mockito.any(SomeClass.class))).thenReturn(new SomeOtherClass);
doNothing().when(service).someMethod();
mvc.perform(get("/get-method").param("paramKey",
"paramValue")).andExpect(status().isOk()).andDo(print());
}
#Test
public void testStatusTnC() throws Exception {
String payload = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
mvc.perform(post("/post-method").content(payload)).andExpect(status().isOk()).andDo(print());
}
#Test
public void testUploadFile() throws Exception {
when(service.uploadSomeContent(any(), any(), anyString(), anyString())).thenReturn(new SomeClass());
mvc.perform(fileUpload("/post-request/uploadFile").file("somefile", "Hello, World!".getBytes()).param("param1", "value1").contentType(MediaType.MULTIPART_FORM_DATA)).andExpect(status().isOk()).andDo(print());
}
}

I need to write JUNIT for Apache camel route

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

How to write JUnit Test case

I am learning Junit testing on spring boot Application. my account controller method is depend on service class method. For that I used Mockito. I tried simple But here I am not getting how to write test case for following method? How I can use mockito.
can any one please help me for writing this test case?
AccountController
#RestController
#RequestMapping("/spacestudy/$ {InstituteIdentifier}/admin/account")
public class AccountController {
#Autowired
AccountService accService;
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
//????
//????
}
}
It will be something like this:
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
when(accountService.populateGridViews("foo","bar")).thenReturn(Arrays.asList(new Tuple("bazz"));
mockMvc.perform(get("/spacestudy/STACKOVERFLOW/admin/account/foo/bar"))
.andExpect(status().isOk())
.andExpect(jsonPath("someField").value("bazz"));
}
}
So basically you are replacing your service with mock and saying what it should return. In your particular case I don't see any reasons for unit testing this class, since it doesn't have any logic inside. But if you would have something like:
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(...) throws Exception {
List<Tuple> result = accService.populateGridViews(...);
if(result==null){
return ResponseEntity.notFound();
}
return ResponseEntity.ok(result);
}
Then it would make more sense to test this class e.g.
1st test - mock your accService to return null and verify that response status is 404
2nd test - mock your accService to return not null and verify that response status is 200

How to use MySQL and neo4j in single spring-boot application

I have created application with spring-boot and neo4j. Following is spring boot application with neo4j
#Configuration
#ComponentScan({ "myproject" })
#EnableAutoConfiguration
#EnableNeo4jRepositories(basePackages = "myproject")
public class Neo4jServer extends Neo4jConfiguration implements CommandLineRunner
{
public Server()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
public void run(String... args) throws Exception
{
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(Neo4jServer.class, args);
}
}
AND following is spring boot application with mysql
#Configuration
#ComponentScan({ "myproject" })
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages = "myproject.persistence")
#PropertySource("myproject.properties")
public class MySQLServer extends DataSourceAutoConfiguration implements CommandLineRunner
{
public void run(String... args) throws Exception
{
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(MySQLServer.class, args);
}
}
I have created properties file in resource package.
spring.datasource.url=jdbc:mysql://localhost:3306/myDB
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
So, There are now two application, one is with neo4j ie Neo4jServer.java and one is with MySQL ie MySQLServer.java
How to use both in single application.
Please make me correct if wrong.
Thank you :)
Need to inject MySQL configured DataSource/TransactionManager bean to application class. MySQL Entities/DAO and Neo4j Node/Relationship/DAO needs to be in different packages. Then you can provide those respective packages for scan to MySQL and Neo4j.
Following code shows the configuration :
#Configuration
#ComponentScan({ "myproject" })
#EnableJpaRepositories(basePackages = "myproject.persistence.mysql")
#EnableAutoConfiguration
#EnableNeo4jRepositories(basePackages = "myproject.persistence.neo4j")
public class Application extends Neo4jConfiguration
{
#Autowired
LocalContainerEntityManagerFactoryBean entityManagerFactory;
public Application()
{
setBasePackage("myproject.persistence.neo4j");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
#Bean(destroyMethod = "close")
public DataSource dataSource()
{
DataSource dataSource = new DataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/dbname");
dataSource.setUsername("mysqluser");
dataSource.setPassword("mysqlpassword");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setPackagesToScan("myproject.persistence.mysql");
entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
Map<String, String> jpaProperties = new HashMap<String, String>();
jpaProperties.put("hibernate.connection.charSet", "UTF-8");
jpaProperties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.EJB3NamingStrategy");
jpaProperties.put("hibernate.bytecode.provider", "javassist");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
entityManagerFactory.setJpaPropertyMap(jpaProperties);
entityManagerFactory.setPersistenceProvider(new HibernatePersistence());
return entityManagerFactory;
}
#Override
#Bean(name = "transactionManager")
public PlatformTransactionManager neo4jTransactionManager() throws Exception
{
return new ChainedTransactionManager(new JpaTransactionManager(entityManagerFactory.getObject()),
new JtaTransactionManagerFactoryBean(graphDatabaseService()).getObject());
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
{
return new PersistenceExceptionTranslationPostProcessor();
}
}