java.lang.NullPointerException at java.base/sun.nio.fs.UnixPath.normalizeAndCheck(UnixPath.java:75) in SpringApplication - spring-boot

I've spring-data-aerospike project at github in branch npe.
The application.properties is
aerospike.host=localhost
aerospike.port=3000
aerospike.namespace=test
aerospike.timeout=125
os.name=Linux
line.separator=\n
The spring ApplicationContext is
mport com.aerospike.demo.simplespringbootaerospikedemo.repositories.AerospikeUserRepository;
import com.aerospike.client.Host;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.aerospike.config.AbstractAerospikeDataConfiguration;
import org.springframework.data.aerospike.repository.config.EnableAerospikeRepositories;
import java.util.Collection;
import java.util.Collections;
#Configuration
#EnableConfigurationProperties(AerospikeConfigurationProperties.class)
#EnableAerospikeRepositories(basePackageClasses = AerospikeUserRepository.class)
public class AerospikeConfiguration extends AbstractAerospikeDataConfiguration {
#Autowired
private AerospikeConfigurationProperties aerospikeConfigurationProperties;
#Override
protected Collection<Host> getHosts() {
return Collections.singleton(new Host(aerospikeConfigurationProperties.getHost(), aerospikeConfigurationProperties.getPort()));
}
#Override
protected String nameSpace() {
return aerospikeConfigurationProperties.getNamespace();
}
}
The main application is -
import com.aerospike.demo.simplespringbootaerospikedemo.configuration.AerospikeConfiguration;
import com.aerospike.demo.simplespringbootaerospikedemo.objects.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.aerospike.core.AerospikeTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.stream.Stream;
import org.joda.time.DateTime;
public class TestSpringConfig {
public static void main(String[] args) throws IOException {
System.out.println(ClassLoader.getSystemResourceAsStream("application.properties").available());
Properties props = new Properties();
InputStream resourceAsStream = ClassLoader.getSystemResourceAsStream("application.properties");
if (resourceAsStream != null) {
props.load(resourceAsStream);
}
if(props != null) {
System.setProperties(props);
}
try {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AerospikeConfiguration.class);
AerospikeTemplate template = ctx.getBean(AerospikeTemplate.class);
template.save(new User(123, "","", 12, DateTime.now().plusSeconds(60).getMillis()));
} catch (Exception e) {
StackTraceElement[] st = e.getStackTrace();
Stream.of(st).forEach(System.out::println);
} catch (ExceptionInInitializerError e) {
System.out.println(e.getCause());
e.getCause().printStackTrace();
}
}
}
when I run the main application I get below error -
java.lang.NullPointerException
at java.base/sun.nio.fs.UnixPath.normalizeAndCheck(UnixPath.java:75)
at java.base/sun.nio.fs.UnixPath.(UnixPath.java:69)
at java.base/sun.nio.fs.UnixFileSystem.getPath(UnixFileSystem.java:279)
at java.base/java.io.FilePermission.(FilePermission.java:207)
at java.base/sun.security.provider.PolicyFile.getKnownPermission(PolicyFile.java:886)
at java.base/sun.security.provider.PolicyFile.getInstance(PolicyFile.java:836)
at java.base/sun.security.provider.PolicyFile.addGrantEntry(PolicyFile.java:735)
at java.base/sun.security.provider.PolicyFile.initDefaultPolicy(PolicyFile.java:491)
at java.base/sun.security.provider.PolicyFile$2.run(PolicyFile.java:338)
at java.base/sun.security.provider.PolicyFile$2.run(PolicyFile.java:335)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/sun.security.provider.PolicyFile.initPolicyFile(PolicyFile.java:335)
at java.base/sun.security.provider.PolicyFile.init(PolicyFile.java:328)
at java.base/sun.security.provider.PolicyFile.(PolicyFile.java:281)
at java.base/java.security.Policy.loadPolicyProvider(Policy.java:207)
at java.base/java.security.Policy.getPolicyNoCheck(Policy.java:178)
at java.base/java.security.ProtectionDomain.implies(ProtectionDomain.java:321)
at java.base/java.security.ProtectionDomain.impliesWithAltFilePerm(ProtectionDomain.java:353)
at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:450)
at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
at ch.qos.logback.core.util.Loader$1.run(Loader.java:48)
at ch.qos.logback.core.util.Loader$1.run(Loader.java:45)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at ch.qos.logback.core.util.Loader.(Loader.java:45)
at ch.qos.logback.classic.util.ContextInitializer.findURLOfDefaultConfigurationFile(ContextInitializer.java:109)
at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:138)
at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:55)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
at org.apache.commons.logging.LogAdapter$Slf4jAdapter.createLocationAwareLog(LogAdapter.java:130)
at org.apache.commons.logging.LogAdapter.createLog(LogAdapter.java:91)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:67)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:59)
at org.springframework.context.support.AbstractApplicationContext.(AbstractApplicationContext.java:178)
at org.springframework.context.support.GenericApplicationContext.(GenericApplicationContext.java:112)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:67)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:91)
at com.aerospike.demo.simplespringbootaerospikedemo.TestSpringConfig.main(TestSpringConfig.java:27)
Any idea how to fix this error?

The workaround that you tried to implement in order to "Autowire" AerospikeTemplate bean doesn't work and results in a NPE. There are a few ways to "Autowire" a bean (in this case an AerospikeTemplate bean) in the static main() method, here is a StackOverFlow question that talks about this scenario:
How to use autowired (#Autowired) references from main(String[] args) method?
But the main question is what are you trying to achieve? the conventional way of using Spring Data Aerospike Repository/Template is to Autowire the repository/template in a service (also a bean) and then call the service methods from something like a controller/test/different service etc... Most Spring applications doesn't include logic inside the static main() method - it can be done but it doesn't make much sense.

To autowire AerospikeTemplate you need to setup Spring Boot application in the main method (check an example here):
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
then you can autowire AerospikeTemplate anywhere you need.
If you are developing a console application using Spring Boot I would suggest using org.springframework.boot.CommandLineRunner. For example:
#Component
public class CommandLineRunnerImpl implements CommandLineRunner {
#Autowired
AerospikeTemplate template;
#Override
public void run(String... args) throws Exception {
template.save(new User(123, "","", 12, DateTime.now().plusSeconds(60).getMillis()));
}
}

Related

Open tracer Jaeger Trace not getting reflect for apache camel

I am new to apache camel and open tracing with Jaeger, I trying to get the traces for apache camel in Jaeger UI but its not getting captured through Open Tracing.
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.springframework.stereotype.Component;
#Component
public class RouteBuilderClient {
public void test() throws Exception {
DefaultCamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("timer:first-timer")
.to("log:first-timer");
}
});
camelContext.start();
camelContext.stop();
}
}
However if if I extend the RouteBuilder class(Below is the sample code) and then I override the configure method then traces are getting generated for Apache camel. Is there any way without extending the routeBuilder I can get the traces?
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
#Component
public class RouteBuilderClient extends RouteBuilder {
#Override
public void configure() throws Exception {
from("timer:first-timer")
.to("log:first-timer");
}
}
My controller class:
import org.apache.camel.opentracing.starter.CamelOpenTracing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#CamelOpenTracing
public class JaegarClientApplication {
public static void main(String[] args) {
SpringApplication.run(JaegarClientApplication.class, args);
}
}
Try adding this in your setup() method, before starting the Camel context:
OpenTracingTracer ottracer = new OpenTracingTracer();
ottracer.init(camelContext);
camelContext.start();
Below is my code that Worked successfully.
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.opentracing.OpenTracingTracer;
public class RouteBuilderClient3 {
public void test() throws Exception {
RouteBuilder builder = new RouteBuilder() {
public void configure() {
from("timer:first-timer3").transform().constant("Rajesh client 3")
.to("log:first-timer3");
}
};
CamelContext myCamelContext = new DefaultCamelContext();
myCamelContext.addRoutes(builder);
OpenTracingTracer ottracer = new OpenTracingTracer();
ottracer.init(myCamelContext);
myCamelContext.start();
// myCamelContext.stop();
}
}

KafkaBindingRebalanceListener Bean not autowired by KafkaMessageChannelBinder Bean

Documentation is pretty straight forward which suggests exposing a Bean of type KafkaBindingRebalanceListener and onPartitiosnAssigned method would be called internally. I'm trying to do the same and somehow while spring framework creates its KafkaMessageChannelBinder Bean the ObjectProvider.getIfUnique() always return null as it not able to find the required bean. It seems when application starts SpringFramework strats creating its Beans first and isnt able to find the Rebalance Listener Bean as it is not yet created. Following are the three code snippets from project. Please help if im missing anything to instruct application to create Beans in application package first before going to Spring Framework.
RebalanceListener
package io.spring.dataflow.sample.seekoffset.config;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.binder.kafka.KafkaBindingRebalanceListener;
import org.springframework.stereotype.Component;
import java.util.Collection;
#Component
public class KafkaRebalanceListener implements KafkaBindingRebalanceListener {
Logger logger = LoggerFactory.getLogger(SeekOffsetConfig.class);
#Override
public void onPartitionsAssigned(String bindingName, Consumer<?, ?> consumer, Collection<TopicPartition> partitions, boolean initial) {
logger.debug("onPartitionsAssigned");
}
}
ConfigClass
package io.spring.dataflow.sample.seekoffset.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
#EnableBinding(Sink.class)
public class SeekOffsetConfig {
Logger logger = LoggerFactory.getLogger(SeekOffsetConfig.class);
#StreamListener(Sink.INPUT)
public void receiveMessage(Message<String> message) {
logger.debug("receiveMessage()");
}
}
ApplicationClass
package io.spring.dataflow.sample.seekoffset;
import io.spring.dataflow.sample.seekoffset.config.KafkaRebalanceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class SeekOffsetApplication {
Logger logger = LoggerFactory.getLogger(SeekOffsetApplication.class);
public static void main(String[] args) {
SpringApplication.run(SeekOffsetApplication.class, args);
}
}
What version are you using? This works fine for me with Boot 2.3.2 and Hoxton.SR6:
#SpringBootApplication
#EnableBinding(Sink.class)
public class So63157778Application {
public static void main(String[] args) {
SpringApplication.run(So63157778Application.class, args);
}
#StreamListener(Sink.INPUT)
public void listen(String in) {
System.out.println(in);
}
#Bean
KafkaBindingRebalanceListener rebal() {
return new KafkaBindingRebalanceListener() {
#Override
public void onPartitionsAssigned(String bindingName, Consumer<?, ?> consumer,
Collection<TopicPartition> partitions, boolean initial) {
System.out.println(bindingName + " assignments: " + partitions + ", initial call :" + initial);
}
};
}
}
input assignments: [input-0], initial call :true
This works for me too:
#SpringBootApplication
#EnableBinding(Sink.class)
public class So63157778Application {
public static void main(String[] args) {
SpringApplication.run(So63157778Application.class, args);
}
#StreamListener(Sink.INPUT)
public void listen(String in) {
System.out.println(in);
}
}
#Component
class Foo implements KafkaBindingRebalanceListener {
#Override
public void onPartitionsAssigned(String bindingName, Consumer<?, ?> consumer,
Collection<TopicPartition> partitions, boolean initial) {
System.out.println(bindingName + " assignments: " + partitions + ", initial call :" + initial);
}
}

How to make post request in apache camel rest

I am new apache rest dsl with spring boot, have made following changes
Main Class
package com.javaoutofbounds.pojo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.ccs.batchfile"})
public class BatchFileApplication {
public static void main(String[] args) {
SpringApplication.run(BatchFileApplication.class, args);
}
}
Service class
package com.ccs.batchfile.service;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.stereotype.Component;
#Component
public class BatchFileService extends RouteBuilder {
#Override
public void configure() throws Exception {
restConfiguration().component("servlet").bindingMode(RestBindingMode.json);
rest("/batchFile").consumes("application/json").produces("application/json").get("/routeStart").to("direct:startRoute");
}
}
Route class
package com.ccs.batchfile.routes;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ccs.batchfile.processor.StartRouteProcessor;
#Component
public class StartRoute extends RouteBuilder{
#Autowired
private StartRouteProcessor startRouteProcessor;
#Override
public void configure() throws Exception {
from("direct:startRoute").log("Inside StartRoute")
.process(startRouteProcessor);
}
}
Processor class
package com.ccs.batchfile.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
#Component("startRouteProcessor")
public class StartRouteProcessor implements Processor{
public void process(Exchange exchange) throws Exception {
String message = exchange.getIn().getBody(String.class);
System.out.println(message);
}
}
I am not getting control to StartRouteProcessor, when i make below post request in postman
http://localhost:8080/batchFile/routeStart/
I have used below test payload to check if works.
{
"title" : "test title",
"singer" : "some singer"
}
When i post the above request i am getting 404 error. Kindly help on this please
I tried your example and you need to add two changes.
In your "main" class, the 'component scan' annotation is right, but you have to add a 'ServletRegistrationBean' with name 'CamelServlet':
package org.funcode.app.main;
import org.apache.camel.component.servlet.CamelHttpTransportServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
#SpringBootApplication(scanBasePackages = {"org.funcode.app"})
public class BatchFileApplication {
private static final String CAMEL_URL_MAPPING = "/api/*";
private static final String CAMEL_SERVLET_NAME = "CamelServlet";
public static void main(String[] args) {
SpringApplication.run(BatchFileApplication.class, args);
}
#Bean
public ServletRegistrationBean servletRegistrationBean() {
ServletRegistrationBean registration =
new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING);
registration.setName(CAMEL_SERVLET_NAME);
return registration;
}
}
And if you want view on the log the content you posted on the request, you need to change the method of the request to "post":
package org.funcode.app.main;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.stereotype.Component;
#Component
public class BatchFileService extends RouteBuilder {
#Override
public void configure() throws Exception {
restConfiguration().component("servlet").bindingMode(RestBindingMode.json);
rest("/batchFile")
.consumes("application/json")
.produces("application/json")
.post("/routeStart")
.to("direct:startRoute");
}
}
I hope it helps.

How to inject objects which are not annotated Spring classes

Lets say I've got a JavaFx class and an ViewState class which needs to have referance of stage created in start method. How am I able to autowire such dependency? I know that Stage.class is not annotated as #Component so Spring is unable to detect duch #Bean.
#SpringBootApplication
#ComponentScan({"controller","service","dao","javafx.stage.Stage"})
#EntityScan( basePackages = {"Model"})
#Import({ SpringConfig.class})
public class JavaFXandSpringBootTestApplication extends Application{
private ApplicationContext ctx;
public static void main(String[] args) {
launch();
}
#Override
public void start(Stage stage) throws Exception {
ViewState viewState = ctx.getBean(ViewState.class);
}
ViewState class:
#Componenet
public class ViewState {
#Autowired
private ApplicationContext ctx;
private Stage stage;
#Autowired
public ViewState(Stage stage)
{
this.stage = stage;
}
}
Compiler massage:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javafx.stage.Stage' available: expected at least 1
You probably don't want to do this at all: your ViewState class would seem to be a model class of some kind, so it should not have references to UI elements (such as Stages).
For completeness, though, here is an example that works, using ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(...). Note that, since you won't be able to create the View object until the stage is registered, you need to make the View bean #Lazy:
package example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
#Component
#Lazy
public class View {
#Autowired
public View(Stage stage) {
Button close = new Button("Close");
close.setOnAction(e -> stage.hide());
StackPane root = new StackPane(close);
Scene scene = new Scene(root, 400, 400);
stage.setScene(scene);
stage.show();
}
}
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import javafx.application.Application;
import javafx.stage.Stage;
#SpringBootApplication
public class Main extends Application {
private ConfigurableApplicationContext ctx ;
#Override
public void start(Stage primaryStage) {
ctx = SpringApplication.run(Main.class);
ctx.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage);
ctx.getBean(View.class);
}
#Override
public void stop() {
ctx.close();
}
public static void main(String[] args) {
launch(args);
}
}

Stateful Session Bean not passivated after Cache Idle Timeout(cache-idle-timeout-in-seconds) elapsed

I am trying to understand Stateful Session bean life cycle.I am particularly interested when activation and passivation life cycle callback invoked.I created a demo to understand this scenario. Here is My code :
My Remote interface is :
package com.orbit.stateful;
import javax.ejb.Remote;
import java.util.List;
#Remote
public interface ShoppingCart
{
public void addItem(String itemName);
public void removeItem(String item);
public List<String> getAllItems();
public void finishShopping();
}
My Stateful session bean class is as follow:
package com.orbit.stateful;
import javax.ejb.Stateful;
import javax.ejb.Remove;
import javax.ejb.PrePassivate;
import javax.ejb.PostActivate;
import javax.ejb.StatefulTimeout;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
//import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;
#Stateful
//#StatefulTimeout(value=5L,unit=TimeUnit.MINUTES)
public class ShoppingCartBean implements ShoppingCart
{
private List<String> itemList;
public ShoppingCartBean(){
System.out.println("Stateful SessionBean Constructor Called");
}
#PostConstruct
public void intialize(){
System.out.println("Initializing shopping Cart");
itemList=new ArrayList<String>();
}
public void addItem(String itemName){
itemList.add(itemName);
}
public void removeItem(String item){
itemList.remove(item);
}
public List<String> getAllItems(){
return itemList;
}
#Remove
public void finishShopping(){
System.out.println("I am finished with Shopping");
}
#PreDestroy
public void tidyUp(){
System.out.println("Remove Shopping Bean");
}
#PrePassivate
public void logPassivation(){
System.out.println("Passivating Now");
}
#PostActivate
public void logActivation(){
System.out.println("Activating Now");
}
}
And standalone client for this bean is :
package com.orbit.stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
import java.util.List;
public class ShoppingCartClient
{
public static void main(String[] args) throws Exception
{
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state",
"com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
Context ctx=new InitialContext(props);
ShoppingCart sc=(ShoppingCart)ctx.lookup("com.orbit.stateful.ShoppingCart");
sc.addItem("J2SE");
//Thread.sleep(17000);
sc.addItem("J2EE");
sc.addItem("JDBC");
List<String> books=sc.getAllItems();
for (String str: books )
{
System.out.println("Books is : "+ str);
}
//sc.finishShopping();
}
}
Now I have set Cache Idle Timeout=20 in GlassFish 3.1.2
But still My stateful session bean is not passivating after 20 seconds. am I doing something wrong or something is not happening correctly in Glashfish ?Help me to understand this.
Thanks in Advance

Resources