QuickFIX/J: Type 'quickfix/field/HaltReason' is not assignable to 'quickfix/IntField' - quickfixj

Summary
We have a quickfix client which receives SecurityDefiniton and SecurityDefinitionUpdateReport messages. These are bulk datas. When we logged to the server they send messages around 8000. At the end they're sending SecurityStatus message. In this part we are getting an exception.
Fix protocol version: FIX50SP2 with FIXT1.1
Quickfix message dependency
<dependency>
<groupId>org.quickfixj</groupId>
<artifactId>quickfixj-messages-fix50sp2</artifactId>
<version>2.3.0</version>
</dependency>
Quickfix Core
<dependency>
<groupId>org.quickfixj</groupId>
<artifactId>quickfixj-core</artifactId>
<version>2.0.0</version>
</dependency>
Exception we received;
Exception in thread "pool-5-thread-1" java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
quickfix/fix50sp2/SecurityStatus.get(Lquickfix/field/HaltReason;)Lquickfix/field/HaltReason; #2: invokevirtual
Reason:
Type 'quickfix/field/HaltReason' (current frame, stack[1]) is not assignable to 'quickfix/IntField'
Current Frame:
bci: #2
flags: { }
locals: { 'quickfix/fix50sp2/SecurityStatus', 'quickfix/field/HaltReason' }
stack: { 'quickfix/fix50sp2/SecurityStatus', 'quickfix/field/HaltReason' }
Bytecode:
0x0000000: 2a2b b600 1557 2bb0
at quickfix.fix50sp2.MessageFactory.create(MessageFactory.java:297)
at foo.bar.data.plugin.fix.api.MessageFactory.MessageFactorySp2.create(MessageFactorySp2.java:93)
at quickfix.MessageUtils.parse(MessageUtils.java:145)
at quickfix.mina.AbstractIoHandler.messageReceived(AbstractIoHandler.java:131)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$TailFilter.messageReceived(DefaultIoFilterChain.java:858)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:542)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1300(DefaultIoFilterChain.java:48)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:947)
at org.apache.mina.filter.codec.ProtocolCodecFilter$ProtocolDecoderOutputImpl.flush(ProtocolCodecFilter.java:398)
at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:234)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:542)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1300(DefaultIoFilterChain.java:48)
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:947)
at org.apache.mina.core.filterchain.IoFilterAdapter.messageReceived(IoFilterAdapter.java:109)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:542)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.fireMessageReceived(DefaultIoFilterChain.java:535)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:703)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:659)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:648)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$600(AbstractPollingIoProcessor.java:68)
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1120)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
We couldn't get SecurityStatus fix message. The problem we thought was about datadictionary. As a field HaltReason is a CharField
public class HaltReason extends CharField {
static final long serialVersionUID = 20050617L;
public static final int FIELD = 327;
public static final char NEWS_DISSEMINATION = 'D';
public static final char ORDER_INFLUX = 'E';
public static final char ORDER_IMBALANCE = 'I';
public static final char ADDITIONAL_INFORMATION = 'M';
public static final char NEWS_PENDING = 'P';
public static final char EQUIPMENT_CHANGEOVER = 'X';
When we look FIX50SP2 default datadictionary halt reason field is INT.
<field number="327" name="HaltReasonInt" type="INT">
<value enum="0" description="NEWS_DISSEMINATION"/>
<value enum="1" description="ORDER_INFLUX"/>
<value enum="2" description="ORDER_IMBALANCE"/>
<value enum="3" description="ADDITIONAL_INFORMATION"/>
<value enum="4" description="NEWS_PENDING"/>
<value enum="5" description="EQUIPMENT_CHANGEOVER"/>
</field>
We tried convert dictionary field to HaltReasonChar and the type CHAR but it didn't work. Did you ever get an exception like this?
Here's the security status message which I received.
8=FIXT.1.19=00017835=f49=BI_TEST56=LIABR34=589857=TRTK152=20220208-20:07:15.9281180=R1181=28513331350=285133255=T2-ON48=3762690422=M336=148325=N60=20220208-20:07:15.92810=245

It doesn't look like the HaltReason field (tag 327) is included in your status message. Is it an optional or required field for the SecurityStatus message type? You can control that in your data dictionary definition.
The dictionary for FIX50SP2.xml I have indicates this field is not required, but yours could be different.
Be careful of broker-supplied dictionaries; they are frequently wrong or outdated.

The following worked fine for me: report is of type quickfix.fix44.SecurityStatus
try {
response.setHaltReason(report.getString(327));
} catch (Exception e) {
log.error...
}

Related

How to combine different mono and use the combined result with error handling?

I have a scenario where i need to use different mono which could return me errors and set map values to null if error is returned.
Ex:
Mono<A> a=Some api call;
Mono<A> b=Some api giving error;
Mono<A> c=Some api call;
Now i want to set the resulting response to map
Map<String,A> m=new HashMap<>();
m.put("a",a);
m.put("b",null);
m.put("c",c);
Can anyone help on how to do all this in reactive non blocking way.
I tried zip but it will not execute if any of the api return error or if i use onErrorReturn(null).
Thanks in advance
To solve your problems, you will have to use some tricks. The problem is that :
Giving an empty mono or mono that ends in error cancel zip operation (source: Mono#zip javadoc)
Reactive streams do not allow null values (source: Reactive stream spec, table 2: Subscribers, bullet 13)
Also, note that putting a null value in a hash map is the same as cancelling any previous value associated with the key (it's important in case you're updating an existing map).
Now, to bypass your problem, you can add an abstraction layer, and wrap your values in domain objects.
You can have an object that represents a query, another a valid result, and the last one will mirror an error.
With that, you can design publishers that will always succeed with non null values.
That's a technic used a lot in functional programming : common errors are part of the (one possible) result value.
Now, let's see the example that create a new Map from multiple Monos:
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Map;
public class BypassMonoError {
/**
* An object identified by a key. It serves to track which key to associate to computed values
* #param <K> Type of the key
*/
static class Identified<K> {
protected final K id;
Identified(K id) {
this.id = id;
}
public K getId() {
return id;
}
}
/**
* Describe the result value of an operation, along with the key associated to it.
*
* #param <K> Type of the identifier of the result
* #param <V> Value type
*/
static abstract class Result<K, V> extends Identified<K> {
Result(K id) {
super(id);
}
/**
*
* #return Computed value on success, or null if the operation has failed. Note that here, we cannot tell from
* a success returning a null value or an error
*/
abstract V getOrNull();
}
static final class Success<K, V> extends Result<K, V> {
private final V value;
Success(K id, V value) {
super(id);
this.value = value;
}
#Override
V getOrNull() {
return value;
}
}
static final class Error<K, V> extends Result<K, V> {
private final Exception error;
Error(K id, Exception error) {
super(id);
this.error = error;
}
#Override
V getOrNull() {
return null;
}
public Exception getError() {
return error;
}
}
/**
* A request that can asynchronously generate a result for the associated identifier.
*/
static class Query<K, V> extends Identified<K> {
private final Mono<V> worker;
Query(K id, Mono<V> worker) {
super(id);
this.worker = worker;
}
/**
* #return The operator that computes the result value. Note that any error is silently wrapped in an
* {#link Error empty result with error metadata}.
*/
public Mono<Result<K, V>> runCatching() {
return worker.<Result<K, V>>map(success -> new Success<>(id, success))
.onErrorResume(Exception.class, error -> Mono.just(new Error<K, V>(id, error)));
}
}
public static void main(String[] args) {
final Flux<Query<String, String>> queries = Flux.just(
new Query("a", Mono.just("A")),
new Query("b", Mono.error(new Exception("B"))),
new Query("c", Mono.delay(Duration.ofSeconds(1)).map(v -> "C"))
);
final Flux<Result<String, String>> results = queries.flatMap(query -> query.runCatching());
final Map<String, String> myMap = results.collectMap(Result::getId, Result::getOrNull)
.block();
for (Map.Entry<String, String> entry : myMap.entrySet()) {
System.out.printf("%s -> %s%n", entry.getKey(), entry.getValue());
}
}
}
Note : In the above example, we silently ignore any occurred error. However, when using the flux, you can test if a result is an error, and if it is, you are free to design your own error management (log, fail-first, send in another flux, etc.).
This outputs:
a -> A
b -> null
c -> C

How do I write an appender that only handles exceptions and still have all other logs logged normally through a root ConsoleAppender

I have a situation where when log.error("message", exception); is called, I want some logic to happen around sending the exception to an external tool, while still maintaining the regular logging for the line to the root appender.
As an example, here would be some code and the expected outcome:
try {
...
} catch (Exception ex) {
LOG.info("abcd");
LOG.error("failed to XYZ", ex);
}
Rough Outcome:
2019-03-05 13:00:20 INFO Main:75 - abcd
2019-03-05 13:00:20 ERROR Main:76 - failed to XYZ -
Exception: exception message
stacktrace
stacktrace
...
While that is logged, I also want the exception sent through another code path.
How can I do this? I'm a bit stuck, does anyone know any good guides for this?
I don't think you really want an Appender here. It would be simpler to write a Filter instead. For reference you can find information regarding creating extensions for log4j2 on the Extending Log4j2 page of the manual
In the example below I created a simple filter that matches when the log event has a Throwable associated with it and mismatches when there is no Throwable (i.e. the Throwable is null or the log was generated from a method call that did not include a Throwable parameter).
In the example I send all matching log events to a simple file appender to illustrate that in fact it does capture only events with a Throwable. You could modify this filter to do whatever you need. You could change it to always be NEUTRAL to every event, but when a non-null Throwable is found it then triggers some special logic to send that Throwable to your external tool. Basically you would be using the filter as more of an interceptor. I will describe that change at the end.
First, here's some basic Java code to generate some logging including a log event that has a Throwable.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class SomeClass {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args){
if(log.isDebugEnabled())
log.debug("This is some debug!");
log.info("Here's some info!");
log.error("Some error happened!");
try{
specialLogic();
}catch(RuntimeException e){
log.error("Woops, an exception was detected.", e);
}
}
public static void specialLogic(){
throw new RuntimeException("Hey an exception happened! Oh no!");
}
}
Next, here's the class I call ThrowableFilter:
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.Message;
#Plugin(name = "ThrowableFilter", category = "Core", elementType = "filter", printObject = true)
public final class ThrowableFilter extends AbstractFilter {
private ThrowableFilter(Result onMatch, Result onMismatch) {
super(onMatch, onMismatch);
}
public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
return onMismatch;
}
public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
return filter(t);
}
public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
return filter(t);
}
#Override
public Result filter(LogEvent event) {
return filter(event.getThrown());
}
private Result filter(Throwable t) {
return t != null ? onMatch : onMismatch;
}
/**
* Create a ThrowableFilter.
* #param match The action to take on a match.
* #param mismatch The action to take on a mismatch.
* #return The created ThrowableFilter.
*/
#PluginFactory
public static ThrowableFilter createFilter(#PluginAttribute(value = "onMatch", defaultString = "NEUTRAL") Result onMatch,
#PluginAttribute(value = "onMismatch", defaultString = "DENY") Result onMismatch) {
return new ThrowableFilter(onMatch, onMismatch);
}
}
Finally, here is the log4j2.xml configuration file I used to test this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="ExceptionFile" fileName="logs/exception.log" immediateFlush="true"
append="true">
<ThrowableFilter onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout
pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="ExceptionFile" />
</Root>
</Loggers>
</Configuration>
Running the logic in SomeClass produces the following output:
On the console:
23:23:25.931 [main] DEBUG example.SomeClass - This is some debug!
23:23:25.946 [main] INFO example.SomeClass - Here's some info!
23:23:25.946 [main] ERROR example.SomeClass - Some error happened!
23:23:25.946 [main] ERROR example.SomeClass - Woops, an exception was detected.
java.lang.RuntimeException: Hey an exception happened! Oh no!
at example.SomeClass.specialLogic(SomeClass.java:25) ~[classes/:?]
at example.SomeClass.main(SomeClass.java:18) [classes/:?]
In the logs/exception.log file:
2019-03-06 23:23:25.946 [main] ERROR example.SomeClass - Woops, an exception was detected.
java.lang.RuntimeException: Hey an exception happened! Oh no!
at example.SomeClass.specialLogic(SomeClass.java:25) ~[classes/:?]
at example.SomeClass.main(SomeClass.java:18) [classes/:?]
Now to change the filter to act more as an interceptor you could alter the following methods:
//Remove parameters from constructor as they will not be used.
private ThrowableFilter() {
super();
}
...
public Result filter(Logger logger, Level level, Marker marker, String msg, Object[] params) {
//Changed to always return NEUTRAL result
return Result.NEUTRAL;
//old logic: return onMismatch;
}
...
private Result filter(Throwable t) {
//TODO: trigger the external tool here when t != null, pass t if needed.
//Changed to always return NEUTRAL result
return Result.NEUTRAL;
//old logic: return t != null ? onMatch : onMismatch;
}
/**
* Create a ThrowableFilter.
* #return The created ThrowableFilter.
*/
#PluginFactory
public static ThrowableFilter createFilter() {
return new ThrowableFilter();
}
Then in the configuration you would remove the parameters to the filter. It would now look like this:
<ThrowableFilter/>
Hope this helps you.

SpringAMQP errorHandler and returnExceptions problem

i am not sure my understanding to errorHandler and returnExceptions is right or not.
but here is my goal: i sent a message from App_A, use #RabbitListener to receive message in App_B.
according to the doc
https://docs.spring.io/spring-amqp/docs/2.1.3.BUILD-SNAPSHOT/reference/html/_reference.html#annotation-error-handling
i assume if APP_B has a business exception during process the message,through set errorHandler and returnExceptions in a right way on #RabbitListener can let the exception back to App_A.
do I understood correctly?
if i am rigth, how to use it in a right way?
with my code, i get nothing in APP_A .
here is my code in APP_B
errorHandler:
#Component(value = "errorHandler")
public class ErrorHandler implements RabbitListenerErrorHandler {
#Override
public Object handleError(Message arg0, org.springframework.messaging.Message<?> arg1,
ListenerExecutionFailedException arg2) throws ListenerExecutionFailedException {
throw new ListenerExecutionFailedException("msg", arg2, null);
}
}
RabbitListener:
#RabbitListener(
bindings = #QueueBinding(
value = #Queue(value = "MRO.updateBaseInfo.queue", durable = "true"),
exchange = #Exchange(name = "MRO_Exchange", type = ExchangeTypes.DIRECT, durable = "true"),
key = "baseInfoUpdate"
),
// errorHandler = "errorHandler",
returnExceptions = "true"
)
public void receiveLocationChangeMessage(String message){
BaseUpdateMessage newBaseInfo = JSON.parseObject(message, BaseUpdateMessage.class);
dao.upDateBaseInfo(newBaseInfo);
}
and code in APP_A
#Component
public class MessageSender {
#Autowired
private RabbitTemplate rabbitTemplate;
public void editBaseInfo(BaseUpdateMessage message)throws Exception {
//and i am not sure set RemoteInvocationAwareMessageConverterAdapter in this way is right
rabbitTemplate.setMessageConverter(new RemoteInvocationAwareMessageConverterAdapter());
rabbitTemplate.convertAndSend("MRO_Exchange", "baseInfoUpdate", JSON.toJSONString(message));
}
}
i am very confuse with three points:
1)do i have to use errorHandler and returnExceptions at the same time? i thought errorHandler is something like a postprocessor that let me custom exception.if i don't need a custom exception can i just set returnExceptions with out errorHandler ?
2)should the method annotated with #RabbitListener return something or void is just fine?
3)in the sender side(my situation is APP_A), does have any specific config to catch the exception?
my workspace environment:
Spring boot 2.1.0
rabbitMQ server 3.7.8 on docker
1) No, you don't need en error handler, unless you want to enhance the exception.
2) If the method returns void; the sender will end up waiting for timeout for a reply that will never arrive, just in case an exception might be thrown; that is probably not a good use of resources. It's better to always send a reply, to free up the publisher side.
3) Just the RemoteInvocationAwareMessageConverterAdapter.
Here's an example:
#SpringBootApplication
public class So53846303Application {
public static void main(String[] args) {
SpringApplication.run(So53846303Application.class, args);
}
#RabbitListener(queues = "foo", returnExceptions = "true")
public String listen(String in) {
throw new RuntimeException("foo");
}
#Bean
public ApplicationRunner runner(RabbitTemplate template) {
template.setMessageConverter(new RemoteInvocationAwareMessageConverterAdapter());
return args -> {
try {
template.convertSendAndReceive("foo", "bar");
}
catch (Exception e) {
e.printStackTrace();
}
};
}
}
and
org.springframework.amqp.AmqpRemoteException: java.lang.RuntimeException: foo
at org.springframework.amqp.support.converter.RemoteInvocationAwareMessageConverterAdapter.fromMessage(RemoteInvocationAwareMessageConverterAdapter.java:74)
at org.springframework.amqp.rabbit.core.RabbitTemplate.convertSendAndReceive(RabbitTemplate.java:1500)
at org.springframework.amqp.rabbit.core.RabbitTemplate.convertSendAndReceive(RabbitTemplate.java:1433)
at org.springframework.amqp.rabbit.core.RabbitTemplate.convertSendAndReceive(RabbitTemplate.java:1425)
at com.example.So53846303Application.lambda$0(So53846303Application.java:28)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:794)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at com.example.So53846303Application.main(So53846303Application.java:15)
Caused by: java.lang.RuntimeException: foo
at com.example.So53846303Application.listen(So53846303Application.java:20)
As you can see, there is a local org.springframework.amqp.AmqpRemoteException with the cause being the actual exception thrown on the remote server.

Retrofit 2.0 Cant convert Request Body to JSON

I hope someone can help me.
I try to send a POST Request with a JSON Body using Retrofit 2.0.
Interface:
public interface Interface {
#POST(/*path*/)
Call<MyResponseObject> sendInt(#Body MyInteger myInt);
}
MyInteger class:
public class MyInteger {
int id;
public MyInteger(int id) {
this.id = id;
}
}
Part of MainActivity:
private Retrofit mRetrofit = null;
private final Interface mService;
...
...
mRetrofit = new Retrofit.Builder()
.baseUrl(/*URL*/)
.addConverterFactory(GsonConverterFactory.create())
.build();
mService = mRetrofit.create(Interface.class);
The call:
MyInteger id = new MyInteger(0);
mService.sendInt(id).enqueue(new Callback<MyResponseObject>() {
#Override
public void onResponse(Call<MyResponseObject> call, Response<MyResponseObject> response) {/*Log something*/}
#Override
public void onFailure(Call<MyResponseObject> call, Throwable t) {}
});
In my Opinion it's like this example:
https://futurestud.io/blog/retrofit-send-objects-in-request-body
But the GsonConverter cant convert MyInteger to JSON..
Here is the Log:
java.lang.IllegalArgumentException: Unable to create #Body converter for class com.??.MyInteger (parameter #1)
for method Interface.sendInt
...
...
Caused by: java.lang.IllegalArgumentException: Could not locate RequestBody converter for class com.??.MyInteger.
Tried:
* retrofit2.BuiltInConverters
* retrofit2.GsonConverterFactory
at retrofit2.Retrofit.nextRequestBodyConverter(Retrofit.java:288)
at retrofit2.Retrofit.requestBodyConverter(Retrofit.java:248)
at retrofit2.RequestFactoryParser.parseParameters(RequestFactoryParser.java:491)
I had the same problem. The root cause was that I was using incompatible libraries.
This combination works for me:
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.0.0-beta4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.0.0-beta4</version>
</dependency>

SnakeYaml class not found exception

When I parse config.yaml using SnakeYaml 1.14 I get a "Class not found exception". The following is the code used for parsing. I have used maven to build the project.
public class AppConfigurationReader
{
private static final String CONFIG_FILE = "config.yaml";
private static String fileContents = null;
private static final Logger logger = LoggerFactory.getLogger(AppConfigurationReader.class);
public static synchronized AppConfiguration getConfiguration() {
return getConfiguration(false);
}
public static synchronized AppConfiguration getConfiguration(Boolean forceReload) {
try {
Yaml yaml = new Yaml();
if(null == fileContents || forceReload) {
fileContents = read(CONFIG_FILE);
}
yaml.loadAs(fileContents, AppConfiguration.class);
return yaml.loadAs(fileContents, AppConfiguration.class);
}
catch (Exception ex) {
ex.printStackTrace();
logger.error("Error loading fileContents {}", ex.getStackTrace()[0]);
return null;
}
}
private static String read(String filename) {
try {
return new Scanner(new File(filename)).useDelimiter("\\A").next();
} catch (Exception ex) {
logger.error("Error scanning configuration file {}", filename);
return null;
}
}
}
I too had this, it was due to an incorrect set of dependencies.
I had used
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
</dependency>
when I should have used
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
The difference being that the latter includes org.yaml:snakeyaml:jar:1.27:compile
May be I am bit late to respond, but it will help others in future.
This issue comes when your class is not able to load the class, sometimes even if it is present in your classpath also.
I encountered this Issue and can be handled in this way.
package my.test.project;
import java.io.InputStream;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
public class MyTestClass {
public static void main(String[] args) {
InputStream input = MyTestClass.class.getClassLoader().getResourceAsStream("test.yml");
Yaml y = new Yaml(new CustomClassLoaderConstructor(MyTestClass.class.getClassLoader()));
TestConfig test =y.loadAs(input, TestConfig.class);
System.out.println(test);
}
}
You need to initialize Yaml object with CustomClassLoaderConstructor it will help load the bean class before it was actually used internally.
I have found a similar error but dumping a file.
You could write the complete name of the class in yaml.load instruction.
For example, if AppConfiguration.class was in org.example.package1, you would write something like:
yaml.loadAs(fileContents, org.example.package1.AppConfiguration.class);
Seems like snakeyaml libraries are not included in your jar file, you have to use the maven assembly plugin eather than just package, so that all the dependency jars gets included

Resources