use of org.apache.commons.fileupload.FileItem in project wicket by apache.
the class MultipartServletWebRequestImpl method readServlet3Parts.
/**
* Reads the uploads' parts by using Servlet 3.0 APIs.
*
* <strong>Note</strong>: By using Servlet 3.0 APIs the application won't be able to use
* upload progress updates.
*
* @param request
* The http request with the upload data
* @return A list of {@link FileItem}s
* @throws FileUploadException
*/
private List<FileItem> readServlet3Parts(HttpServletRequest request) throws FileUploadException {
List<FileItem> itemsFromParts = new ArrayList<>();
try {
Collection<Part> parts = request.getParts();
if (parts != null) {
for (Part part : parts) {
FileItem fileItem = new ServletPartFileItem(part);
itemsFromParts.add(fileItem);
}
}
} catch (IOException | ServletException e) {
throw new FileUploadException("An error occurred while reading the upload parts", e);
}
return itemsFromParts;
}
use of org.apache.commons.fileupload.FileItem in project ff4j by ff4j.
the class ConsoleServlet method doPost.
/**
* {@inheritDoc}
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String message = null;
String messagetype = "info";
try {
if (ServletFileUpload.isMultipartContent(req)) {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
if (OPERATION.equalsIgnoreCase(item.getFieldName())) {
LOGGER.info("Processing action : " + item.getString());
}
} else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) {
String filename = FilenameUtils.getName(item.getName());
if (filename.toLowerCase().endsWith("xml")) {
importFile(getFf4j(), item.getInputStream());
message = "The file <b>" + filename + "</b> has been successfully imported";
} else {
messagetype = ERROR;
message = "Invalid FILE, must be CSV, XML or PROPERTIES files";
}
}
}
} else {
String operation = req.getParameter(OPERATION);
String uid = req.getParameter(FEATID);
LOGGER.info("POST - op=" + operation + " feat=" + uid);
if (operation != null && !operation.isEmpty()) {
if (OP_EDIT_FEATURE.equalsIgnoreCase(operation)) {
updateFeatureDescription(getFf4j(), req);
message = msg(uid, "UPDATED");
} else if (OP_EDIT_PROPERTY.equalsIgnoreCase(operation)) {
updateProperty(getFf4j(), req);
message = renderMsgProperty(uid, "UPDATED");
} else if (OP_CREATE_PROPERTY.equalsIgnoreCase(operation)) {
createProperty(getFf4j(), req);
message = renderMsgProperty(req.getParameter(NAME), "ADDED");
} else if (OP_CREATE_FEATURE.equalsIgnoreCase(operation)) {
createFeature(getFf4j(), req);
message = msg(uid, "ADDED");
} else if (OP_TOGGLE_GROUP.equalsIgnoreCase(operation)) {
String groupName = req.getParameter(GROUPNAME);
if (groupName != null && !groupName.isEmpty()) {
String operationGroup = req.getParameter(SUBOPERATION);
if (OP_ENABLE.equalsIgnoreCase(operationGroup)) {
getFf4j().getFeatureStore().enableGroup(groupName);
message = renderMsgGroup(groupName, "ENABLED");
LOGGER.info("Group '" + groupName + "' has been ENABLED.");
} else if (OP_DISABLE.equalsIgnoreCase(operationGroup)) {
getFf4j().getFeatureStore().disableGroup(groupName);
message = renderMsgGroup(groupName, "DISABLED");
LOGGER.info("Group '" + groupName + "' has been DISABLED.");
}
}
} else {
LOGGER.error("Invalid POST OPERATION" + operation);
messagetype = ERROR;
message = "Invalid REQUEST";
}
} else {
LOGGER.error("No ID provided" + operation);
messagetype = ERROR;
message = "Invalid UID";
}
}
} catch (Exception e) {
messagetype = ERROR;
message = e.getMessage();
LOGGER.error("An error occured ", e);
}
// Update FF4J in Session (distributed)
getServletContext().setAttribute(FF4J_SESSIONATTRIBUTE_NAME, ff4j);
renderPage(ff4j, req, res, message, messagetype);
}
use of org.apache.commons.fileupload.FileItem in project ff4j by ff4j.
the class HomeController method post.
/**
* {@inheritDoc}
*/
public void post(HttpServletRequest req, HttpServletResponse res, WebContext ctx) throws Exception {
String msg = null;
String msgType = "success";
String operation = req.getParameter(WebConstants.OPERATION);
// Upload XML File
if (ServletFileUpload.isMultipartContent(req)) {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
if (OPERATION.equalsIgnoreCase(item.getFieldName())) {
LOGGER.info("Processing action : " + item.getString());
}
} else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) {
String filename = FilenameUtils.getName(item.getName());
if (filename.toLowerCase().endsWith("xml")) {
try {
importFile(getFf4j(), item.getInputStream());
msg = "The file <b>" + filename + "</b> has been successfully imported";
} catch (RuntimeException re) {
msgType = ERROR;
msg = "Cannot Import XML:" + re.getMessage();
break;
}
} else {
msgType = ERROR;
msg = "Invalid FILE, must be CSV, XML or PROPERTIES files";
}
}
}
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
} else if (WebConstants.OP_CREATE_SCHEMA.equalsIgnoreCase(operation)) {
try {
getFf4j().createSchema();
msg = "Schema has been created in DB (if required).";
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
} catch (RuntimeException re) {
ctx.setVariable("msgType", ERROR);
ctx.setVariable("msgInfo", "Cannot create Schema:" + re.getMessage());
ctx.setVariable(KEY_TITLE, "Home");
ctx.setVariable("today", Calendar.getInstance());
ctx.setVariable("homebean", new HomeBean());
}
} else if (WebConstants.OP_CLEAR_CACHE.equalsIgnoreCase(operation)) {
FF4jCacheProxy cacheProxy = getFf4j().getCacheProxy();
if (cacheProxy != null) {
cacheProxy.getCacheManager().clearFeatures();
cacheProxy.getCacheManager().clearProperties();
msg = "Cache Cleared!";
} else {
msg = "Cache not present: it cannot be cleared!";
}
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
}
}
use of org.apache.commons.fileupload.FileItem in project openmrs-core by openmrs.
the class StartupErrorFilter method doPost.
/**
* @see org.openmrs.web.filter.StartupFilter#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
// if they are uploading modules
if (getModel().errorAtStartup instanceof OpenmrsCoreModuleException) {
RequestContext requestContext = new ServletRequestContext(httpRequest);
if (!ServletFileUpload.isMultipartContent(requestContext)) {
throw new ServletException("The request is not a valid multipart/form-data upload request");
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
Context.openSession();
List<FileItem> items = upload.parseRequest(requestContext);
for (FileItem item : items) {
InputStream uploadedStream = item.getInputStream();
ModuleUtil.insertModuleFile(uploadedStream, item.getName());
}
} catch (FileUploadException ex) {
throw new ServletException("Error while uploading file(s)", ex);
} finally {
Context.closeSession();
}
Map<String, Object> map = new HashMap<>();
map.put("success", Boolean.TRUE);
renderTemplate("coremoduleerror.vm", map, httpResponse);
// TODO restart openmrs here instead of going to coremodulerror template
}
}
use of org.apache.commons.fileupload.FileItem in project cerberus-source by cerberustesting.
the class UpdateTestDataLib method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
response.setContentType("application/json");
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
String type = policy.sanitize(fileData.get("type"));
String system = policy.sanitize(fileData.get("system"));
String environment = policy.sanitize(fileData.get("environment"));
String country = policy.sanitize(fileData.get("country"));
String database = policy.sanitize(fileData.get("database"));
String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
// Parameter that needs to be secured --> We SECURE+DECODE them
// this is mandatory
String name = fileData.get("name");
String group = fileData.get("group");
String description = fileData.get("libdescription");
String service = fileData.get("service");
// Parameter that we cannot secure as we need the html --> We DECODE them
String script = fileData.get("script");
String servicePath = fileData.get("servicepath");
String method = fileData.get("method");
String envelope = fileData.get("envelope");
String csvUrl = fileData.get("csvUrl");
String separator = fileData.get("separator");
String activateAutoSubdata = fileData.get("subdataCheck");
Integer testdatalibid = 0;
boolean testdatalibid_error = true;
try {
if (fileData.get("testdatalibid") != null && !fileData.get("testdatalibid").isEmpty()) {
testdatalibid = Integer.valueOf(fileData.get("testdatalibid"));
testdatalibid_error = false;
}
} catch (NumberFormatException ex) {
testdatalibid_error = true;
LOG.warn(ex);
}
try {
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(name)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Test data library name is missing."));
finalAnswer.setResultMessage(msg);
} else if (testdatalibid_error) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test data library").replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert testdatalibid to an integer value or testdatalibid is missing."));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
// specific attributes
ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
AnswerItem resp = libService.readByKey(testdatalibid);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the
* error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
TestDataLib lib = (TestDataLib) resp.getItem();
String fileName = lib.getCsvUrl();
if (file != null) {
ans = libService.uploadFile(lib.getTestDataLibID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
fileName = file.getName();
}
}
lib.setName(name);
lib.setType(type);
lib.setGroup(group);
lib.setDescription(description);
lib.setSystem(system);
lib.setEnvironment(environment);
lib.setCountry(country);
lib.setDatabase(database);
lib.setScript(script);
lib.setDatabaseUrl(databaseUrl);
lib.setServicePath(servicePath);
lib.setService(service);
lib.setMethod(method);
lib.setEnvelope(envelope);
lib.setDatabaseCsv(databaseCsv);
if (file == null) {
lib.setCsvUrl(csvUrl);
} else {
lib.setCsvUrl(File.separator + lib.getTestDataLibID() + File.separator + fileName);
}
lib.setSeparator(separator);
lib.setLastModifier(request.getRemoteUser());
ans = libService.update(lib);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update operation finished with success, then the
* logging entry must be added.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateTestDataLib", "UPDATE", "Update TestDataLib - id: " + testdatalibid + " name: " + name + " system: " + system + " environment: " + environment + " country: " + country, request);
}
List<TestDataLibData> tdldList = new ArrayList();
// Getting list of SubData from JSON Call
if (fileData.get("subDataList") != null) {
JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
tdldList = getSubDataFromParameter(request, appContext, testdatalibid, objSubDataArray);
}
// When File has just been uploaded to servlet and flag to load the subdata value has been checked, we will parse it in order to automatically feed the subdata.
if (file != null && activateAutoSubdata.equals("1")) {
String str = "";
try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibcsv_path", "", null) + lib.getCsvUrl()))) {
// First line of the file is split by separator.
str = reader.readLine();
String[] subData = (!lib.getSeparator().isEmpty()) ? str.split(lib.getSeparator()) : str.split(",");
// We take the subdata from the servlet input.
TestDataLibData firstLine = tdldList.get(0);
tdldList = new ArrayList();
firstLine.setColumnPosition("1");
tdldList.add(firstLine);
int i = 1;
for (String item : subData) {
String subdataName = "SUBDATA" + i;
TestDataLibData tdld = tdldFactory.create(null, testdatalibid, subdataName, item, null, null, Integer.toString(i), null);
tdldList.add(tdld);
i++;
}
// Update the Database with the new list.
} finally {
try {
file.getInputStream().close();
} catch (Throwable ignore) {
}
}
}
ans = tdldService.compareListAndUpdateInsertDeleteElements(testdatalibid, tdldList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
} catch (JSONException ex) {
LOG.warn(ex);
// returns a default error message with the json format that is able to be parsed by the client-side
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
}
}
Aggregations