How to skip JdbcAppender during #SpringBootTest? - spring-boot

We are using JdbcAppender to log all WARN and ERROR logs into database.
But when we are running the SpringBootTest classes, we are using in-memory database for our tests so its throwing exceptions because of JdbcAppender fails to log.
Caused by: org.h2.jdbc.JdbcSQLException: Table "APPLICATION_LOG" not found; SQL statement:
INSERT INTO application_log (application_log_id,service_id,logger,log_level,message,throwable,log_date) VALUES (?,?,?,?,?,?,?)
2018-06-15 11:53:38,369 main ERROR An exception occurred processing Appender DB org.apache.logging.log4j.core.appender.AppenderLoggingException: Cannot write logging event or flush buffer; JDBC manager cannot connect to the database.
Method:
#PostConstruct
public void onStartUp() {
// Create a new connectionSource build from the Spring properties
LoggerConnectionSource connectionSource = new LoggerConnectionSource(url, userName, password, validationQuery);
// This is the mapping between the columns in the table and what to
// insert in it.
ColumnConfig[] columnConfigs = new ColumnConfig[7];
columnConfigs[0] = ColumnConfig.createColumnConfig(null, "application_log_id", "0", null, null, null, null);
columnConfigs[1] = ColumnConfig.createColumnConfig(null, "service_id", "" + serviceId + "", null, null, "false",
null);
columnConfigs[2] = ColumnConfig.createColumnConfig(null, "logger", "%logger", null, null, "false", null);
columnConfigs[3] = ColumnConfig.createColumnConfig(null, "log_level", "%level", null, null, "false", null);
columnConfigs[4] = ColumnConfig.createColumnConfig(null, "message", "%message", null, null, "false", null);
columnConfigs[5] = ColumnConfig.createColumnConfig(null, "throwable", "%ex{full}", null, null, "false", null);
columnConfigs[6] = ColumnConfig.createColumnConfig(null, "log_date", null, null, "true", null, null);
// filter for the appender to keep only errors
ThresholdFilter filter = ThresholdFilter.createFilter(appenderLevel, null, null);
JdbcAppender appender = JdbcAppender.createAppender(appenderName, "true", filter, connectionSource, "1",
appenderTableName, columnConfigs);
// start the appender, and this is it...
appender.start();
((Logger) LogManager.getRootLogger()).addAppender(appender);
}
Is there any way to skip jdbcAppender during #SpringBootTest ?

Related

How to catch the SqlExceptionHelper in spring boot?

I could not capture that error that comes from the stored procedure that I created.
create procedure sp_users
#option int = 0,
#nom_user varchar(50) = null,
#ema_user varchar(50) = null
as
begin
set nocount on
begin try
if #option = 2
begin
if not exists (select * from tb_users where ema_user = #ema_user)
begin
insert into tb_users values (#nom_user,#ema_user)
end
else
begin
raiserror('The email already exists',16,1)
end
end
end try
begin catch
declare #errorMessage varchar(100), #errorSeverity int, #errorState int
set #errorMessage = error_message()
set #errorSeverity = error_severity()
set #errorState = error_state()
raiserror(#errorMessage,#errorSeverity,#errorState)
end catch
end
when I enter an email that already exists, it shows me the message.
Msg 50000, Level 16, State 1, Procedure sp_users, Line 71 [Batch Start Line 81]
The email already exists
this is the code that I made in spring boot
#Service
public class CrudUserService implements CrudUserDAO{
#PersistenceContext
private EntityManager em;
#SuppressWarnings({ "unchecked" })
#Override
public ValidateApiResponse MntUser(Integer op, String nom, String ema) {
ValidateApiResponse vapi = new ValidateApiResponse();
Session session = em.unwrap(Session.class);
try {
ProcedureCall call = session.createStoredProcedureCall("sp_users");
call.registerParameter(1, Integer.class, ParameterMode.IN);
call.registerParameter(2, String.class, ParameterMode.IN).enablePassingNulls(true);
call.registerParameter(3, String.class, ParameterMode.IN).enablePassingNulls(true);
call.setParameter(1, op);
call.setParameter(2, nom);
call.setParameter(3, ema);
call.execute();
vapi.dTable = call.getResultList();
vapi.Attr = "OK";
} catch (Exception e) {
//vapi.Attr = "";
//vapi.Error = e.getMessage();
System.out.println(e.getMessage());
} finally {
session.close();
}
return vapi;
}
}
when I try to capture the error in spring boot I get this in the console. it shows me the message, but I can't capture that message from SqlExceptionHelper.
2019-12-30 19:19:22.892 WARN 10504 --- [nio-8090-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 50000, SQLState: S0001
2019-12-30 19:19:22.893 ERROR 10504 --- [nio-8090-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : The email already exists
org.hibernate.exception.SQLGrammarException: Error calling CallableStatement.getMoreResults
I have already solved it, but creating an output parameter.
procedure
create proc sp_users
#option int = 0,
#nom_user varchar(50) = null,
#ema_user varchar(50) = null,
#message_error varchar(50) = null output
as
begin
set nocount on
begin try
if #option = 2
begin
if not exists(select * from tb_users where ema_user = #ema_user)
begin
insert into tb_users values(#nom_user,#ema_user)
end
else
begin
set #message_error = 'The email already exists'
raiserror(#message,16,1)
end
end
end try
begin catch
print error_message()
end catch
end
spring boot
#Service
public class CrudUserService implements CrudUserDAO {
#PersistenceContext
private EntityManager em;
#SuppressWarnings({ "unchecked" })
#Override
public ValidateApiResponse MntUser(Integer op, String nom, String ema) {
ValidateApiResponse vapi = new ValidateApiResponse();
Session session = em.unwrap(Session.class);
ProcedureCall call = session.createStoredProcedureCall("sp_users");
call.registerParameter(1, Integer.class, ParameterMode.IN);
call.registerParameter(2, String.class, ParameterMode.IN).enablePassingNulls(true);
call.registerParameter(3, String.class, ParameterMode.IN).enablePassingNulls(true);
call.registerParameter(4, String.class, ParameterMode.OUT).enablePassingNulls(true);
call.setParameter(1, op);
call.setParameter(2, nom);
call.setParameter(3, ema);
call.execute();
String message = (String) call.getOutputParameterValue(4);
if (message == "" || message == null) {
vapi.dTable = call.getResultList();
vapi.Attr = "OK";
} else {
vapi.Attr = "";
vapi.Error = message;
}
return vapi;
}
}
This is the message I get when I enter an email that already exists.
"Msj": "Internal Server Error",
"MsjDetail": "The email already exists",
"dtCollection": [],
"MsjCode": 500

Vaadin table column order is getting changed automatically

I have created a table which has few columns in it. i have given header names for each column. After table initialization i see that column are not appearing in the order in which they are added in table. Column names are reordered alphabetically. Please find below the code of the same.
private Table createGridTable() {
Table grid = new FilterAndPagedTable(this.generateTableOptions());
grid.addContainerProperty("previousPeriod", String.class, null);
grid.addContainerProperty("prevchannelA", Float.class, null);
grid.addContainerProperty("prevchannelB", Float.class, null);
grid.addContainerProperty("prevchannelC", Float.class, null);
grid.addContainerProperty("prevchannelD", Float.class, null);
grid.addContainerProperty("prevAllChannelCons", Float.class, null);
grid.addContainerProperty("presentPeriod", String.class, null);
grid.addContainerProperty("presentchannelA", Float.class, null);
grid.addContainerProperty("presentchannelB", Float.class, null);
grid.addContainerProperty("presentchannelC", Float.class, null);
grid.addContainerProperty("presentchannelD", Float.class, null);
grid.addContainerProperty("presentAllChannelCons", Float.class, null);
grid.addContainerProperty("diffOfPrevNPresent", Float.class, null);
grid.addContainerProperty("percentageChangeOfPrevNPresent", String.class, null);
grid.setColumnHeader("previousPeriod", PrevYearConstants.PREVIOUS_PERIOD);
grid.setColumnHeader("prevchannelA", IemsConstants.A_DC_Power);
grid.setColumnHeader("prevchannelB", IemsConstants.B_Essential_Cooling);
grid.setColumnHeader("prevchannelC", IemsConstants.C_UPS_Power);
grid.setColumnHeader("prevchannelD", IemsConstants.D_Non_Essential_Cooling);
grid.setColumnHeader("prevAllChannelCons", "A + B + C + D");
grid.setColumnHeader("presentPeriod", PrevYearConstants.PRESENT_PERIOD);
grid.setColumnHeader("presentchannelA", IemsConstants.A_DC_Power);
grid.setColumnHeader("presentchannelB", IemsConstants.B_Essential_Cooling);
grid.setColumnHeader("presentchannelC", IemsConstants.C_UPS_Power);
grid.setColumnHeader("presentchannelD", IemsConstants.D_Non_Essential_Cooling);
grid.setColumnHeader("presentAllChannelCons", "A + B + C + D");
grid.setColumnHeader("diffOfPrevNPresent", PrevYearConstants.DIFFERENCE);
grid.setColumnHeader("percentageChangeOfPrevNPresent", PrevYearConstants.PERCENTAGE);
System.out.println(grid.isSortAscending());
System.out.println(grid.isSortEnabled());
grid.setVisibleColumns(new Object[] { "previousPeriod", "prevchannelA", "prevchannelB", "prevchannelC",
"prevchannelD", "prevAllChannelCons", "presentPeriod", "presentchannelA", "presentchannelB",
"presentchannelC", "presentchannelD", "presentAllChannelCons", "diffOfPrevNPresent",
"percentageChangeOfPrevNPresent" });
grid.setSizeFull();
return grid;
}
public FilterAndPagedTableOptions generateTableOptions() {
FilterAndPagedTableOptions fptOptions = new FilterAndPagedTableOptions();
fptOptions.setCollapseAllowed(false);
fptOptions.setColumnReorderingAllowed(false);
fptOptions.setSortAllowed(false);
fptOptions.setShowInbuiltFilterBar(false);
return fptOptions;
}
i am loading data in table as below
List<PrevYearConsumption> tableContainer = viewElements.get(PrevYearConstants.PREV_YEAR_TABLE_CONFIG)
.getTableContainer();
this.grid.setPageLength(tableContainer.size());
BeanItemContainer container = new BeanItemContainer<PrevYearConsumption>(PrevYearConsumption.class);
container.addAll(tableContainer);
this.grid.setContainerDataSource(container);
The order of columns in table is not coming the way i have added in table's header. It is coming in random manner.
I am using vaadin 8.
Kindly help here .
Let me know in case any further info is required.
Is this pure Vaadin 8 or is it Vaadin 7 or is it Vaadin 8 with compatibility packages?
i would try to invoke
grid.setVisibleColumns(new Object[] { "previousPeriod", "prevchannelA", "prevchannelB", "prevchannelC",
"prevchannelD", "prevAllChannelCons", "presentPeriod", "presentchannelA", "presentchannelB",
"presentchannelC", "presentchannelD", "presentAllChannelCons", "diffOfPrevNPresent",
"percentageChangeOfPrevNPresent" });
after loading the data in the table.

Spring Integration JMS header 'priority' must be a number

I'm using Spring Integration JMS 5.1.3 with ActiveMQ, and I found an error with mapping priority:
java.lang.IllegalArgumentException: The 'priority' header value must be a Number.
at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.integration.IntegrationMessageHeaderAccessor.verifyType(IntegrationMessageHeaderAccessor.java:177) ~[spring-integration-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.messaging.support.MessageHeaderAccessor.setHeader(MessageHeaderAccessor.java:305) ~[spring-messaging-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.messaging.support.MessageHeaderAccessor.lambda$copyHeaders$0(MessageHeaderAccessor.java:396) ~[spring-messaging-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at java.util.HashMap.forEach(HashMap.java:1289) ~[na:1.8.0_181]
at org.springframework.messaging.support.MessageHeaderAccessor.copyHeaders(MessageHeaderAccessor.java:394) ~[spring-messaging-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.integration.support.MessageBuilder.copyHeaders(MessageBuilder.java:179) ~[spring-integration-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.integration.support.MessageBuilder.copyHeaders(MessageBuilder.java:48) ~[spring-integration-core-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.integration.jms.ChannelPublishingJmsMessageListener.onMessage(ChannelPublishingJmsMessageListener.java:327) ~[spring-integration-jms-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:736) ~[spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:696) ~[spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:674) ~[spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:318) [spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:257) [spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1189) [spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1179) [spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1076) [spring-jms-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]
My message header as following:
I have disabled the inbound message header for Priority:
#Bean
public DefaultJmsHeaderMapper jmsHeaderMapper() {
final DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper();
{
mapper.setMapInboundDeliveryMode(true);
mapper.setMapInboundExpiration(true);
mapper.setMapInboundPriority(false);
}
return mapper;
}
Is there any resolution for this issue ?
The inbound message in DEBUG log:
2019-03-01 09:51:51.278 DEBUG 4224 --- [sage-listener-1] .i.j.ChannelPublishingJmsMessageListener : converted JMS Message [ActiveMQTextMessage {commandId = 19, responseRequired = true, messageId = ID:hot-srv-wso2-01-44620-1551368625113-1:4:3:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:hot-srv-wso2-01-44620-1551368625113-1:4:3:1, destination = queue://extraction-request, transactionId = null, expiration = 0, timestamp = 1551408495720, arrival = 0, brokerInTime = 1551408705168, brokerOutTime = 1551408705172, correlationId = ID:hot-srv-wso2-01-44620-1551368625113-1:3:3:1:1, replyTo = queue://extraction-response, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = org.apache.activemq.util.ByteSequence#67153d1f, dataStructure = null, redeliveryCounter = 6, size = 0, properties = {Connection=Keep-Alive, User-Agent=Apache-HttpClient/4.1.1 (java 1.5), Host=10.10.15.235:8280, Accept-Encoding=gzip,deflate, jms_type=vn.sps.ias.domain.Response, priority=4, JMS_DESTINATION=ReqOutput, JMS_REPLY_TO=ReqROutput, Content-Length=38, JMS_REDELIVERED=false, Content-Type=application/json, timestamp=1551408705049}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = {"text":"1 was processed"}}] to integration Message payload []
For me, this problem occurred when I used the header "priority" in a custom message.
MessageBuilder.withPayload(val).setHeader("priority", true).build();
It seems as "priority" is a header value you must not use.
Changing to
MessageBuilder.withPayload(val).setHeader("prio", true).build();
solved the problem for me.

Message is not receiving in JMS Simple Receiver Program

I have created Simple JMS Client and Receiver Program. I have used JDk1.7 and activeMQ 5.10.0.My Sender code is executing with particlur message
MessageProducer mp= session.createProducer(destinatin);
Message message = session.createTextMessage("Hi Welcome to ActiveMQ Example");
mp.send(message);
System.out.println("Message Has Sent");
and
Receiver code My Reciver Code is this one where it is not printing anything.
and after some time it gives me error of connection timeout.Could you find out where I am creating mistake...
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://Name-PC:61616");
//connectin creation
Connection con = connectionFactory.createConnection();
Session session = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
Destination dest= new ActiveMQQueue("Test1.Queue");
MessageConsumer Consumer = session.createConsumer(dest);
Message message = Consumer .receive();
System.out.println("End of Message1");
TextMessage text = (TextMessage) message;
System.out.println("Message" +text.getText());
System.out.println("End of Message");
In http://localhost:8161/admin/queues.jsp it is showing content on
Name Test1.Queue, Number Of Pending Messages =1, Number Of Consumers=1 Messages Enqueued =1,but Messages Dequeued not showing anything
You need to start the connection.
This groovy code works for me:
factory = new ActiveMQConnectionFactory("tcp://tpmint:61616");
dest = new ActiveMQQueue("foo.bar");
conn = null;
session = null;
consumer = null;
try {
conn = factory.createConnection();
println "Connected: $conn";
session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
println "Session: $session";
consumer = session.createConsumer(dest);
println "Consumer: $consumer";
conn.start();
msg = consumer.receive(1000);
if(msg==null) println "Timeout";
else println "Msg:$msg";
} finally {
if(consumer!=null) try { consumer.close(); println "Consumer Closed";} catch (e) {}
if(session!=null) try { session.close(); println "Session Closed";} catch (e) {}
if(conn!=null) try { conn.close(); println "Connection Closed"; } catch (e) {e.printStackTrace(System.err);}
}
Output:
Connected: ActiveMQConnection {id=ID:tpmint-51137-1445798087365-0:8,clientId=null,started=false}
Session: ActiveMQSession {id=ID:tpmint-51137-1445798087365-0:8:1,started=false}
Consumer: ActiveMQMessageConsumer { value=ID:tpmint-51137-1445798087365-0:8:1:1, started=false }
Msg:ActiveMQTextMessage {commandId = 7, responseRequired = false, messageId = ID:tpmint-58446-1445793097761-4:2:1:1:3, originalDestination = null, originalTransactionId = null, producerId = ID:tpmint-58446-1445793097761-4:2:1:1, destination = queue://foo.bar, transactionId = null, expiration = 0, timestamp = 1445798905534, arrival = 0, brokerInTime = 1445798905534, brokerOutTime = 1445802982704, correlationId = , replyTo = null, persistent = false, type = , priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = org.apache.activemq.util.ByteSequence#5346e84e, dataStructure = null, redeliveryCounter = 2, size = 0, properties = {JMSXMessageCounter=1}, readOnlyProperties = true, readOnlyBody = true, droppable = false, text = hey hey}
Consumer Closed
Session Closed
Connection Closed

Windows Starting a service returns ERROR_SERVICE_DISABLED

I have successfully created a service:
hService = CreateService(hSCManager,lpServiceName,lpDisplayName,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
dwStartType,
SERVICE_ERROR_NORMAL,
lpFilePath,
NULL,
NULL,
NULL,
NULL,
NULL);
But when I try to start the service:
hService = OpenService(hSCManager, lpServiceName, SERVICE_ALL_ACCESS);
if (StartService(hService,0,NULL)== NULL){
DWORD error = GetLastError();
}
The error is equal to ERROR_SERVICE_DISABLED. How does one enable the service? This is not immediately obvious from the Windows API documentation.

Resources