getRequestDispatcher dispatching jsp but not html - html

I am running google app engine and using JAVAEE.
I have a two filters but only one is configured with restrictions.
WEB.XML
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<filter>
<filter-name>connexionFilter</filter-name>
<filter-class>AHSFilters.connexionFilter</filter-class>
</filter>
<filter>
<filter-name>restrictFilter</filter-name>
<filter-class>AHSFilters.restrictFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>connexionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>restrictFilter</filter-name>
<url-pattern>/client</url-pattern>
<url-pattern>/admin</url-pattern>
</filter-mapping>
</web-app>
I first login so I can go trough the first filter.
I change my url to localhost:8080/client
my connexion filter is as so:
package AHSFilters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class connexionFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
if(session.getAttribute("sessionUser") != null)
chain.doFilter(req, resp);
if (req.getHeader("X-Requested-With") != null)
chain.doFilter(req, resp);
else
req.getServletContext().getRequestDispatcher("/").forward(request, response);
// TODO Auto-generated method stub
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
my servlet is as so:
package AHSServlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet(
name = "ClientServ",
urlPatterns = {"/client"}
)
public class ClientServ extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.getWriter().flush();
this.getServletContext().getRequestDispatcher("/restrict/client/test.jsp").forward(request, response);;
}
}
when my file is setted to test.jsp I go to the correct page, but when I rename it to test.html and of course change the path in getRequestDispatcher I get redirected to my login page (/ route).
So I have to files /restrict/client/test.jsp i get the correct response
and /restrict/client/test.html I go back to the signin page.
I've tried putting a simple hello in test.html also tried with valid html page with the same result. Is there any settings I'm missing in order to allow html?
Where could it come from? Any help is greatly appreciated.

I think in order to do so you need little configuration. In web.xml write a configuration code
<jsp-config>
<jsp-property-group>
<url-pattern>*.html</url-pattern>
</jsp-property-group>
</jsp-config>
To understand better you can check
Can you render a file without a .jsp extension as a JSP?
Running .jsp as .html file

Related

mail is not sending to respective user in java

I am trying to send mail to respective user who upload file. I have one process.jsp page, in that user will enter mail id and when user click on send then mail will be sent as file is uploaded. I have written code for sending mail but it's giving error like There were an error: null. File is uploading into MySQL database successfully but mail is not sending.
This is my process.jsp page
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<input type="email" name="mailid" value="" required="" size="60" placeholder="Please enter your mail address" />
<input type="submit" value="Send" />
<table>
<tr style="display:none">
<td>Subject </td>
<td><input type="text" name="subject" size="50" /></td>
</tr>
<tr style="display:none">
<td>Content </td>
<td><textarea rows="10" cols="39" name="content"></textarea> </td>
</tr>
</table>
</form>
Note:- I want only two fields i.e. one Textfield for mail id and another one for send button. I don't want Subject and Content fields
This is my EmailUtility.java page
package com.codejava.email;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailUtility {
/**
* Sends an e-mail message from a SMTP host with a list of attached files.
*
*/
public static void sendEmailWithAttachment(String host, String port,
final String userName, final String password, String toAddress
)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = {
new InternetAddress(toAddress)
};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
// msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
}
This is my SendMailAttachServlet.java file
package com.codejava.email;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/SendMailAttachServlet")
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("recipient");
// String subject = request.getParameter("subject");
// String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
}
<form action="SendMailAttachServlet" method="post" enctype="multipart/form-data">
<input type="email" name="mailid" value="" required="" size="60" placeholder="Please enter your mail address" />
<input type="submit" value="Send" />
</form>
Now servlet code:
package com.codejava.email;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/SendMailAttachServlet")
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class SendMailAttachServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
/**
* handles form submission
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// List<File> uploadedFiles = saveUploadedFiles(request);
String recipient = request.getParameter("mailid");//here you have to give the same name as your HTML name filed or input filed have
String resultMessage = "";
try {
EmailUtility.sendEmailWithAttachment(host, port, user, pass,
recipient);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
//deleteUploadFiles(uploadedFiles);
request.setAttribute("message", resultMessage);
getServletContext().getRequestDispatcher("/result.jsp").forward(
request, response);
}
}
/**
* Saves files uploaded from the client and return a list of these files
* which will be attached to the e-mail message.
*/
}
This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>EmailAttachWebApp</display-name>
<!-- SMTP settings -->
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>465</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>dhanbashital#gmail.com</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>password</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Building a web application with embedded-jetty and jersey .. with request dispatching

I am setting a web application with embedded jetty and jersey .As i am fairly new with concepts, it is difficult to load a sample webpage index.html. When i target it as localhost:8989/myServlet i see the code flow through my servlet . But request dispatcher always returns null.
Please let me know with this:
Main class:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class MainApp {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8989);
jettyServer.setHandler(context);
ServletHandler handler =new ServletHandler();
handler.addServletWithMapping(MyServletHandler.class,"/myServlet");
jettyServer.setHandler(handler);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
Entry.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
Myservlet class:
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServletHandler extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Control is in servlet");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.html"); // this returns null. hence i am unable to request dispatch to view the html webpage.
}
}
I use Maven to build the application and i have placed index.html in src/main/resources directory
This works, but you'll have to properly setup the ServletContext so that the request.getRequestDispatcher() can do something.
For starters, your ServletContextHandler MUST have a Resource Base setup.
You'll have to setup a DefaultServlet so that the request dispatcher can be returned properly.
You'll also have to use embedded-jetty properly, don't use ServletHandler directly like that. Use the ServletHolder if you must, but otherwise just use the ServletContextHandler directly.
Here's an example of this behavior.
Run with a System Property of baseResource pointing to a directory where you have a index.html.
package jetty.dispatching;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;
import static java.nio.charset.StandardCharsets.UTF_8;
public class DispatchingToDefaultServletDemo
{
public static void main(String[] args) throws Exception
{
DispatchingToDefaultServletDemo demo = new DispatchingToDefaultServletDemo();
try
{
demo.startServer();
demo.makeRequests();
}
finally
{
demo.stopServer();
}
}
private Server server;
public void startServer() throws Exception
{
server = new Server(8989);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
// Must have Resource Base for proper ServletContext (even if it points to an empty URI directory in a JAR file)
context.setBaseResource(getBaseResource());
// Don't use ServletHandler directly!
context.addServlet(MyServletHandler.class, "/myServlet");
// Add DefaultServlet last on ServletContextHandler to be able to serve content from resource base.
// It must be named "default" (per servlet spec)
ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
defaultHolder.setInitParameter("dirAllowed", "true");
context.addServlet(defaultHolder, "/"); // this is the default url-pattern
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler()); // always last in handler tree
server.setHandler(handlers);
server.start();
}
public Resource getBaseResource() throws IOException
{
String baseResourceLocation = System.getProperty("baseResource");
if (baseResourceLocation == null)
{
baseResourceLocation = System.getProperty("user.dir");
}
Resource resource = Resource.newResource(baseResourceLocation);
System.out.println("Base Resource is " + resource);
return resource;
}
private void stopServer() throws Exception
{
server.stop(); // use .stop() NOT .destroy()
}
private void makeRequests()
{
performGET("/myServlet");
performGET("/");
}
private void performGET(String requestPath)
{
try
{
URI uri = server.getURI().resolve(requestPath);
System.out.println("Requesting GET on " + uri);
HttpURLConnection http = (HttpURLConnection) uri.toURL().openConnection();
System.out.println(" Response Status code = " + http.getResponseCode());
try (InputStream in = http.getInputStream())
{
System.out.println(" Response Body: " + IO.toString(in, UTF_8));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static class MyServletHandler extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.html");
System.out.println("request Dispatcher = " + requestDispatcher);
requestDispatcher.forward(request, response);
}
}
}
The output ...
$ java -DbaseResource=/home/joakim/code/jetty/bases/listing-base/rez/welcomish/ -classpath <..snip..> jetty.dispatching.DispatchingToDefaultServletDemo
2019-04-18 15:15:15.595:INFO::main: Logging initialized #180ms to org.eclipse.jetty.util.log.StdErrLog
Base Resource is file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/
2019-04-18 15:15:15.678:INFO:oejs.Server:main: jetty-9.4.15.v20190215; built: 2019-02-15T16:53:49.381Z; git: eb70b240169fcf1abbd86af36482d1c49826fa0b; jvm 1.8.0_192-b12
2019-04-18 15:15:15.725:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2019-04-18 15:15:15.726:INFO:oejs.session:main: No SessionScavenger set, using defaults
2019-04-18 15:15:15.727:INFO:oejs.session:main: node0 Scavenging every 660000ms
2019-04-18 15:15:15.736:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,AVAILABLE}
2019-04-18 15:15:15.747:INFO:oejs.AbstractConnector:main: Started ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.747:INFO:oejs.Server:main: Started #333ms
Requesting GET on http://127.0.1.1:8989/myServlet
request Dispatcher = Dispatcher#0x5d8c6ff2{null,/index.html}
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
Requesting GET on http://127.0.1.1:8989/
Response Status code = 200
Response Body: <h1>My welcomish HTML</h1>
2019-04-18 15:15:15.827:INFO:oejs.AbstractConnector:main: Stopped ServerConnector#3ffc5af1{HTTP/1.1,[http/1.1]}{0.0.0.0:8989}
2019-04-18 15:15:15.827:INFO:oejs.session:main: node0 Stopped scavenging
2019-04-18 15:15:15.829:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler#482f8f11{/,file:///home/joakim/code/jetty/bases/listing-base/rez/welcomish/,UNAVAILABLE}
Process finished with exit code 0

Camel endpoint mocking nullpointer exception

Iam trying to mock switchyard endpoint switchyard://TohpGetAccountReports using the mock endpoint in camel. the mockAccountReportEndpoint defined in junit test is returning null and the test id failing with nullpointer exception.can you please tell me what is wrong with my code?
Camel route :
<route id="accountReportRoute" streamCache="true">
<from uri="direct:accountReport" />
<doTry>
<setProperty propertyName="hpResponse">
<constant>A</constant>
</setProperty>
<to
uri="xslt:xslt/account_reports_manager/create_get_accountreport_request.xslt" />
<log message="GetAccountReports Request : ${body}" logName="esb.hp.InModelProvider.AccountReport"
loggingLevel="TRACE" />
<to
id="AccountReportEndpoint" uri="switchyard://TohpGetAccountReports?operationName=GetAccountReports" />
<log message="GetAccountReports Response : ${body}" logName="esb.hp.InModelProvider.AccountReport"
loggingLevel="TRACE" />
<to
uri="xslt:xslt/account_reports_manager/create_get_accountreport_response.xslt" />
<doCatch>
<exception>java.lang.Exception</exception>
<handled>
<constant>false</constant>
</handled>
<log
message="Exception in hp Model provider accountReportRoute ${exception.stacktrace} "
logName="esb.hp.InModelProvider.AccountReport" loggingLevel="ERROR" />
</doCatch>
</doTry>
<log message="Workaround for handling account report soap fault"
logName="esb.hp.InModelProvider.AccountReport" loggingLevel="DEBUG" />
</route>
junit test class
package com.company.esb.hp.in.modelprovider.test;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.model.ModelCamelContext;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.ServiceDomain;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;
import org.switchyard.component.test.mixins.http.HTTPMixIn;
import org.switchyard.test.BeforeDeploy;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.transform.config.model.TransfohpwitchYardScanner;
import com.company.esb.common.test.esbSwitchyardTest;
import com.company.esb.hp.in.modelprovider.test.util.RiskInProviderUtil;
#SwitchYardTestCaseConfig(config = SwitchYardTestCaseConfig.SWITCHYARD_XML, mixins = {
CDIMixIn.class, HTTPMixIn.class }, scanners = { TransfohpwitchYardScanner.class })
#RunWith(SwitchYardRunner.class)
public class hpInModelProviderTest extends esbSwitchyardTest {
private static final Logger LOG = Logger
.getLogger(hpInModelProviderTest.class);
private SwitchYardTestKit testKit;
public static final String getAcctResult = "TohpGetAccountReports";
#EndpointInject(uri = "mock://switchyard:TohpGetAccountReports*")
protected MockEndpoint mockAccountReportEndpoint;
#BeforeDeploy
public void setProperties() {
System.setProperty("esb.hp.inmodelprovider.url", "http://pusslasrws1451.company.biz");
}
#Before
public void installServices() {
simulateesbServices(testKit);
}
#Test
public void testAccountReportDirectRouteSuccess() throws Exception {
String request = readFile("xml/endtoend/success/GetJobsResults/get_job_status-response.xml");
ServiceDomain domain = testKit.getServiceDomain();
//testKit.removeService(getAcctResult);
//testKit.registerInOutService(getAcctResult,
// new GetAccountReportsServiceMockExchangeHandler());
CamelContext ctx = (CamelContext) domain
.getProperty("CamelContextProperty");
Exchange ex = new DefaultExchange(ctx);
ModelCamelContext modelContext = (ModelCamelContext) ctx;
modelContext.getRouteDefinition("accountReportRoute").adviceWith(modelContext, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveById("AccountReportEndpoint").replace().to(mockAccountReportEndpoint);
}
});
mockAccountReportEndpoint.expectedMessageCount(1);
mockAccountReportEndpoint.returnReplyBody(new Expression() {
#Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
return exchange.getContext().getTypeConverter().convertTo(type, RiskInProviderUtil.readFile("xml/endtoend/success/GetJobsResults/get_account_report_service-response.xml"));
}
});
// MockEndpoint endpoint = getMockEndpoint("mock:switchyard:service");
ex.setProperty("sToken", "f3669d3a-5a2b-4b99-a8df-3aabfd4aae58");
ex.setProperty("sAccId", "196497");
ex.getIn().setBody(request);
ProducerTemplate producer = ctx.createProducerTemplate();
producer.send("direct:accountReport", ex);
System.out.println(ex.getIn().getBody(String.class));
}
#Override
protected void addSetupProperties(Map<String, String> map) {
}
}
..after you have done the adviceWith you must start CamelContext by invoke the start method on the context instance.
http://camel.apache.org/advicewith.html#AdviceWith-UsingisUseAdviceWith()
Try to override the isUseAdviceWith() method (should return true) and start the context after you have done the adviceWith. If it has been already started then try to stop() it and start() it again (cold restart).

App crashes everytime run with error "Unfortunately MyApplication1 has stopped"

I am using Volley library for fetching the json data. I have also modified the Manifest adding the necessary Internet permission . But when I run the app it crashes.
Main activity.java
package com.example.sans.myapplication1;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
listView=(ListView)findViewById(R.id.list);
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, "http://api.themoviedb.org/3/movie/popular?api_key=fa468af9e769ba5fbc027e9e933130ed",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Movie> movieList= new ArrayList<Movie>();
try{
JSONArray jsonArray=response.getJSONArray("results");
for (int i=0;i< jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String title= jsonObject.getString("title");
movieList.add(new Movie(title));
MovieAdapter adapter= new MovieAdapter(getApplicationContext(),movieList);
listView.setAdapter(adapter);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error getting data", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
$ MovieAdapter.java
package com.example.sans.myapplication1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by sans on 13/7/16.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
public MovieAdapter(Context context, List<Movie> objects) {
super(context,0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie=getItem(position);
if(convertView==null){
convertView= LayoutInflater.from(getContext()).inflate(R.layout.list_row, parent);
}
TextView title=(TextView)convertView.findViewById(R.id.title);
title.setText(movie.getTitle());
return convertView;
}
}
$ Movie.java
package com.example.sans.myapplication1;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by sans on 13/7/16.
*/
public class Movie {
private String title;
public Movie(String title){
this.title=title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
$ list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/listPreferredItemHeight"
android:id="#+id/title"/>
</LinearLayout>
$ content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sans.myapplication1.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</RelativeLayout>
Log error
FATAL EXCEPTION: main
Process: com.example.sans.myapplication1, PID: 4252
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.sans.myapplication1.MovieAdapter.getView(MovieAdapter.java:29)
at android.widget.AbsListView.obtainView(AbsListView.java:2346)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1280)
at android.widget.ListView.onMeasure(ListView.java:1188)
at android.view.View.measure(View.java:18788)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18788)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-13 17:37:39.746 1532-1903/? W/ActivityManager: Force finishing activity com.example.sans.myapplication1/.MainActivity
In MovieAdapter.java class change convertView!=null to convertView==null
& in list_row.xml file
instead of android:minHeight="?attr/listPreferredItemHeight"
change it to android:minHeight="?android:attr/listPreferredItemHeight"

unable to upload file to mysql using struts1

I am trying to upload a file into mysql database using struts1.But unable to doso,I am getting the error:FileNotFoundException.Here is my code...
1.JSP Page:
<%# taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<body>
<html:form action="upload" enctype="multipart/form-data">
Select a File :<html:file property="file"/>
<html:submit/>
</html:form>
</body>
</html:html>
2.My Action Form
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm{
private FormFile file;
public FormFile getFile(){
return this.file;
}
public void setFile(FormFile file){
this.file=file;
}
}
3.Action Class
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
UploadForm file=(UploadForm)form;
System.out.print("Executed");
FormFile formFile=file.getFile();
System.out.print("Executed1");
String fileName=formFile.getFileName();
System.out.print(fileName);
File file1=new File(formFile.getFileName());
System.out.print(">>>>");
FileInputStream fin=new FileInputStream(file1);
System.out.print("*****");
Integer fileSize=formFile.getFileSize();
int insert=0;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
System.out.println("Connection Opened.");
PreparedStatement pst=con.prepareStatement("insert into upload values(?)");
pst.setBinaryStream(1,fin,fileSize);
insert=pst.executeUpdate();
System.out.print("File Uploaded.");
}
catch(Exception e){System.out.println(e);}
if(insert!=0){
return mapping.findForward("success");
}
else{
return mapping.findForward("error");
}
}
}
I am getting error at this line in my Action Class:FileInputStream fin=new FileInputStream(file1);
Please help me to resolve this problem.