mail is not sending to respective user in java - html

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>

Related

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

getRequestDispatcher dispatching jsp but not 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

Android crashes while sending json object

I am trying to send json object through volley in android studio to a server (mvc spring project in eclipse + tomcat is listening) but the app crashes. I'm new to the volley library. Also, the json object is made up of the data gotten from user inputs in combo box and textviews.
Login Activity:
package com.example.mujtaba.quizzer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.StringRequest;
import com.example.mujtaba.quizzer.Activity.QuizMaking;
import com.example.mujtaba.quizzer.Activity.QuizTaking;
import org.w3c.dom.Text;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
private Button button;
private TextView username;
private TextView password;
private Spinner role;
private String url = "http://localhost:8080/users/signup";
private RequestQueue queue;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username=(TextView) findViewById(R.id.username);
password=(TextView) findViewById(R.id.password);
button=(Button) findViewById(R.id.button);
role = (Spinner) findViewById(R.id.role);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.role_spinner, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
role.setAdapter(adapter);
}
public void Quiz(View v) { //select a new activity on the basis of role
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
queue = new RequestQueue(cache, network);
// Start the queue
queue.start();
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String,String>();
MyData.put("Username", username.getText().toString() ); //Add the data you'd like to send to the server.
MyData.put("Password",password.getText().toString());
MyData.put("Role",role.getSelectedItem().toString());
MyData.put("Score","0");
return MyData;
}
};
queue.add(MyStringRequest);
}
}
Logcat error:
*3430-3440/com.android.dialer E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
at dalvik.system.CloseGuard.open(CloseGuard.java:184)
at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
at android.os.Binder.execTransact(Binder.java:446)*

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).

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.