package ef.impl.command.upload;
import ef.api.*;
import ef.api.Error;
import ef.impl.command.AbstractCommand;
import ef.impl.response.MapResponse;
import org.apache.commons.fileupload.FileItem;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: sduchenko
* Date: 23.04.13
* Time: 17:20
*/
public class UploadCommand extends AbstractCommand<UploadRequest> {
public UploadCommand(VolumeManager volumeManager) {
super(volumeManager);
}
@Override
public UploadRequest buildRequest(SourceRequestReader requestReader) {
if(!requestReader.isUpload()){
throw new ErrException(Error.errUploadCommon);
}
Map<String, List<FileItem>> map = requestReader.getFileUpload();
UploadRequest request = new UploadRequest();
request.target = requestReader.getRequiredUploadString("target");
request.upload = map.get("upload[]");
if(request.upload == null || request.upload.isEmpty()){
throw new ErrException(Error.errUploadNoFiles);
}
return request;
}
@Override
public Response execute(UploadRequest request) {
Volume volume = volumeManager.getRequiredVolume(request.target);
Map<String, String> errorData = new HashMap<String, String>();
List<FileEntry> added = new ArrayList<FileEntry>();
for(FileItem file: request.upload){
InputStream is = null;
try {
is = file.getInputStream();
added.add(volume.upload(request.target, file.getName(), is));
} catch (Exception e) {
String error;
if(e instanceof ErrException){
error = ((ErrException) e).getError().getErrName();
}else{
error = Error.errUploadCommon.getErrName();
}
errorData.put(file.getName(), error);
} finally {
if(is != null){
try {
is.close();
} catch (IOException ignored) {}
}
}
}
MapResponse response = new MapResponse();
response.put("added", added);
if(!errorData.isEmpty()){
response.put("error", "Some files was not uploaded");
response.put("errorData", errorData);
}
return response;
}
}