How to use Spring boot for local simple project? - java

That's a bit silly, but I'm really missing the point here. I have a Spring Boot working app, the main Application class is
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
It it is from this https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate great and simple example.
It has a controller for http requests which says
#RequestMapping("/create")
#ResponseBody
public String create(String email, String name) {
User user = null;
try {
user = new User(email, name);
userDao.save(user);
}
catch (Exception ex) {
return "Error creating the user: " + ex.toString();
}
return "User succesfully created! (id = " + user.getId() + ")";
}
My question is, how do I use it like my simple local application with some logic in main() mwthod?
I tried something like
new UserController().create("test#test.test", "Test User");
but it doesn't work, though I get no errors. I just don't need any http requests/responses.

Once your application is running and your UserController() is ready to accept requested if it annotated by #Controller you can call the create method by url
ex. localhost:8080/create providing email, name as request parameters

Yes you can create sprint boot command line application.
please add the below method in Application class of spring boot
#Autowired
private UserServiceImpl userServiceImpl;
#Bean
public CommandLineRunner commandLineRunner(ApplicationContext context) {
return ((String...args) -> {
/**
*
* Call any methods of service class
*
*/
userServiceImpl.create();
});
}

Related

datasource.getConnection() not working in Springboot application

My db properties are kept in application-test.properties (I am running Springboot application in test profile) and the Datasource is referred through #Autowired annotation. It throws NullPointerException when I try to use datasource.getConnection().
I have referred similar questions and mostly all of them include some solutions with bean xml configurations. In my case I am not explicitly using any bean configurations. Every datasource properties are kept in application-test.properties file and I am referring through it using Datasource. I am a newbie to Springboot and any help would be great.
My repository class
#Repository
public class ActualUserDetailsDAO {
#Autowired
DataSource dataSource;
public String getPriorityType(String idNo) throws Exception {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String cxPriorityType = null;
int count = 0;
try {
con = dataSource.getConnection();
String sql = ConfigurationHandler.getInstance().getConfigValue("sample.query");
......................
} catch (SQLException e) {
................
} catch (Exception e) {
..............
} finally {
.................
}
return cxPriorityType;
}
My application properties
spring.main.banner-mode=off
server.port=8180
# Datasource settings
spring.datasource.initialize=true
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.name=camst2
spring.datasource.url=jdbc:oracle:thin:#..................
spring.datasource.username=username
spring.datasource.password=password
# Tomcat JDBC settings
spring.datasource.tomcat.initial-size=10
spring.datasource.tomcat.max-active=100
spring.datasource.tomcat.min-idle=10
spring.datasource.tomcat.max-idle=100
#spring.datasource.tomcat.max-wait=6000
spring.datasource.tomcat.max-wait=30000
#spring.datasource.tomcat.test-on-connect=true
#spring.datasource.tomcat.test-on-borrow=true
#spring.datasource.tomcat.test-on-return=true
# Tomcat AccessLog
server.tomcat.accesslog.suffix=.log
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.directory=/tomcat/logs
server.tomcat.accesslog.pattern=%h %l %u %t %r %s %b %D
My application class
#SpringBootApplication
public class Application {
#Autowired
DataSource dataSource;
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
I found the solution. The problem was in my controller class. I was creating an instance of the my repository class by myself. I should have used #Autowired instead.
#RestController
public class ActualUserDetails implements ActualUserDetailsInt {
#RequestMapping(value = "/foo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getActualUserDetails(#PathVariable("idNo") String idNo, #RequestParam("lob") String lob,
#RequestParam("offerSellingType") String offerSellingType) {
//do something
ActualUserDetailsDAO actualUserDetailsDAO = new ActualUserDetailsDAO();
actualUserDetailsDAO.getPriorityType(idNo);
//do something
I changed this into following.
#RestController
public class ActualUserDetails implements ActualUserDetailsInt {
#Autowired
ActualUserDetailsDAO actualUserDetailsDAO;
#RequestMapping(value = "/foo", method = RequestMethod.GET, produces =
MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getActualUserDetails(#PathVariable("idNo") String idNo,
#RequestParam("lob") String lob,
#RequestParam("offerSellingType") String offerSellingType) {
//do something
actualUserDetailsDAO.getPriorityType(idNo);
//do something
Manually creating object of my repository class did not detected dataSource defined inside it. Autowiring my repository class in my controller class seems to solve this problem.
If your data source is not been detected for any reason, I strongly recommend to have a deeper look on your code.
Following are some of the things to look for when this kind of error happens.
Look for the correct folder structure (application properties file
reside under resources folder)
If you are running Spring in a different profile (say test
profile), make sure relevant configurations are written in
application-test.properties
Check for proper annotation in relevant classes
Make sure your application properties are not overridden by any other
configurations

Spring Boot - How to start my Spring Boot Application from sister module in a multi-module project?

I have a multi-module project with two projects: backend and client. The backend is a normal Spring Boot Rest API, nothing special. The client module is just a Java Library using the Rest API.
The backend has packaging of "war" as the backend as it uses JSPs, too and needs to be deployed to a servlet container. The backend is still easily testable with #SpringBootTest.
Now I want to have some integration tests inside the client module using the backend module as a sandbox server.
To use all the backend classes in the client module I added
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<attachClasses>true</attachClasses>
</configuration>
</plugin>
and configured the backend as a test dependency in client with classes
In my client/src/test/java I have a helper class which starts up the backend module
#Configuration
public class SandboxServer {
#Bean
public ConfigurableApplicationContext backend() {
return
new SpringApplicationBuilder(BackendApplication.class)
.sources(SandboxServerConfig.class)
.run("spring.profiles.active=sandbox")
}
}
The profile "sandbox" is used to setup a test database etc. But I had more problems. First problem was regarding the document root, so I configured it:
public class SandboxServerConfig
implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
#Override
public void customize(TomcatServletWebServerFactory factory) {
factory.setDocumentRoot(new File("../backend/src/main/webapp"));
}
}
But it still does not work as Spring is not picking up backend/src/main/resources/application.properties
That might be correct as it is not in the root classpath of the client module.
So it does not really work. I guess it is not possible to just start up the sibling module in an Integration test.
How can I achieve to start up the sibling spring boot module for integration testing? What is the best practice for szenarios like this?
You can override the application.properties location using TestPropertySource like this:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = BlaApplication.class)
#TestPropertySource(locations="/path/to/backend/src/main/resources/application.properties")
public class ExampleApplicationTests {
}
I found a much more solid solution. In my sibling Project "frontend" I have a Component which is starting up the backend server in integration mode if and only if it is not already running.
Benefits:
The real WAR is tested
You can start the WAR before in your IDE and let the tests run fast
If you run it with maven it is started up before all tests only once
No build configuration needed (like pre-integration in maven)
process is seperated from Junit runtime so no hassle with complex setups.
Drawbacks:
You need to build the package before you can run any integration test in the frontend. But hey, you should build your package before you test it. That's what integration test is all about.
And here is my SandboxServerProcess.class.
import org.springframework.stereotype.Component;
import javax.annotation.*;
import javax.annotation.*;
import java.io.*;
import java.net.*;
import java.util.*;
#Component
#Profile("integration")
public class SandboxServerProcess {
private static final String WAR = "../backend/target/backend.war";
private final static int PORT = 8081;
private boolean startedByMe;
#PostConstruct
public void start() throws Exception {
if (isStarted()) {
return;
}
testWarExists();
packagedWar("start");
if (waitForStartup()) {
startedByMe = true;
return;
}
throw new RuntimeException("Sandbox Server not started");
}
private void testWarExists() {
File file = new File(WAR);
if (!file.exists()) {
throw new RuntimeException("WAR does not exist:" + file.getAbsolutePath());
}
}
#PreDestroy
public void stop() throws IOException {
if (startedByMe) {
packagedWar("stop");
}
}
private void packagedWar(String command) throws IOException {
ProcessBuilder builder = new ProcessBuilder();
builder.environment().put("MODE", "service");
builder.environment().put("SPRING_PROFILES_ACTIVE", "integration");
builder.environment().put("APP_NAME", "backend");
builder.environment().put("PID_FOLDER", "./");
builder.environment().put("LOG_FOLDER", "./");
List<String> commands = new ArrayList<>();
commands.add(WAR);
commands.add(command);
builder.command(commands);
builder.inheritIO();
builder.redirectErrorStream(true);
builder.start();
}
private boolean isStarted() {
try {
Socket socket = new Socket();
InetSocketAddress sa = new InetSocketAddress("localhost", PORT);
socket.connect(sa, 500);
logger.warn("SandboxServer is started");
return true;
} catch (IOException e) {
return false;
}
}
private boolean waitForStartup() throws InterruptedException {
for (int i = 1; i < 30; i++) {
if (isStarted()) {
return true;
}
logger.warn("SandboxServer not yet ready, tries: " + i);
Thread.sleep(1000);
}
return false;
}
}

Spring-Data-Neo4J: How do log into the remote server?

I'm using Spring-Data-Neo4j 4.0.0.M1, and trying to connect to the server. I'm getting an exception:
Caused by: org.apache.http.client.HttpResponseException: Unauthorized
I have a password on the server interface, but I'm not sure how to tell Spring about it.
#Configuration
#EnableNeo4jRepositories(basePackages = "com.noxgroup.nitro.persistence")
#EnableTransactionManagement
public class MyConfiguration extends Neo4jConfiguration {
#Bean
public Neo4jServer neo4jServer () {
/*** I was quite surprised not to see an overloaded parameter here ***/
return new RemoteServer("http://localhost:7474");
}
#Bean
public SessionFactory getSessionFactory() {
return new SessionFactory("org.my.software.domain");
}
#Bean
ApplicationListener<BeforeSaveEvent> beforeSaveEventApplicationListener() {
return new ApplicationListener<BeforeSaveEvent>() {
#Override
public void onApplicationEvent(BeforeSaveEvent event) {
if (event.getEntity() instanceof User) {
User user = (User) event.getEntity();
user.encodePassword();
}
}
};
}
}
Side Note
4.0.0 Milestone 1 is absolutely fantastic. If anyone is using 3.x.x, I'd recommend checking it out!
The username and password are passed currently via system properties
e.g.
-Drun.jvmArguments="-Dusername=<usr> -Dpassword=<pwd>"
or
System.setProperty("username", "neo4j");
System.setProperty("password", "password");
https://jira.spring.io/browse/DATAGRAPH-627 is open (not targeted for 4.0 RC1 though), please feel free to add comments/vote it up

JMX process, is it possible to call an external application to handle access rights when client attempts access

I have an application that is running on localhost:1234, I am using jconsole to connect to this. The application has a password file to handle login.
I need to allow logging in based on different AD groups of the windows user. So for example, if they are in Group1 they will be given readwrite access, if they are Group2 they are given readonly access, and group3 is not given and access.
I have created an AD group handling application that can query a list of AD groups and return the required user access level and login details.
My problem: I want to connect to the application using jconsole via the command line using something like:
jconsole localhost:1234
Obviously this will fail to connect, because it's expecting a username and password.
Is there a way in which I can have my JMX application that's running on localhost:1234 wait for an incoming connection request and run my AD group handling application to determine their access level?
My application on localhost:1234 is very basic and looks like this:
import java.lang.management.ManagementFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
public class SystemConfigManagement {
private static final int DEFAULT_NO_THREADS = 10;
private static final String DEFAULT_SCHEMA = "default";
public static void main(String[] args)
throws MalformedObjectNameException, InterruptedException,
InstanceAlreadyExistsException, MBeanRegistrationException,
NotCompliantMBeanException{
//Get the MBean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//register the mBean
SystemConfig mBean = new SystemConfig(DEFAULT_NO_THREADS, DEFAULT_SCHEMA);
ObjectName name = new ObjectName("com.barc.jmx:type=SystemConfig");
mbs.registerMBean(mBean, name);
do{
Thread.sleep(2000);
System.out.println(
"Thread Count = " + mBean.getThreadCount()
+ ":::Schema Name = " + mBean.getSchemaName()
);
}while(mBean.getThreadCount() != 0);
}
}
and
package com.test.jmx;
public class SystemConfig implements SystemConfigMBean {
private int threadCount;
private String schemaName;
public SystemConfig(int numThreads, String schema){
this.threadCount = numThreads;
this.schemaName = schema;
}
#Override
public void setThreadCount(int noOfThreads) {
this.threadCount = noOfThreads;
}
#Override
public int getThreadCount() {
return this.threadCount;
}
#Override
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
#Override
public String getSchemaName() {
return this.schemaName;
}
#Override
public String doConfig() {
return "No of Threads=" + this.threadCount + " and DB Schema Name = " + this.schemaName;
}
}
[source : http://www.journaldev.com/1352/what-is-jmx-mbean-jconsole-tutorial]
Is there somewhere in main() where I can create this query to validate the user details using the AD group handling application?
The default RMI connector server cannot do that very well (you can provide your own JAAS module (UC3) or Authenticator (UC4)).
You might be better off using another protocol/implementation which does already delegate authentication. There are some webservice, REST- and even jboss remoting connectors and most of them can be authenticated via a container mechanism. However I think most of them are not easy to integrate.
If you use for example Jolokia (servlet), you could also use hawt.io as a very nice "AJAX" console. (I am not sure if jolokia actually ships a JMX client connector which you can use in JConsole but there are many alternative clients which are most of the time better for integration/automation).

Aspect-Oriented programming issue in grails . Point-cut methods are not executing

I am using Grails 2.4.3 . In resource.groovy I have added component-scan
xmlns aop:"http://www.springframework.org/schema/aop"
context.'component-scan'('base-package': 'com')
Then in src/groovy I have created groovy class
package com.demo.aspects.mongo.history;
import grails.transaction.Transactional
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.aspectj.lang.annotation.After
import org.springframework.stereotype.Component
#Aspect
#Component
#Transactional
public class MongoAspectAdvice {
#After("execution(* com.demo.global.BaseOptionService.save(..))")
def afterMethod(){
println "after method execution"
}
#Before("execution(* com.demo.global.BaseOptionService.save(..))")
def beforeMethod(){
println "before method execution"
}
}
And save funtion in com.demo.global.BaseOptionService is defined as
def save(def entity){
if(entity.id == null){
entity.createdDate = new Date()
}
entity.lastUpdatedDate = new Date()
log.debug(entity)
neo4jTemplate.save(entity)
}
And BaseOptionService is extended by UserService in which BaseOptionService method is called.
UserService.groovy
class UserService extends BaseOptionService{
def addUser(username,email,role,phonenumber){
log.debug "user ===== "+username
UserCommand userCommand = new UserCommand()
userCommand.username = username
userCommand.email = email
userCommand.phonenumber = phonenumber
userCommand.role = role
if(userCommand.labels?.empty == true || userCommand.labels == null){
if(role == null){
userCommand.addLabel(null)
}else{
userCommand.addLabel("_USER")
userCommand.addLabel(role)
}
}
userCommand.isActive = true
userCommand.token = null
UserDomain user = userCommand.getUser()
log.debug "user == "+user
save(user)
return user
}
def removeLabels(id,label){
UserDomain user = findOne(id,UserDomain)
if(user.labels?.contains(label)){
user.labels.remove(label)
}
save(user)
return user
}
def serviceMethod() {
}
}
When save function is executing , I haven't seen println statement of afterMethod and beforeMethod in console and there is no error . I am not sure what wrong I am doing. Please help.
when your application start, the component scan will scan all packages for check what beans are present.
This process anyway don't instantiate the bean if it's not referenced by any other class. In other way you are telling that yes i have a MongoAspectAdvice class that is annotated with #Component so it's also a singleton but where you use it?
Try to import it in UserService.
Then if stil not working ( for check that you can put a breakpoint in that class ) add the following code to you resources.groovy:
// Place your Spring DSL code here
beans = {
mongoAspectAdvice(MongoAspectAdvice) { bean ->
bean.autowire = "byName"
}
And then import in your service:
def mongoAspectAdvice
However you can replicate this behaviour by using some grails ad-hc closures:
def beforeInterceptor = {
println "Tracing action ${actionUri}"
}
And
def afterInterceptor = {
println "Tracing action ${actionUri}"
}
Put them in BaseOptionService

Categories

Resources