In our application we have couple of webservices.i need to get the userids(means who has loged in and webservice name) for auditing purpose i need to store.
Could anyone suggest which will be either filter chain or Interceptors and how to get the webservice name.
You can use PreSecurityInterceptor for doing this ,request from client will first goto it and there you can log the data in db or file .
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
/**
* This interceptor verify the method name and log the details
* */
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ResourceMethod;
//import org.jboss.resteasy.core.ResourceMethodInvoker;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.Failure;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.interception.PreProcessInterceptor;
#Provider
#ServerInterceptor
public class PreSecurityInterceptor implements PreProcessInterceptor {
#Context HttpServletRequest req;
#Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
System.out.println("********************************************* pre process *****************************");
System.out.println(new Date() + " Method : " + method.getMethod().getName() + " being called from "
+ req.getRemoteHost()+":"+req.getLocalPort()+": Remote Port "+req.getRemotePort());
if ( "defaultMethod".equalsIgnoreCase(method.getMethod().getName())) {
return null; // normal flow continues
} else {
System.out.println(new Date() + " Method : " + method.getMethod().getName() + " Precondition failed ");
return (ServerResponse) Response
.status(Response.Status.PRECONDITION_FAILED).entity("invalid method details provided !!").build();
}
}
}
Related
I am trying to log some info during api call in console in my Spring Boot application. I have used Spring Aop and trying to use #Around advise with #Pointcut by using ProceedingJoinPoint. The program is compiling successfully & runs quite well. But logging is not happening in console. I think my Pointcut is not triggering. My code is given bellow. Please help.
package org.mycomp.mat.aspect;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.mycomp.mycompmat.user.profile.service.UserProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
#Aspect
#Component
public class LoggingAspect {
Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
#Pointcut("execution(public * org.mycomp.mat.repository..*(..))")
public void requestPointcut() {
}
#Around("requestPointcut()")
public Object requestLogger(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
ObjectMapper objectMapper = new ObjectMapper();
String methodName = proceedingJoinPoint.getSignature().getName();
String className = proceedingJoinPoint.getTarget().getClass().toString();
Object[] inputArguments = proceedingJoinPoint.getArgs();
logger.info(
"Operation " + methodName +
" Of " + className +
" On " + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) +
" With Input Parameters :-> " + objectMapper.writeValueAsString(inputArguments)
);
Object object = proceedingJoinPoint.proceed();
logger.info(objectMapper.writeValueAsString(object));
return object;
}
}
the issue is with the pointcut expression missing * for the class name part
like org.mycomp.mat.repository.myClass.myMethod({arguments})
change from #Pointcut("execution(public * org.mycomp.mat.repository..*(..))") to #Pointcut("execution(public * org.mycomp.mat.repository.*.*(..))")
I am trying to trigger function thru amazon sqs trigger. The trigger is working fine but, the message is not passed into the my function.
Here is my lambda function
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class x implements RequestHandler<RequestClass, ResponseClass> {
private LambdaLogger logger;
public void log(String message) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
logger.log(sdf.format(cal.getTime()) + " " + message+"\n");
}
public ResponseClass handleRequest(RequestClass request, Context context) {
this.logger = context.getLogger();
log("Request " + request);
if (request == null || (request.getFilename() == null && request.getRecords() == null)) {
log("No file was passed in");
throw new RuntimeException("No file was passed in");
}
return new ResponseClass(null);
}
}
And request class is https://pastebin.com/Q1G6bnrA
The records are always null when I see logs.
Have you taken care of the execution role permissions of the Lambda?
From here:
Execution Role Permissions
Lambda needs the following permissions to manage messages in your Amazon SQS queue. Add them to your function's execution role.
sqs:ReceiveMessage
sqs:DeleteMessage
sqs:GetQueueAttributes
The following code is working fine for me:
package au.com.redbarn.aws.lambda2lambda_via_sqs;
import java.util.List;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;
import lombok.extern.log4j.Log4j2;
#Log4j2
public class SQSConsumerLambda implements RequestHandler<SQSEvent, String> {
#Override
public String handleRequest(SQSEvent input, Context context) {
log.info("message received");
List<SQSMessage> records = input.getRecords();
for (SQSMessage record : records) {
log.info(record.getBody());
}
return "Ok";
}
}
Maybe try using SQSEvent instead of your own RequestClass.
I want to get current country name in java . I use this code.
private HttpServletRequest request;
Locale currentCountry = request.getLocale();
System.out.println(currentCountry.getDisplayCountry());
But it through an NullPointerException like Caused by: java.lang.NullPointerException. at 2nd line. Please Help me anyone.
The snippet of code is not enough to tell why you got the Null Pointer. I assume you are use servlet on server side.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HttpServletBean;
public class MyServlet extends HttpServletBean {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Locale userlocale = request.getLocale();
out.println("Your Country : " + userlocale.getCountry());
out.println();
out.println("");
}
}
I am currently working on a Java Web application that runs on Apache Tomcat 7. Due to the fact that I want to log some information into a database, I use the following configuration file information for initiating my Logger:
log4j.rootLogger = DEBUG, DB
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.URL=jdbc:mysql://localhost:3306/cap_recommender_log
log4j.appender.DB.driver=com.mysql.jdbc.Driver
log4j.appender.DB.user=log_user
log4j.appender.DB.password=some_password
log4j.appender.DB.sql=INSERT INTO notify_service_log(date, logger, level, message) VALUES('%d{YYYY-MM-dd}','%C','%p','%m')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
Also, the notify_service_log table is as follows:
CREATE TABLE `notify_service_log` (
`date` date NOT NULL,
`logger` varchar(256) NOT NULL,
`level` varchar(10) NOT NULL,
`message` text NOT NULL,
KEY `index_level` (`level`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Finally, the web service code is as follows:
package com.imis.cap.service.notify;
import com.imis.cap.module.etl.EtlModuleClient;
import gr.aia.cap.eventbroker.v1.ArrayOfServiceMessage;
import gr.aia.cap.eventbroker.v1.BooleanResponse;
import gr.aia.cap.eventbroker.v1.ServiceMessage;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.jws.WebService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
#WebService(serviceName = "NotifyService", portName = "HttpBinding_NotifyService", endpointInterface = "gr.aia.cap.eventbroker.v1.NotifyService", targetNamespace = "http://www.aia.gr/cap/eventbroker/v1/", wsdlLocation = "WEB-INF/wsdl/NotifyService/NotifyService.wsdl")
public class NotifyService {
private String username;
private String password;
private String log_properties_file;
private DataSource registration_db;
private static org.apache.log4j.Logger notifyServiceLogger =
Logger.getLogger(NotifyService.class);
public NotifyService() {
Context context;
try {
context = (Context) new InitialContext().lookup("java:comp/env");
this.username = (String) context.lookup("CAP_RECOMMENDER_UNAME");
this.password = (String) context.lookup("CAP_RECOMMENDER_PASS");
this.registration_db = (DataSource) context.lookup("jdbc/cap_registration_db");
this.log_properties_file = (String) context.lookup("NOTIFY_SERVICE_LOG_PROPERTIES_FILE");
}catch(NamingException e) {
System.err.println(e.getMessage());
notifyServiceLogger.error("NotifyService: NamingException occured during construction. Message: " +
e.getMessage());
}
PropertyConfigurator.configure(this.log_properties_file);
notifyServiceLogger.info("NotifyService: Object constructor completed successfully.");
}
public gr.aia.cap.eventbroker.v1.BooleanResponse notify(gr.aia.cap.eventbroker.v1.NotifyRequest request) throws ParseException {
ArrayOfServiceMessage arrayOfServiceMsg = new ArrayOfServiceMessage();
ServiceMessage msg = new ServiceMessage();
BooleanResponse response = new BooleanResponse();
EventTypeReader eventType = new EventTypeReader(request);
String regCode = request.getRegistrationCode();
String dbRegCode = "";
**notifyServiceLogger.info("NotifyService.notify(): Called with reg-code: " + request.getRegistrationCode() + ".");**
/**Some more code**/
return new BooleanResponse(); //Sample response
}
}
The client Code that performs the call of the notify procedure is as follows:
package notifyclient;
import gr.aia.cap.eventbroker.v1.ArrayOfAttribute;
import gr.aia.cap.eventbroker.v1.BooleanResponse;
import gr.aia.cap.eventbroker.v1.EventType;
import gr.aia.cap.eventbroker.v1.NotifyRequest;
public class NotifyClient {
public static void main(String[] args) {
NotifyRequest request = new NotifyRequest();
request.setRegistrationCode("blasdadasd");
request.setAttributes(new ArrayOfAttribute());
request.setEventType(EventType.USER);
BooleanResponse response = notify(request);
System.out.println("Output: " + response.getErrors().getServiceMessage().toString());
}
public static gr.aia.cap.eventbroker.v1.BooleanResponse notify(gr.aia.cap.eventbroker.v1.NotifyRequest request) {
gr.aia.cap.eventbroker.v1.NotifyService_Service service = new gr.aia.cap.eventbroker.v1.NotifyService_Service();
gr.aia.cap.eventbroker.v1.NotifyService port = service.getHttpBindingNotifyService();
return port.notify(request);
}
}
I have to inform you at this point that the required classes that are needed to perform the Web Service call are automatically generated by Netbeans 7.2.
The problem lies on the fact that the Constructor's message is logged into the database, but the information message in the notify function is never logged. Why is this happening? Any ideas?
As comments state, adding PropertyConfigurator.configure(this.log_properties_file); on the line above the logger call in the notify() method resolved the problem.
I have written a servlet for approval of leaves. In this servlet I have also written code to send a mail. Due to this, it shows HTTP 405 error. If I remove the code which sends a mail, then it does not show the error, but I need the mail code.
package mis;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.jdo.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class approve extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try{
HttpSession session = req.getSession(true);
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery(Leave_bal.class);
query1.setFilter("emp_Id == emp");
query1.declareParameters("String emp");
List<Leave_bal> results1 = (List<Leave_bal>)query1.execute(session.getAttribute("emp_Id").toString());
String plan="";
String unplan="";
String planleave_result="" ;
String unplanleave_result="";
for (Leave_bal e : results1)
{
plan=e.getplan_leave();
resp.getWriter().println("Planned_Leave"+plan);
unplan=e.getunplan_leave();
resp.getWriter().println("Unplanned:"+unplan);
}
int plan_leave=Integer.parseInt(plan);
int unplan_leave=Integer.parseInt(unplan);
String ID=req.getParameter("id");
resp.getWriter().println(ID);
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Leave_detail.class);
query.setFilter("id == ID");
query.declareParameters("String ID");
List<Leave_detail> results = (List<Leave_detail>)query.execute(ID);
String plan_detail="";
String duration="";
for (Leave_detail e : results)
{
plan_detail=e.getLeave_Type();
duration=e.getdurtn();
//f=e.getfrom();
//t=e.getto();
}
resp.getWriter().println("duration "+duration);
resp.getWriter().println("Planned_selected "+plan_detail);
int duration_integer=Integer.parseInt(duration);
resp.getWriter().println("duration "+duration_integer);
//String duration=req.getParameter("date");
// resp.getWriter().println("diffrence:"+duration);
//int workingdays=Integer.parseInt(duration);
//String Leave = req.getParameter("a");
// resp.getWriter().println("planned:"+Leave);
if(plan_detail.equals("UNPLAN"))
{
unplan_leave=unplan_leave-duration_integer;
unplanleave_result=String.valueOf(unplan_leave);
planleave_result=plan;
resp.getWriter().println("Planned After Change"+unplanleave_result);
//st="Applied";
}
if(plan_detail.equals("PLAN"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("LWP"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("Onduty"))
{
planleave_result=plan;
unplanleave_result=unplan;
}
Leave_detail status_update = pm.getObjectById(Leave_detail.class,ID);
status_update.setstatus("Approved");
pm.makePersistent(status_update);
Leave_bal ed1=new Leave_bal(session.getAttribute("emp_Id").toString(),planleave_result,unplanleave_result);
pm.makePersistent(ed1);
//code for mail
RequestDispatcher dispatcher = getServletConfig ( ) .getServletContext ().getRequestDispatcher("/MailServiceapply");
dispatcher.forward (req, resp) ;
pm.close();
}
catch(Exception a )
{
resp.getWriter().println(a .getMessage());
} finally{
}
resp.sendRedirect("hr.jsp#LMS");
}
}
This thread on Java Forums provides some hints for this error, like
HTML form invokes POST operation and servlet doesn't implement doPost (direct link)
Inital HTML form not declared in web.xml file (or misspelled) (direct link)
At the bottom of this servlet you're forwarding the request to another servlet:
RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/MailServiceapply");
dispatcher.forward(req, resp);
This is not only a poor approach, certainly because you've written data to the HTTP response before in the servlet and you thus risk IllegalStateException (writing to the response should take place in a JSP), but doing so also requires that the servlet in question also implements doGet(). The error which you're facing suggests that this mail service servlet has only the doPost() implemented.
You need to add a doGet() method to the mail service servlet and use RequestDispatcher#include() to invoke it.
dispatcher.include(req, resp);
Needless to say that this is still a poor approach. You'd rather like to refactor the mail code logic into a standalone Java class which you then import and invoke in both servlets and put all the presentation logic in a JSP.