Passing value of variable from one method to another - java

This seems so easy, but I don't know why I'm having such difficulty with it...So in the getURL, I return the String "total". I'm trying to return the SAME value "total" already has in the method handleRequest. Suggestions? Thanks in advance!
public class Multiply implements Controller {
static int product;
private static String total;
public static String getURL(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
String[] item = queryString.split("&");
product = 1;
for (int i = 0; i < item.length; i++) {
String[] s = item[i].split("=");
String name = s[0];
String value = s[1];
int numValue = Integer.parseInt(value);
product = product * numValue;
}
total = "" + product;
return total;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Mess = total;
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}

You have a number of problems with your implementation of this. First, by declaring total static, all instances of this class will have the same value of total. If you're using a framework that creates your controller and reuses it, this could lead to problems because all instances of the class will be referring to and updating the same member field.
What you want is to have your getURL method to return the value of total and then call it from your handleRequest. getURL can be static because it relies on no non-static member fields. You should really rename getURL to getTotal or getTotalFromURL because that is what you're doing. What you're asking getURL to do is actually a side effect, and should be avoided as a practice.
public class Multiply implements Controller {
public static String getURLTotal(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
String[] item = queryString.split("&");
int product = 1;
for (int i = 0; i < item.length; i++) {
String[] s = item[i].split("=");
String name = s[0];
String value = s[1];
int numValue = Integer.parseInt(value);
product = product * numValue;
}
return Integer.toString(product);
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String Mess = Multiply.getURLTotal(request);
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}

total is a member variable to the class Multiply. You should have no problems accessing it from either method. Keep in mind that it is uninitialized. So unless you call getURL before handleRequest then total will not be assigned to any String and will give you an error.
Also, I would watch your capitalization in several areas.
edit: Just for clarification, you technically aren't passing a value from one method to another. You are accessing a shared member variable between two methods.

Related

How to call the method in Java clicking on a link?

This is my servlet:
#WebServlet({ "/Response", "/reportsto" })
public class Response extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Response() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
services2 messageservice = new services2();
services3 jiraservice = new services3();
service4 empid = new service4();
String id = request.getParameter("ManagerId");
try {
String name="";
String id1 =empid.getEmpId(id);
System.out.println("id is ===> "+id1);
Map<Object, Object> map=messageservice.getReportees(id1);
Set<Map.Entry<Object,Object>> s1=map.entrySet();
for (Iterator<Map.Entry<Object,Object>> iterator = s1.iterator(); iterator.hasNext();) {
Map.Entry<Object,Object> entry = iterator.next();
Object name1 = entry.getKey();
Object value = entry.getValue();
PrintWriter out=response.getWriter();
out.println("<html><body><table>\r\n" +
"<tr>\r\n" +
"<th>User Id</th>\r\n" +
"<th>Username</th>\r\n" +
"</tr>\r\n" +
"<tr>\r\n" +
"<td>"+value+"</td>\r\n" +
"<td><a href=''>"+name1+"</a></td>\r\n" +
"</tr>\r\n" +
"</table></body></html>");
//how should I pass the object value to getJiras which accepts the strings.
}
I will get the output as:
User Id Username
AR12345 Anagha R
So If I click on Anagha the userid must be passed to the getJiras which has return type as Map Object and then It should process and display the
CHA-3603: Validating Release on the browser in the same page of the above output.
getJiras()
public class services3{
public Map<Object, Object> getJiras(String values) throws Exception {
String api = "https:*****";
String id = values;
String ext= "******";
String url = api+id+ext;
String name = "******";
String password = "********";
String authString = name + ":" + password;
String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
System.out.println("Base64 encoded auth string: " + authStringEnc);
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept("application/json")
.header("Authorization", "Basic " + authStringEnc)
.get(ClientResponse.class);
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
//here I am trying to parse the json data.
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(output);
JSONArray jsonarr_1 = (JSONArray) jobj.get("issues");
System.out.println("The total number of issues in validating release are:"+jsonarr_1.size());
Map<Object, Object> map=new HashMap<Object,Object>();
for(int i=0;i<jsonarr_1.size();i++){
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONObject jsonobj_2 = (JSONObject)jsonobj_1.get("fields");
JSONObject status1 = (JSONObject)jsonobj_2.get("status");
JSONObject issuetype = (JSONObject)jsonobj_2.get("issuetype");
Object obj1 = jsonobj_1.get("key");
Object obj2 = status1.get("name");
map.put(obj1, obj2);
}
return map;
}
Also how can I also display the json array size which is being printed in the browser.The problem is getting complicated day by day,Please help to solve this problem.Thanks in advance
You can create another servlet or use same servlet to make one more get request. That request will call to jira service.
Case 1: Create another servlet, it is similar to what you are doing
Case 2: You can custom your current servlet method doGet. Sample code is below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestAction = request.get("action");
if("detail".equals(requestAction)) {
services3 service = new services3();
//get result.
} else if("view".equals(requestAction)){
//your current code
}
//add result to response
}

trying to change request in Filter, so that it reflect in #RequestParam

I am trying the read the request attributes and change them using Filter, so that in Controller I would receive changed values as per my need. but the changes I did in Filter is not reflected in #RequestParam.
My controller:
public Response getDetails(HttpServletRequest req, #RequestParam(required = false) String userId) {
System.out.println("attrib in request:"+req.getParameter("userId"));
System.out.println("attrib in RequestParam:"+userId);
}
My Filter:
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
System.out.println("inside filter---------------------------");
HtmlRequestWrapper req = new HtmlRequestWrapper(request);
chain.doFilter(req, response);
} catch (Exception ex) {
request.setAttribute("errorMessage", ex);
// request.getRequestDispatcher("/WEB-INF/views/jsp/error.jsp").forward(request,
// response);
}
}
My HttpServletRequestWrapper(HtmlRequestWrapper):
public class HtmlRequestWrapper extends HttpServletRequestWrapper {
public HtmlRequestWrapper(ServletRequest request) {
super((HttpServletRequest) request);
}
public String sanitize(String input) {
String result = "";
result = input + "bla bla";
return result;
}
public String getParameter(String paramName) {
String value = super.getParameter(paramName);
value = sanitize(value);
return value;
}
public String[] getParameterValues() {
String values[] = null;
// String values[] = request.getParameterValues(paramName);
for (Enumeration<String> en = super.getParameterNames(); en.hasMoreElements();) {
String paramName = (String) en.nextElement();
values = super.getParameterValues(paramName);
int n = values.length;
for (int i = 0; i < n; i++) {
System.out.println("param val before: " + values[i]);
values[i] = sanitize(values[i]);
System.out.println("param val after: " + values[i]);
}
}
return values;
}
public Map<String, String[]> getParameterMap() {
Map<String, String[]> paramMap = new HashMap<>();
String values[] = null;
for (Enumeration<String> en = super.getParameterNames(); en.hasMoreElements();) {
String paramName = (String) en.nextElement();
values = super.getParameterValues(paramName);
int n = values.length;
for (int i = 0; i < n; i++) {
System.out.println("param val before in map: " + values[i]);
values[i] = sanitize(values[i]);
System.out.println("param val after in map: " + values[i]);
}
paramMap.put(paramName, values);
this.getRequest().setAttribute(paramName, values);
}
return Collections.unmodifiableMap(paramMap);
}
}
as you can see i am just trying to append some text to the attribute values.In real scenario would be cleaning and appending with some logic.
Note: In my controller I get the changed value in req.getParameter("userId") but #RequestParam(required = false) String userId contains the same old values passed down from the actual request.
I want #RequestParam(required = false) String userId to reflect the changes in req.getParameter("userId").
updating(Adding WebConfig class):
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ServiceInterceptor());
}
#Bean
public Filter htmlFilter() {
return new HtmlFilter();
}

how variables accessible in anonymous class?

I have following code :
class A extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletRespons
response) throws ServletException, IOExceptio
{
String str= "String In doGet()";
JsonBatchCallback<Users> callback = new
JsonBatchCallback<Users>(){
String inThisClass = str; // Showing me error
}
}
}
str is not accessible. How i can access "str".
My Actual Code is as follows :
public class SyncTask extends HttpServlet {
private static final long serialVersionUID = 1L;
final Logger logger = Logger.getLogger(this.getClass().getName());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String domain = request.getParameter("DomainName");
String reqAdminEmail = request.getParameter("AdminEmail");
String searchRegex = request.getParameter("searchRegex");
Boolean manualSync = false;
if(reqAdminEmail != null){
manualSync = true;
}
String adminEmail = "";
try{
Date startTime = new Date();
Manager mangerObj = new Manager("MASTER");
final String SERVICE_ACCOUNT_EMAIL = Constant.getServiceAccountEmail();
final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = Constant.getServiceAccountPkcs12FilePath();
Collection<String> SCOPES = new ArrayList<String>();
SCOPES.add("https://www.googleapis.com/auth/admin.directory.user");
SCOPES.add("https://www.googleapis.com/auth/admin.directory.orgunit");
String nextToken = null;
int noOfUsers = 0;
mangerObj = new Manager(domain);
Configuration config = mangerObj.getConfiguration();
if(config==null)
return;
else
adminEmail = config.getAdminEmail();
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setServiceAccountUser(adminEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Directory directoryService = new Directory.Builder(httpTransport, jsonFactory, credential).setApplicationName("Directory ").build();
BatchRequest batch = directoryService.batch();
do{
List list = directoryService.users().list();
list.setCustomer("my_customer");
list.setMaxResults(500);
list.setPageToken(nextToken);
list.setFields("nextPageToken,users(relations,orgUnitPath,primaryEmail,name)");
if(searchRegex != null ){
if(searchRegex.isEmpty() == false){
list.setQuery("email:"+searchRegex+"*");
}
}
JsonBatchCallback<Users> callback = new JsonBatchCallback<Users>() {
#Override
public void onSuccess(Users users, HttpHeaders responseHeaders) {
nextToken = users.getNextPageToken(); // i'm not able to access nextToken
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
System.out.println("Error Message: " + e.getMessage());
}
};
list.queue(batch, callback);
}while(nextToken != null);
try {
batch.execute();
} catch(Exception ex){
ErrorHandler.errorHandler(this.getClass().getName(), ex);
}
}catch(Exception ex){
ErrorHandler.errorHandler(this.getClass().getName(), ex);
}
}
I have updated my code where actually i am getting error. I want to access nextToken into anonymous class,but i not able to accesss.
Error as follows :
nextToken cannot be resolved to a variable
You need to make the str variable final.
As a matter of fact the inThisClass variable is redundant, at least in what you posted so far.
But your actual code shows a different error message from your sample code. Your actual code cannot be written, because you don't have write-access to local variables in enclosing scopes from anonymous classes. You will have to think of something else, such as a final StringBuilder.
Declare str in doGet as final:
final String str = "String In doGet()";
Anonymous classes can access only final local variables of an outer method. In Java 8 it was changed.
Also your IDE should assist you with fixes of such errors.

NullPointer trying to retrieve an Integer value

I have a problem when retrieving data (an Integer value) between servlets, when I want to multiply the value retrieved. I have this function in my first servlet,
private int totalNumberOf(Map<String,Integer> cart) {
int counter = 0;
for (String key : cart.keySet())
counter += cart.get(key);
return counter;
}
And I also have the attribute for it (placed at the end of the doGet() method)...
req.setAttribute("quantity", new Integer(totalNumberOf(cart)));
, a function that gives me the total number of products that are in the cart, which updates the value every time I add something to the cart so when I finish buying I can get an updated value of the number of products that are currently in the cart.
The problem comes now, when I try to do the fictional checkout (because I just have a generic price for every type of product) and I have to multiply the number of items by the generic price (here's where the NullPointer shows up).
Here's the code of my second servlet,
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity;
int toPay;
int genericValue = 20;
quantity = (Integer) req.getAttribute("quantity");
toPay = quantity.intValue() * genericValue; // NullPointer
}
I've tried everything in every way but I can't get rid of that ugly NullPointer. Hope you can help me a bit with this...
UPDATE Servlet1
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida = "";
Map<String,Integer> carrito = null;
String articuloElegido = req.getParameter("producto");
HttpSession session = req.getSession();
if (session.isNew()) {
session.invalidate();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
dispatcher.forward(req, res);
}
else {
String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
if (session.getAttribute("carrito") == null) {
carrito = new HashMap<String,Integer>();
session.setAttribute("carrito",carrito);
mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
}
else {
carrito = (Map<String,Integer>) session.getAttribute("carrito");
mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
}
insertarEnCarrito(carrito, articuloElegido);
}
req.setAttribute("mensaje", mensajeBienvenida);
req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
req.setAttribute("cantidad", numeroTotalLibros(carrito));
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
dispatcher.forward(req, res);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
if (carrito.get(articulo) == null){
carrito.put(articulo, new Integer(1));
}
else {
int numeroArticulos = (Integer)carrito.get(articulo).intValue();
carrito.put(articulo, new Integer(numeroArticulos+1));
}
}
private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
String cestaEnHTML = "";
for (String key : carrito.keySet())
cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
return cestaEnHTML;
}
private int numeroTotalLibros(Map<String,Integer> carrito) {
int counterLibro = 0;
for (String key : carrito.keySet())
counterLibro += carrito.get(key);
return counterLibro;
}
}
Servlet2
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida;
String cestaDeLaCompraEnHTML;
mensajeBienvenida = (String) req.getAttribute("mensaje");
cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY>" + mensajeBienvenida + "<br>");
out.println(cestaDeLaCompraEnHTML + "<br>");
out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
out.println("Seguir comprando!</BODY></HTML>");
out.println("Anular Compra</BODY></HTML>");
out.println("Pagar Compra</BODY></HTML>");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Servlet3
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer cantidadLibro;
int pagar;
int valorLibro = 20;
Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
Usuario usuario = (Usuario) session.getAttribute("user");
cantidadLibro = (Integer) req.getAttribute("cantidad");
if (cantidadLibro == null){
cantidadLibro = 0;
} else {
cantidadLibro = (Integer) req.getAttribute("cantidad");
}
// pagar = cantidadLibro.intValue() * valorLibro;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
out.println("<br><p>Total a pagar por su compra - " + "<br>");
out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
out.println("<br><p>User ID - " + usuario.getId() + "<br>");
session.invalidate();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Besides the refactoring and optimisation that your code might need, the problem you are refering to is that your are setting the attribute "cantidad" to the request instead of the session.
In Servlet1, replace this
req.setAttribute("cantidad", numeroTotalLibros(carrito));
with this
session.setAttribute("cantidad", numeroTotalLibros(carrito));
And in Servlet3, replace this
cantidadLibro = (Integer) req.getAttribute("cantidad");
with this
cantidadLibro = (Integer) session.getAttribute("cantidad");
The reason is that you are forwarding your request from Servlet1 to Servlet2, and so in Servlet2 you can access the "forwarded" request and all its attributes, BUT Serlvet3 is called independently at a later stage. I guess that is when you press "Pagar" in the rendered HTML page. Therefore, you can no longer access those attributes via the request because it is a different request. You can instead access them via the session if you stored them there previously.
Hope this helps.
Have you ever heard about debugging tools?
Your quantity variable has null value, it could be because of abscense attribute quantity in request. That is why you got NPE: null * (primitive numeric constant) -> NullPointerException.
From your code it it looks like "quantity.intValue()" throws your null pointer because quantity is null. Try this:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity = 0;
int toPay;
int genericValue = 20;
if (req.getAttribute("quantity") != null) {
quantity = (Integer) req.getAttribute("quantity");
}
toPay = quantity.intValue() * genericValue;
}
Notice not only do I initialize quantity with a value of 0 (so that it is not null) I also add a null check to "req.getAttribute("quantity")" so that you do not assign null to quantity in the case where .getAttribute returns null.
It's likely that your getAttribute function returned null. Remember to do null checking in code. I suggest a if (quantity != null) check before you call .intValue()
Another possible solution would be to check what .getAttribute() returned instead of checking what quantity was set to. You could also give quantity a default value.
if (req.getAttribute("quantity") == null) {
quantity = 0;
} else {
quantity = (Integer) req.getAttribute("quantity");
}

HttpServletRequestWrapper removed parameter still showing up

I'm trying to filter out a query parameter named 'reason' using a Filter in java/jsp.
Basically, the filter is in place to ensure that a user has entered a 'reason' for viewing a page. If they have not, it needs to redirect them to the 'enter reason' page. Once they have entered a valid reason, they can continue on to the page they requested.
So the basics of it work. However, the 'reason' is sent via a query paremter (i.e. GET parameter). Once the user selects a reason, the reason parameter is being forwarded on to the page they wanted to see. This is a problem, since checking if the reason paremeter exists is one of the main ways the filter determines if the user can move on.
I've tried extending HttpServletRequestWrapper, and overrode a bunch of methods (i.e. getPameter, etc) in an effort to remove the 'reason' parameter. However, I haven't been able to see the parameter get removed. Once the Filter forwards on to the requested page, the 'reason' parameter is always in the query string (i.e. the url in the browser url bar) as a GET parameter.
My filter class looks like:
public final class AccessRequestFilter implements Filter {
public class FilteredRequest extends HttpServletRequestWrapper {
public FilteredRequest(ServletRequest request) {
super((HttpServletRequest)request);
}
#Override
public String getParameter(String paramName) {
String value = super.getParameter(paramName);
if ("reason".equals(paramName)) {
value = null;
}
return value;
}
#Override
public String[] getParameterValues(String paramName) {
String[] values = super.getParameterValues(paramName);
if ("reason".equals(paramName)) {
values = null;
}
return values;
}
#Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(getParameterMap().keySet());
}
#Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> params = new HashMap<String, String[]>();
Map<String, String[]> originalParams = super.getParameterMap();
for(Object o : originalParams.entrySet()) {
Map.Entry<String, String[]> pairs = (Map.Entry<String, String[]>) o;
params.put(pairs.getKey(), pairs.getValue());
}
params.remove("reason");
return params;
}
#Override
public String getQueryString() {
String qs = super.getQueryString();
return qs.replaceAll("reason=", "old_reason=");
}
#Override
public StringBuffer getRequestURL() {
String qs = super.getRequestURL().toString();
return new StringBuffer( qs.replaceAll("reason=", "old_reason=") );
}
}
private FilterConfig filterConfig = null;
private static final Logger logger = MiscUtils.getLogger();
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.debug("Entering AccessRequestFilter.doFilter()");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession();
boolean canView = false;
long echartAccessTime = 0L;
String demographicNo = "";
String reason = "";
Date current = new Date();
String user_no = (String) session.getAttribute("user");
ProgramProviderDAO programProviderDAO = (ProgramProviderDAO)SpringUtils.getBean("programProviderDAO");
ProgramQueueDao programQueueDao = (ProgramQueueDao)SpringUtils.getBean("programQueueDao");
// Check to see if user has submitted a reason
reason = request.getParameter("reason");
demographicNo = request.getParameter("demographicNo");
Long demographicNoAsLong = 0L;
try {
demographicNoAsLong = Long.parseLong( demographicNo );
} catch (Exception e) {
logger.error("Unable to parse demographic number.", e);
}
if (reason == null) {
// If no reason was submitted, see if user still has time remaining on previous submission (if there was one)
try {
echartAccessTime = (Long)session.getServletContext().getAttribute("echartAccessTime_" + demographicNo);
} catch (Exception e) {
logger.warn("No access time found");
}
if (current.getTime() - echartAccessTime < 30000) {
canView = true;
}
} else if (!reason.equals("")) {
// TODO: validate reason
canView = true;
session.getServletContext().setAttribute("echartAccessTime_" + demographicNo, current.getTime());
String ip = request.getRemoteAddr();
// Log the access request and the reason given for access
LogAction.addLog(user_no, "access", "eChart", demographicNo, ip, demographicNo, reason);
}
if (!canView) {
// Check if provider is part of circle of care
List<Long> programIds = new ArrayList<Long>();
List<ProgramQueue> programQueues = programQueueDao.getAdmittedProgramQueuesByDemographicId( demographicNoAsLong );
if (programQueues != null && programQueues.size() > 0) {
for (ProgramQueue pq : programQueues) {
programIds.add( pq.getProgramId() );
}
List<ProgramProvider> programProviders = programProviderDAO.getProgramProviderByProviderProgramId(user_no, programIds);
if (programProviders != null && programProviders.size() > 0) {
canView = true;
}
}
}
String useNewCaseMgmt;
if((useNewCaseMgmt = request.getParameter("newCaseManagement")) != null ) {
session.setAttribute("newCaseManagement", useNewCaseMgmt);
ArrayList<String> users = (ArrayList<String>)session.getServletContext().getAttribute("CaseMgmtUsers");
if( users != null ) {
users.add(request.getParameter("providerNo"));
session.getServletContext().setAttribute("CaseMgmtUsers", users);
}
}
else {
useNewCaseMgmt = (String)session.getAttribute("newCaseManagement");
}
String requestURI = httpRequest.getRequestURI();
String contextPath = httpRequest.getContextPath();
if (!canView && !requestURI.startsWith(contextPath + "/casemgmt/accessRequest.jsp")) {
httpResponse.sendRedirect(contextPath + "/casemgmt/accessRequest.jsp?" + httpRequest.getQueryString());
return;
}
logger.debug("AccessRequestFilter chainning");
chain.doFilter( new FilteredRequest(request), response);
}
}
The filter is setup to intercept all request and forwards coming into a subdirectory called casemgmt. The filter in web.xml is like:
<filter>
<filter-name>AccessRequestFilter</filter-name>
<filter-class>org.oscarehr.casemgmt.filter.AccessRequestFilter</filter-class>
</filter>
...
<filter-mapping>
<filter-name>AccessRequestFilter</filter-name>
<url-pattern>/casemgmt/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Anyone have any ideas how I can actually remove the 'reason' parameter?
Wrapping and manipulating the HttpServletRequest in the server side absolutely doesn't magically affect the URL as you see in browser's address bar. That URL stands as-is, as it's the one which the browser used to request the desired resource. The wrapped request would only affect the server side code which is running after the filter on the same request.
If you want to change the URL in browser's address bar, then you should be sending a redirect to exactly the desired URL.
Basically,
if (reasonParameterIsIn(queryString)) {
response.sendRedirect(requestURL + "?" + removeReasonParameterFrom(queryString));
return;
}

Categories