Cant read multipart data from HttpServletRequest in Servlet 3.0 - servlets

I am sending form data to backend (java+struts) from a ajax post method.
$( "#profileModalForm" ).submit(function( event ) {
var formData = new FormData(this);
formData.append('image', $('input[type=file]')[0].files[0]);
formData.append('section', 'general');
formData.append('action', 'previewImg');
$.ajax({
cache: false,
url: 'SaveProfilePopupData.ws',
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (html) {
$('#notificationArea').html(html);
}
});
event.preventDefault();
});
Browser console shows these as sent parameters.
-----------------------------181712305727018
Content-Disposition: form-data; name="hiddenIdTxt"
1000
-----------------------------181712305727018
Content-Disposition: form-data; name="passwordTxt"
abcd
-----------------------------181712305727018
Content-Disposition: form-data; name="repeatPasswordTxt"
abcd
-----------------------------181712305727018
Content-Disposition: form-data; name="fileInput"; filename="myImage.jpg"
Content-Type: image/jpeg
Øÿà.........(Some unreadable data here)
But I cant read parameters and parts from my HttpServletRequest.
public ActionForward saveProfilePopupData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
TransactionResult result = TransactionResult.getInstance();
if (WSUtil.getCurrentUser(request) != null) {
try {
for (Part part : request.getParts()) {
//First Logger
WSLogger.info(part.getSize());
}
//Second Logger
WSLogger.info(request.getParameter("hiddenIdTxt").toString());
result.setResultMessage("Profile Updated!");
result.setResultType(TransactionResultType.SUCCESS);
} catch (Exception ex) {
WSLogger.error("UserController - saveProfilePopupData Exception", ex);
}
} else {
return mapping.findForward(SESEXPIRE);
}
request.setAttribute("RESULT", result);
return mapping.findForward(SUCCESS);
}
First logger shows an empty line and second logger gives and nullpointer exception. What am I doing wrong here?
Here are the dependencies for my application.
<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-core</artifactId>
<version>1.3.10</version>
<exclusions>
<exclusion>
<artifactId>antlr</artifactId>
<groupId>antlr</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-extras</artifactId>
<version>1.3.10</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-taglib</artifactId>
<version>1.3.10</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>net.sf.flexjson</groupId>
<artifactId>flexjson</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>

I came up with a different way to do this. I used apache commons fileupload.
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while(iterator.hasNext()){
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if(item.isFormField()){
if(item.getFieldName().equals("hiddenIdTxt")){
byte[] str = new byte[stream.available()];
stream.read(str);
id = Integer.parseInt(new String(str,"UTF8"));
}
if(item.getFieldName().equals("passwordTxt")){
byte[] str = new byte[stream.available()];
stream.read(str);
password1 = new String(str,"UTF8");
}
if(item.getFieldName().equals("repeatPasswordTxt")){
byte[] str = new byte[stream.available()];
stream.read(str);
password2 = new String(str,"UTF8");
}
}else{
byte[] str = new byte[stream.available()];
stream.read(str);
imageBase64String = Base64.encodeBase64String(str);
}
}

Related

How to document Form-based Authemtication implemented by spring security via spring-doc-openapi?

I'm implementing auth for my REST api and I have a problecm with docs. I wrote auth by spring-security form-based authentication. On success it gives me coockie to keep seesion authenticated. I have found no way to make spring-doc-openapi to find default spring-security controller for login/logout operations. The only way i found - make fakes of them like this:
#RestController
#RequestMapping(value = "/")
public class FakeSecurityController {
/**
* Implemented by Spring Security
*/
#Operation(summary = "Login with the given credentials.")
#ApiResponses(value = {
#ApiResponse(responseCode = "200",
description = "Login processing url",
content = #Content(schema = #Schema(implementation = AuthDTO.class)),
headers = #Header(name = "SESSION", description = "Cookie", required = true, schema = #Schema(implementation = String.class)))
})
#PostMapping(value = "/login", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<AuthDTO> login(#RequestParam("username") String username,
#RequestParam("password") String password) {
throw new IllegalStateException("Add Spring Security to handle authentication");
}
/**
* Implemented by Spring Security
*/
#Operation(summary = "Logout the current user.")
#ApiResponses(value = {
#ApiResponse(responseCode = "200", description = "Logout processing url")
})
#PostMapping(value = "/logout")
#SecurityRequirements
public void logout() {
throw new IllegalStateException("Add Spring Security to handle authentication");
}
}
What should i do to make spring-doc-openapi doceument these endpoints by itself?
If your project that uses spring-security, you should add the following dependency, in combination with the springdoc-openapi-ui dependency: This dependency helps ignoring #AuthenticationPrincipal and provide the spring-security /login endpoint out of the box:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>${springdoc.version}</version>
</dependency>

log4net:ERROR Could not create Appender [Console] of type [log4net.Appender.ColoredConsoleAppender]. Reported error

Hello friend I have the following problem when trying to use log4net in net core in my console application.
My code is this:
using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Teltonika.Codec;
namespace UdpListener
{
class Program
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
static void Main()
{
XmlConfigurator.Configure();
IPAddress ip;
if (!IPAddress.TryParse(ConfigurationManager.AppSettings["ipAddress"], out ip))
{
Log.Error("Ip is not valid.");
throw new ArgumentException("Ip is not valid.");
}
int port;
if (!int.TryParse(ConfigurationManager.AppSettings["port"], out port))
{
Log.Error("Port is not valid.");
throw new ArgumentException("Port is not valid.");
}
Task.Run(async () =>
{
try
{
using (var udpClient = new UdpClient(new IPEndPoint(ip, port)))
{
Log.Info("Listening...");
while (true)
{
//IPEndPoint object will allow us to read datagrams sent from any source.
var receivedResults = await udpClient.ReceiveAsync();
byte[] data = receivedResults.Buffer;
//tramaService.InsertTrama(new Entity.GpsPuntos()
//{
// Fecha = DateTime.Now,
// Trama = String.Join("", data.Select(x => x.ToString("X2")).ToArray())
//});
Log.Info(string.Format("Received connection from: {0}", receivedResults.RemoteEndPoint));
Log.Info(string.Format("{0} - received [{1}]", DateTime.Now, String.Join("", data.Select(x => x.ToString("X2")).ToArray())));
var reader = new ReverseBinaryReader(new MemoryStream(data));
// Decode data
var avlData = new DataDecoder(reader).DecodeUdpData();
// Create response
var bytes = new List<byte>();
const short packetLength = 2 /* Id */+ 1 /* Type */ + 1 /* Avl packet id */+ 1 /* num of accepted elems */;
bytes.AddRange(BitConverter.GetBytes(BytesSwapper.Swap(packetLength)));
bytes.AddRange(BitConverter.GetBytes(BytesSwapper.Swap(avlData.PacketId)));
bytes.Add(avlData.PacketType);
bytes.Add(avlData.AvlPacketId);
bytes.Add((byte)avlData.AvlData.DataCount);
var response = bytes.ToArray();
Log.Info(string.Format("{0} - response [{1}]", DateTime.Now, String.Join("", bytes.Select(x => x.ToString("X2")).ToArray())));
await udpClient.SendAsync(response, response.Length, receivedResults.RemoteEndPoint);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
});
Console.ReadLine();
}
}
}
this my mistake
log4net:ERROR Could not create Appender [Console] of type [log4net.Appender.ColoredConsoleAppender]. Reported error follows.
System.NotSupportedException: No data is available for encoding 850. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
at System.Text.Encoding.GetEncoding(Int32 codepage)
at log4net.Appender.ColoredConsoleAppender.ActivateOptions()
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [Console] not found.
My archive configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings>
<add key="ipAddress" value="172.17.160.1"/>
<add key="port" value="3316"/>
<!--<add key="log4net.Internal.Debug" value="true"/>-->
</appSettings>
<log4net>
<appender name="Console" type="log4net.Appender.ColoredConsoleAppender" Target="Console.Error">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger - %message%newline"/>
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="500KB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d %-5p %c %m%n"/>
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="Console"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
</configuration>
I want it to show me in the console application that it is working.
I had this same error myself today after upgrading from .NET Framework to .NET 5. I managed to get around it by adding the following line at the start of my progam:
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
For me this was solved by using the ManagedColoredConsoleAppender instead.
Using the ManagedColoredConsoleAppender is a better solution if you want to run the application also on other OS's besides Windows.
The ColoredConsoleAppender depends on the kernel32.dll, which ManagedColoredConsoleAppender does not.
See also https://issues.apache.org/jira/browse/LOG4NET-658.

Property 'pos:empCode' is not valid for this type or one of the secondary types! error setting custom object in cmis

When I am adding my custom object in map, it gives me error.
java.lang.IllegalArgumentException: Property 'pos:empCode' is not
valid for
this type or one of the secondary types! at org.apache.chemistry.opencmis.client.runtime.repository.ObjectFactoryImpl.conver
tProperties(ObjectFactoryImpl.java:426) at
org.apache.chemistry.opencmis.client.runtime.SessionImpl.createDocument(Session
Impl.java:1091) at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImp
l.java:77)
My code is:
Map<String, Object> metaData = new HashMap<String, Object>(0);
metaData.put(DocumentConstants.EMPCODE, empCode);
// metaData.put(DocumentConstants.TYPE, Constants.EMP_FILE_UPLOAD);
// metaData.put(DocumentConstants.SUBTYPE, Constants.ADD);
docService.uploadDocumentsForAlfresco(metaData, byteArray, fileName);
DocService:
public Boolean uploadDocumentsForAlfresco(Map<String, Object> metaData,
byte[] data, String name) {
Session session = connect();
String folderPath = null;
folderPath = cmisSite.concat(cmisPath).concat("documentlibrary/");
// String path =
"DATAFILES/".concat(metaData.get(DocumentConstants.EMPCODE).toString());
String path = "DATAFILES/".concat("6");
folderPath = folderPath.concat(path);
Folder folder = createFolder(session, folderPath);
// metaData.put(PropertyIds.OBJECT_TYPE_ID, "D:ebs:bulkUploadDoc");
metaData.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
// set the alfresco object factory
metaData.put(PropertyIds.NAME, name);
ByteArrayInputStream input = new ByteArrayInputStream(data);
ContentStream contentStream =
session.getObjectFactory().createContentStream(name, data.length,
"application/octet-stream", input);
try {
folder.createDocument(metaData, contentStream,
VersioningState.MAJOR);
return true;
} catch (Exception ex) {
//log.error("exception while uploading document",ex);
ex.printStackTrace();
return false;
}
}
added dependency in pom.xml
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.3</version>
</dependency>
<dependency>
<groupId>org.apache.chemistry.opencmis</groupId>
<artifactId>chemistry-opencmis-client-impl</artifactId>
<version>0.13.0</version>
</dependency>
pos:empCode is a property that is defined on one of your custom types or aspects. You are attempting to set the value of that property on the object, but you've told CMIS that the object type is cmis:document. The cmis:document type maps to cm:content, the out-of-the-box type which does not have your custom property.
Instead of using cmis:document as the object type ID, use the object type ID of the type from your custom model that defines the pos:empCode property.

I don't know what this exception is?

This is my Dispatcher codes
#RequestMapping(value="blogWrite", method=RequestMethod.POST)
public ModelAndView writeBlog(BlogText blogText, MultipartFile[] files, HttpSession session) {
System.out.println("writeBlog() 실행");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/Blog/BlogPersonal/blogPersonal");
MemberInfo memberInfo = (MemberInfo)session.getAttribute("session");
final String path = "C:/Users/Dongjoo/Downloads/fileUpload/"+memberInfo.getMemberId();
logger.info("path:{}",path);
blogService.addBlogText(modelAndView,blogText,files,path);
return modelAndView;
}
And this is my service layer codes
#Autowired
private BlogDAO blogDAO;
public MemberInfo getMemberLogin(MemberInfo memberInfo) {
MemberInfo takeMemberInfo = blogDAO.memberLogin(memberInfo);
return takeMemberInfo;
}
public ModelAndView addBlogText(ModelAndView modelAndView, BlogText blogText, MultipartFile[] files, final String path) {
System.out.println("addBlogText() 실행");
for(MultipartFile file : files){
File newFile = new File(path+"/"+file.getOriginalFilename());
try {
FileUtils.writeByteArrayToFile(newFile, file.getBytes());
System.out.println("파일 업로드 성공!");
modelAndView.addObject("message", "파일업로드 성공!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("파일 업로드 실패!");
modelAndView.addObject("message", "파일업로드 실패!");
}
}
return modelAndView;
}
And web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<display-name>CharacterEncodingFilter</display-name>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description></description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
And pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
And writeForm.jsp
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var day = 1;
$('#addBtn').click(function() {
var tagAdd = '';
console.log('일차 : '+day);
if(day==1) {
tagAdd += '<div class="dayAndTimeDiv">';
tagAdd += '<input type="hidden" class="dayRequired" name="dayRequired" value="'+day+'"/>';
tagAdd += '<span class="dayRequiredShow">'+day+'일차</span>';
tagAdd += '<input type="text" class="timeRequired" name="timeRequired" size="2"/>';
tagAdd += '<span class="timeRequiredDiv"> 시간</span>';
tagAdd += '</div>';
tagAdd += '<div class="imageArea">';
tagAdd += '<input type="file" id="blogTextImage" name="blogTextImage"/><br/>';
tagAdd += '<textarea rows="20" cols="50" id="blogTextContent" name="blogTextContent"></textarea>';
tagAdd += '</div>';
$('#writeArea').append(tagAdd);
console.log(tagAdd);
}
else {
/* 지금 태그 추가/삭제가 안 된다. 일단 이것은 나중으로 미루고... */
$('#addBtnDiv').remove();
tagAdd = '<input type="button" id="addBtn"/>';
$('#addBtnDiv').append(tagAdd);
tagAdd = '';
tagAdd += '<div class="dayAndTimeDiv">';
tagAdd += '<input type="hidden" class="dayRequired" name="dayRequired" value="'+day+'"/>';
tagAdd += '<span class="dayRequiredShow">'+day+'일차</span>';
tagAdd += '<input type="text" class="timeRequired" name="timeRequired" size="2"/>';
tagAdd += '<span class="timeRequiredDiv"> 시간</span>';
tagAdd += '</div>';
tagAdd += '<div class="imageArea">';
tagAdd += '<input type="file" id="blogTextImage" name="blogTextImage" multiple="multiple"/><br/>';
tagAdd += '<textarea rows="20" cols="50" id="blogTextContent" name="blogTextContent"></textarea>';
tagAdd += '</div>';
$('#writeArea').append(tagAdd);
console.log(tagAdd);
}
day++;
});
$('#insertBlogTextBtn').click(function() {
$('form').submit();
});
});
</script>
</head>
<body>
<div id="memberNameDiv">
<span id="memberName">${session.memberName}</span>
</div>
<div>
<hr>
</div>
<div id="blogTextArea">
<form action="/blogWrite" method="post" enctype="multipart/form-data">
<div id="categoryDiv">
<span id="categoryHover">카테고리</span>
</div>
<div id="addBtnDiv">
<input type="button" id="addBtn"/>
</div>
<br/>
<div id="writeArea">
</div>
</form>
</div>
<div id="buttonArea">
<input type="button" id="insertBlogTextBtn" name="insertBlogTextBtn" value="글등록"/>
<input type="reset" id="cancelBtn" name="cancelBtn" value="취소"/>
</div>
I didn't make DAO part yet for putting data in database
I want to put some files.
But i've got Exception(error)
below :
Servlet.service() for servlet [appServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lorg.springframework.web.multipart.MultipartFile;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lorg.springframework.web.multipart.MultipartFile;.<init>()] with root cause
java.lang.NoSuchMethodException: [Lorg.springframework.web.multipart.MultipartFile;.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:103)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/wpad.dat] in DispatcherServlet with name 'appServlet'
please help me!!!(please Ignore Korean language what i wrote)
Declare CommonsMultipartResolver bean in serlvet configuration.
eg.
For XML config:
--------------
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>2097152</value> <!-- 2MB -->
</property>
</bean>
For java config:
---------------
#Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
In Controller annotation use like :
#RequestParam("photo") MultipartFile file

UnsupportedOperationException in NativeSshFile.setAttributes when uploading files Apache Mina sshd Server

I start up a local SFTP server using Apache Mina SSHD. Here is my related code. To testing I use WinSCP as my SFTP client. I can connect to the server successfully and can view server root directory also. But the problem was that when I try to upload a file into that server root directory.
I got a
Exception caught in SFTP subsystem
java.lang.UnsupportedOperationException: null
at org.apache.sshd.common.file.nativefs.NativeSshFile.setAttributes(NativeSshFile.java:634) ~[sshd-core-0.10.0.jar:0.10.0]
at org.apache.sshd.server.sftp.SftpSubsystem.process(SftpSubsystem.java:427) ~[sshd-core-0.10.0.jar:0.10.0]
at org.apache.sshd.server.sftp.SftpSubsystem.run(SftpSubsystem.java:334) ~[sshd-core-0.10.0.jar:0.10.0]
at java.lang.Thread.run(Unknown Source) [na:1.7.0_75].
Below is my related log files.
10:30:46.758 [Thread-1] DEBUG o.a.s.c.file.nativefs.NativeSshFile - Authorized
10:30:46.767 [Thread-1] ERROR o.a.sshd.server.sftp.SftpSubsystem - Exception caught in SFTP subsystem
java.lang.UnsupportedOperationException: null
at org.apache.sshd.common.file.nativefs.NativeSshFile.setAttributes(NativeSshFile.java:634) ~[sshd-core-0.10.0.jar:0.10.0]
at org.apache.sshd.server.sftp.SftpSubsystem.process(SftpSubsystem.java:427) ~[sshd-core-0.10.0.jar:0.10.0]
at org.apache.sshd.server.sftp.SftpSubsystem.run(SftpSubsystem.java:334) ~[sshd-core-0.10.0.jar:0.10.0]
at java.lang.Thread.run(Unknown Source) [na:1.7.0_75]
10:30:46.767 [Thread-1] DEBUG o.a.s.server.channel.ChannelSession - Send SSH_MSG_CHANNEL_EOF on channel ChannelSession[id=0, recipient=256]
10:30:46.768 [Thread-1] DEBUG o.a.sshd.common.io.nio2.Nio2Session - Writing 64 bytes
Also my maven dependency,
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-sftp</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>0.10.0</version>
</dependency>
I would like to know that how can I overcome above problem when uploading files into my local SFTP server. Thanks.
When uploading files, WinSCP, depending on its configuration, sets uploaded file timestamp (on by default) and/or permissions (off by default).
The Mina SSHD 0.10.0 does not support setting file attributes.
public void setAttributes(Map<Attribute, Object> attributes) throws IOException {
if (!attributes.isEmpty()) {
throw new UnsupportedOperationException();
}
}
The latest Mina SSHD 0.14.0 does support setting the timestamp and by default only logs that it cannot set the permissions (or other attributes).
public void setAttributes(Map<Attribute, Object> attributes) throws IOException {
Set<Attribute> unsupported = new HashSet<Attribute>();
for (Attribute attribute : attributes.keySet()) {
Object value = attributes.get(attribute);
switch (attribute) {
case Size: {
long newSize = (Long) value;
FileChannel outChan = new FileOutputStream(file, true).getChannel();
outChan.truncate(newSize);
outChan.close();
continue;
}
case LastModifiedTime:
setLastModified((Long) value);
break;
default:
unsupported.add(attribute);
break;
}
}
handleUnsupportedAttributes(unsupported);
}
protected void handleUnsupportedAttributes(Collection<Attribute> attributes) {
if (!attributes.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (Attribute attr : attributes) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(attr.name());
}
switch (nativeFileSystemView.getUnsupportedAttributePolicy()) {
case Ignore:
break;
case Warn:
LOG.warn("Unsupported attributes: " + sb.toString());
break;
case ThrowException:
throw new UnsupportedOperationException("Unsupported attributes: " + sb.toString());
}
}
}

Resources