Apache tomcat error-http status 404 - tomcat8

//code for my application:-
when i run my application and open the logout or profile page i.e. i click on logout or profile links then the error 404 resource not found occurs //index.html
<h1>Welcome to login pannel</h1>
Login
Logout
Profile
//link.html
Login |
Logout |
Profile
//login.html
<form action="loginservlet" method="post">
Name:<input type="text" name="name"/><br>
Password:<input type="password" name="pass"/><br>
<input type="submit" value="login"/>
</form>
//loginservlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/* Servlet implementation class loginservlet
*/
#WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("1234")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
Cookie ck=new Cookie("name",name);
res.addCookie(ck);
}else{
out.print("sorry, username or password error!");
req.getRequestDispatcher("login.html").include(req, res);
}
out.close();
}
}
//profileservlet.java//
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class profileservlet
*/
#WebServlet("/profileservlet")
public class profileservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public profileservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
Cookie ck[]=req.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
req.getRequestDispatcher("login.html").include(req, res);
}
out.close();
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
}
//logoutservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class logoutservlet
*/
#WebServlet("/logoutservlet")
public class logoutservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
res.setContentType("text/html");
PrintWriter out=res.getWriter();
req.getRequestDispatcher("link.html").include(req, res);
Cookie ck=new Cookie("name","");
ck.setMaxAge(0);
res.addCookie(ck);
out.print("you are successfully logged out!");
//res.getWriter().append("Served at: ").append(req.getContextPath());
}
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>log_in_out</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Related

How to add Security Headers in Vue App running on tomcat

I have a vue app that is deployed on server running a tomcat 9. HOw can I add Feature-Policy and Expect-CT headers to all the pages?
Filter class that add headers to response
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.HttpServletResponse;
public class MyCustomHeadersFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
HeaderResponseWrapper headerResponseWrapper = new HeaderResponseWrapper(httpResp);
headerResponseWrapper.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
headerResponseWrapper.setHeader("Pragma", "no-cache"); // HTTP 1.0.
headerResponseWrapper.setHeader("Expires", "0"); // Proxies.
chain.doFilter(request, headerResponseWrapper);
}
#Override
public void destroy() {
}
}
HeaderResponseWrapper class
import java.io.*;
import javax.servlet.http.*;
public class HeaderResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter writer;
public HeaderResponseWrapper(HttpServletResponse response) {
super(response);
writer = new CharArrayWriter();
}
public PrintWriter getWriter() {
return new PrintWriter(writer);
}
public String toString() {
return writer.toString();
}
}
Now add this class as filter in the web.xml of tomcat and map it to relevant URLs
<filter>
<filter-name>MyCustomHeadersFilter</filter-name>
<filter-class>com.headers.config.MyCustomHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyCustomHeadersFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

Spring Security Filter test, authentification not working in POSTMAN

I'm trying to check if attemptAuthentication is working but in postman but I'm getting 401 unauthorized.
My security Configure:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//http.formLogin();
http.authorizeRequests().antMatchers("/login","/login/**","/register/**").permitAll();
http.authorizeRequests().antMatchers(HttpMethod.POST,"/tasks/**").hasAuthority("ADMIN");
http.authorizeRequests().anyRequest().authenticated();
http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
http.addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
}
My attemptAuthentication:
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
AppUser appUser = null;
try {
appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("****************************");
System.out.println(appUser.getUsername());
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
}
My postman test:
My JWTAuthenticationFilter:
package security;
import java.io.IOException;
import java.util.Date;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.example.springJWT.entities.AppUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super();
// super.setFilterProcessesUrl("/login");
this.authenticationManager = authenticationManager;
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
AppUser appUser = null;
try {
appUser = new ObjectMapper().readValue(request.getInputStream(), AppUser.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("****************************");
System.out.println(appUser.getUsername());
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(appUser.getUsername(), appUser.getPassword()));
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
User springUser=(User) authResult.getPrincipal();
String jwt=Jwts.builder()
.setSubject(springUser.getUsername())
.setExpiration(new Date(System.currentTimeMillis()+SecurityConstants.EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS256, SecurityConstants.SECRET)
.claim("roles", springUser.getAuthorities())
.compact();
response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX+jwt);
super.successfulAuthentication(request, response, chain, authResult);
}
}
in your JWTAuthenticationFilter class in the attemptAuthentication method you are providing a UsernamePasswordAuthenticationToken to the auth manager
which has as principal a String instance and the in the successfulAuthentication method you are trying to cast this to an User
User springUser=(User) authResult.getPrincipal();
and this goes wrong if I try it but it depends on the AuthenticationProvider you are actually using

How to use camel type converter to convert exchange data into file object in apahce camel? [duplicate]

I am new to Camel and I am facing an issue while sending files to webservice via camel http.
I have a rest web service which consumes Multipart form data type content and accepts input as part of form data.
When I send file and form parameter via camel it gives me the following error at camel console:
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/JAX_RS_Application/resource/restwb/upload with statusCode: 415
at org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:230)
at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:156)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:435)
at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)
at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
The error i get on the server side console is as follows:
SEVERE: MessageBodyReader not found for media type=application/octet-stream, typ
e=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=clas
s org.glassfish.jersey.media.multipart.FormDataMultiPart.
The code snippet of the Rest web-service created via jersey is as follows:
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/restwb")
public class FileResource {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(#FormDataParam("username") String username,#FormDataParam("password") String password,#FormDataParam("upload") InputStream is) {
String output ="Hi "+username+" your password is "+password;
output=output+IOUtils.LINE_SEPARATOR +IOUtils.LINE_SEPARATOR;
output=output+"Output :"+IOUtils.LINE_SEPARATOR+"------------------------------------------------------------------------------"+IOUtils.LINE_SEPARATOR;
try {
output=output+IOUtils.toString(is)+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
output=output+"==================================================================================================="+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
System.out.println("Output :"+output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return output;
}
}
And my Camel config is as follows:
import org.apache.camel.*;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.spi.UnitOfWork;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.james.mime4j.message.Multipart;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
/**
* Created by Manish.Pillai on 7/16/2015.
*/
public class LoggingMain {
private static final Logger logger =Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception{
CamelContext camelContext =new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getContext().getTypeConverterRegistry().addTypeConverter(HttpEntity.class,InputStream.class,new InputStreamToHttpEntityConvertor());
exchange.getOut().setBody(exchange.getIn().getBody(),HttpEntity.class);
}
})
.to("http://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
static class InputStreamToHttpEntityConvertor implements TypeConverter {
public boolean allowNull() {
return false;
}
public <T> T convertTo(Class<T> type, Object value) throws TypeConversionException {
Exchange exchange=(Exchange)value;
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("upload", new FileBody(exchange.getIn().getBody(File.class), ContentType.MULTIPART_FORM_DATA, (String) exchange.getIn().getHeader(Exchange.FILE_NAME)));
multipartEntityBuilder.addPart("username",username);
multipartEntityBuilder.addPart("password",password);
return (T)multipartEntityBuilder.build();
}
public <T> T convertTo(Class<T> aClass, Exchange exchange, Object o) throws TypeConversionException {
return convertTo(aClass,o);
}
public <T> T mandatoryConvertTo(Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Object value) {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Exchange exchange, Object value) {
return convertTo(type,value);
}
}
}
Any leads would be helpful.
Well, there are several things that can be improved in your code.
First, since you are using a MultipartEntityBuilder, that means you're using Apache's HttpClient version 4.3+, so for best compatibility you should use Camel's HTTP4 component.
Third, in an example as small as this, you don't really need to use the converter, you can do something like this:
public class LoggingMain {
private static final Logger logger = Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception {
CamelContext camelContext = new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("username", username);
multipartEntityBuilder.addPart("password", password);
String filename = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
File file = exchange.getIn().getBody(File.class);
multipartEntityBuilder.addPart("upload", new FileBody(file, ContentType.MULTIPART_FORM_DATA, filename));
exchange.getIn().setBody(multipartEntityBuilder.build());
}
})
.to("http4://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
I hope this helps!

Unable to log in to Apache FTP Server

I am trying to integrate the Apache FTP server into my application. I have followed the instructions given here but have run into some problems. Currently I am able to run the server and connect to it from my browser but can not log in. I have tried admin/admin and anonymous/*, but the login fails every time. In the apache-ftpserver-1.0.6 source code I had downloaded, the files associated with the user manager are located in res/conf, although when I try to match that file path in my own program I get an error that says "invalid resource directory name" and am unable to build. I also tried including the files users.properties and ftpd-typical.xml in the main directly and can run, but again cannot log in. It seems like my project does not realize these files are present.
Does anyone have experience with Apache FTP Server that could tell me the correct way to include these files so that I can log in to my server?
Thanks!
P.S. I don't think it should make any difference, but I am developing this program for Android.
In the following code I am crating admin user and non-admin user, setting restrictions of reading, writing and restricting throttling and upload rate limit and imposing download rate limiting.
Added a listener to listen user login and logout download start and download finish events.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FileSystemFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.ftpletcontainer.impl.DefaultFtpletContainer;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.TransferRatePermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SFTPServer {
// ===========================================================
// Constants
// ===========================================================
private final int FTP_PORT = 2221;
private final String DEFAULT_LISTENER = "default";
// private final Logger LOG = LoggerFactory.getLogger(SFTPServer.class);
private static final List<Authority> ADMIN_AUTHORITIES;
private static final int BYTES_PER_KB = 1024;
private static final String DEFAULT_USER_DIR = "C:\\upload";
public final static int MAX_CONCURRENT_LOGINS = 1;
public final static int MAX_CONCURRENT_LOGINS_PER_IP = 1;
// ===========================================================
// Fields
// ===========================================================
private static FtpServer mFTPServer;
private static UserManager mUserManager;
private static FtpServerFactory mFTPServerFactory;
private ListenerFactory mListenerFactor;
// ===========================================================
// Constructors
// ===========================================================
static {
// Admin Authorities
ADMIN_AUTHORITIES = new ArrayList<Authority>();
ADMIN_AUTHORITIES.add(new WritePermission());
ADMIN_AUTHORITIES.add(new ConcurrentLoginPermission(MAX_CONCURRENT_LOGINS, MAX_CONCURRENT_LOGINS_PER_IP));
ADMIN_AUTHORITIES.add(new TransferRatePermission(Integer.MAX_VALUE, Integer.MAX_VALUE));
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void init() throws FtpException {
mFTPServerFactory = new FtpServerFactory();
mListenerFactor = new ListenerFactory();
mListenerFactor.setPort(FTP_PORT);
mFTPServerFactory.addListener(DEFAULT_LISTENER, mListenerFactor.createListener());
mFTPServerFactory.getFtplets().put(FTPLetImpl.class.getName(), new FTPLetImpl());
PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
userManagerFactory.setFile(new File("ftpusers.properties"));
userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
mUserManager = userManagerFactory.createUserManager();
mFTPServerFactory.setUserManager(mUserManager);
this.createAdminUser();
SFTPServer.addUser("admin1", "admin1", 20, 20);
mFTPServer = mFTPServerFactory.createServer();
mFTPServer.start();
}
private UserManager createAdminUser() throws FtpException {
UserManager userManager = mFTPServerFactory.getUserManager();
String adminName = userManager.getAdminName();
if (!userManager.doesExist(adminName)) {
// LOG.info((new
// StringBuilder()).append("Creating user : ").append(adminName).toString());
BaseUser adminUser = new BaseUser();
adminUser.setName(adminName);
adminUser.setPassword(adminName);
adminUser.setEnabled(true);
adminUser.setAuthorities(ADMIN_AUTHORITIES);
adminUser.setHomeDirectory(DEFAULT_USER_DIR);
adminUser.setMaxIdleTime(0);
userManager.save(adminUser);
}
return userManager;
}
public static void addUser(String username, String password, int uploadRateKB, int downloadRateKB) throws FtpException {
BaseUser user = new BaseUser();
user.setName(username);
user.setPassword(password);
user.setHomeDirectory(DEFAULT_USER_DIR);
user.setEnabled(true);
List<Authority> list = new ArrayList<Authority>();
list.add(new TransferRatePermission(downloadRateKB * BYTES_PER_KB, uploadRateKB * BYTES_PER_KB)); // 20KB
list.add(new ConcurrentLoginPermission(MAX_CONCURRENT_LOGINS, MAX_CONCURRENT_LOGINS_PER_IP));
user.setAuthorities(list);
mFTPServerFactory.getUserManager().save(user);
}
public static void restartFTP() throws FtpException {
if (mFTPServer != null) {
mFTPServer.stop();
try {
Thread.sleep(1000 * 3);
} catch (InterruptedException e) {
}
mFTPServer.start();
}
}
public static void stopFTP() throws FtpException {
if (mFTPServer != null) {
mFTPServer.stop();
}
}
public static void pauseFTP() throws FtpException {
if (mFTPServer != null) {
mFTPServer.suspend();
}
}
public static void resumeFTP() throws FtpException {
if (mFTPServer != null) {
mFTPServer.resume();
}
}
public static void main(String... are) {
try {
new SFTPServer().init();
} catch (FtpException e) {
e.printStackTrace();
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
FTPLET Listener
import java.io.IOException;
import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletResult;
public class FTPLetImpl extends DefaultFtplet {
#Override
public FtpletResult onLogin(FtpSession session, FtpRequest request) throws FtpException, IOException {
System.out.println(session.getUser().getName() + " Logged in");
return super.onLogin(session, request);
}
#Override
public FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException {
System.out.println(session.getUser().getName() + " Disconnected");
return super.onDisconnect(session);
}
#Override
public FtpletResult onDownloadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
System.out.println(session.getUser().getName() + " Started Downloading File " + request.getArgument());
return super.onDownloadStart(session, request);
}
#Override
public FtpletResult onDownloadEnd(FtpSession session, FtpRequest request) throws FtpException, IOException {
System.out.println("Finished Downloading " + request.getArgument());
return super.onDownloadEnd(session, request);
}
}

Dynamic add servlet in WebLogic 12c not work?

I have two servlets below and work well with Tomcat7/Indigo,
it will print ' is added' when I visit myhost/DynamicAddServlet/tobeadded.jsp.
But they do not work in WebLogic 12c, is this possible in WebLogic 12c?
AddServletServlet
package test.servlets;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name="AddServletServlet", urlPatterns={"/add.jsp"},
loadOnStartup=1)
public class AddServletServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8873939883201271898L;
#Override
public void init() throws ServletException {
super.init();
final ServletRegistration.Dynamic dn =
this.getServletContext().addServlet("TobeAddedServlet", TobeAddedServlet.class);
dn.setAsyncSupported(true);
dn.addMapping("/tobeadded.jsp");
System.out.println(" ... init ...");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}
TobeAddedServlet
package test.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TobeAddedServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -8873939883201271898L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(" is added");
}
}
the stacktrace in WebLogic 12c:
<Mar 2, 2012 5:56:09 PM CST> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "1330682169014" for task "2". Error is: "weblogic.application.ModuleException: [HTTP:101216]Servlet: "AddServletServlet" failed to preload on startup in Web application: "DynamicAddServlet".
java.lang.UnsupportedOperationException: [HTTP:101388]The ServletContext was passed to the ServletContextListener.contextInitialized method of a ServletContextListener that was neither declared in web.xml or web-fragment.xml, nor annotated with javax.servlet.annotation.WebListener.
at weblogic.servlet.internal.WebAppServletContext.checkNotifyDynamicContext(WebAppServletContext.java:3834)
at weblogic.servlet.internal.WebAppServletContext.addServlet(WebAppServletContext.java:3464)
at weblogic.servlet.internal.WebAppServletContext.addServlet(WebAppServletContext.java:3564)
at test.servlets.AddServletServlet.init(AddServletServlet.java:25)
at javax.servlet.GenericServlet.init(GenericServlet.java:240)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:299)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:250)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.StubSecurityHelper.initServletInstance(StubSecurityHelper.java:94)
at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:82)
at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:74)
at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:60)
at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:34)
at weblogic.servlet.internal.ServletStubImpl.initStubLifecycleHelper(ServletStubImpl.java:638)
at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:579)
at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1874)
at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1848)
at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1738)
at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2740)
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1704)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:781)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:70)
at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:212)
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:111)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:213)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:208)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:70)
at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:24)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:729)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:35)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:258)
at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:61)
at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:79)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:582)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:148)
at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:114)
at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:149)
at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:335)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:844)
at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1253)
at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:440)
at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:163)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:545)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)"
Thanks in advance,
Hippo
According to Servlet specification (point 4.4) You can execute method addServlet only from contextInitialized method of a ServletContextListener implementation or from the onStartup method of a ServletContainerInitializer implementation.
Servlet Specification