Java Code Examples for org.apache.struts.upload.FormFile#getFileSize()

The following examples show how to use org.apache.struts.upload.FormFile#getFileSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ComMailingAttachmentsAction.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private static boolean newAttachmentHasName(ComMailingAttachmentsForm form) {
       FormFile file = form.getNewAttachment();
	if (file == null || file.getFileSize() <= 0) {
           // No upload file (size <= 0)? Then we don't need a name.
		return true;
	} else {
		return StringUtils.isNotBlank(form.getNewAttachmentName());
	}
}
 
Example 2
Source File: ConfigFileForm.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate a file-upload. This checks that:
 * <ul>
 * <li>The file exists
 * <li>The file isn't too large
 * <li>If the file is text, its contents are valid after macro-substitution
 * </ul>
 * @param request the incoming request
 * @return a ValidatorResult..  The list is empty if everything is OK
 */
public ValidatorResult validateUpload(HttpServletRequest request) {
    ValidatorResult msgs = new ValidatorResult();

    FormFile file = (FormFile)get(REV_UPLOAD);
    //make sure there is a file
    if (file == null ||
        file.getFileName() == null ||
        file.getFileName().trim().length() == 0) {
        msgs.addError(new ValidatorError("error.config-not-specified"));

    }
    else if (file.getFileSize() == 0) {
        msgs.addError(new ValidatorError("error.config-empty",
                                                    file.getFileName()));
    }
    //make sure they didn't send in something huge
    else if (file.getFileSize() > ConfigFile.getMaxFileSize()) {
        msgs.addError(new ValidatorError("error.configtoolarge",
                StringUtil.displayFileSize(ConfigFile.getMaxFileSize(), false)));
    }
    // It exists and isn't too big - is it text?
    else if (!isBinary()) {
        try {
            String content = new String(file.getFileData());
            String startDelim = getString(REV_MACROSTART);
            String endDelim   = getString(REV_MACROEND);
            msgs.append(ConfigurationValidation.validateContent(
                                content, startDelim, endDelim));
        }
        catch (Exception e) {
            msgs.addError(new ValidatorError("error.fatalupload",
                              StringUtil.displayFileSize(
                                      ConfigFile.getMaxFileSize(), false)));
        }
    }

    return msgs;
}
 
Example 3
Source File: ConfigFileForm.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate a file-upload. This checks that:
 * <ul>
 * <li>The file exists
 * <li>The file isn't too large
 * <li>If the file is text, its contents are valid after macro-substitution
 * </ul>
 * @param request the incoming request
 * @return a ValidatorResult..  The list is empty if everything is OK
 */
public ValidatorResult validateUpload(HttpServletRequest request) {
    ValidatorResult msgs = new ValidatorResult();

    FormFile file = (FormFile)get(REV_UPLOAD);
    //make sure there is a file
    if (file == null ||
        file.getFileName() == null ||
        file.getFileName().trim().length() == 0) {
        msgs.addError(new ValidatorError("error.config-not-specified"));

    }
    else if (file.getFileSize() == 0) {
        msgs.addError(new ValidatorError("error.config-empty",
                                                    file.getFileName()));
    }
    //make sure they didn't send in something huge
    else if (file.getFileSize() > ConfigFile.getMaxFileSize()) {
        msgs.addError(new ValidatorError("error.configtoolarge",
                StringUtil.displayFileSize(ConfigFile.getMaxFileSize(), false)));
    }
    // It exists and isn't too big - is it text?
    else if (!isBinary()) {
        try {
            String content = new String(file.getFileData());
            String startDelim = getString(REV_MACROSTART);
            String endDelim   = getString(REV_MACROEND);
            msgs.append(ConfigurationValidation.validateContent(
                                content, startDelim, endDelim));
        }
        catch (Exception e) {
            msgs.addError(new ValidatorError("error.fatalupload",
                              StringUtil.displayFileSize(
                                      ConfigFile.getMaxFileSize(), false)));
        }
    }

    return msgs;
}
 
Example 4
Source File: MailingWizardAction.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
    * If the user is not logged in - forwards to login page.
    * Checks if the size of new attachment exceeds the max allowed size for attachment. If the size is over the limit
    * adds appropriate error messages. If the size is ok - creates a new mailing component for attachment and fills it
    * with data and adds that component to mailing. Loads list of target groups into request. Forwards to attachments
    * page
    *
    * @param mapping The ActionMapping used to select this instance
    * @param form data for the action filled by the jsp
    * @param req request from jsp
    * @param res response
    * @return destination specified in struts-config.xml to forward to next jsp
    * @throws Exception if a exception occurs
    */
public ActionForward attachment(ActionMapping mapping, ActionForm form,
		HttpServletRequest req, HttpServletResponse res) throws Exception {
	if (!AgnUtils.isUserLoggedIn(req)) {
		return mapping.findForward("logon");
	}

	MailingWizardForm aForm = (MailingWizardForm) form;
	FormFile newAttachment=aForm.getNewAttachment();
       try	{
           int fileSize = newAttachment.getFileSize();
           boolean maxSizeOverflow = false;
           // check for parameter max_allowed_packet
           String maxSize = configService.getValue(ConfigValue.AttachmentMaxSize);
           if (fileSize != 0 && maxSize != null && fileSize > Integer.parseInt(maxSize)){
               maxSizeOverflow = true;
           }
           if (fileSize != 0 && !maxSizeOverflow) {
			MailingComponent comp=mailingComponentFactory.newMailingComponent();

			comp.setCompanyID(AgnUtils.getCompanyID(req));
			comp.setMailingID(aForm.getMailing().getId());
			if(aForm.getNewAttachmentType() == 0) {
				comp.setType(MailingComponent.TYPE_ATTACHMENT);
			} else {
				comp.setType(MailingComponent.TYPE_PERSONALIZED_ATTACHMENT);
			}
			if(aForm.getNewAttachmentName().isEmpty()) {
				aForm.setNewAttachmentName(aForm.getNewAttachment().getFileName());
			}

			comp.setComponentName(aForm.getNewAttachmentName());
			comp.setBinaryBlock(newAttachment.getFileData(), newAttachment.getContentType());
			comp.setTargetID(aForm.getAttachmentTargetID());
			aForm.getMailing().addComponent(comp);
			userActivityLogService.writeUserActivityLog(AgnUtils.getAdmin(req), "upload mailing attachment", "Mailing ID: "+aForm.getMailing().getId()+", component name: "+aForm.getNewAttachmentName());
           } else if (maxSizeOverflow) {
               ActionMessages errors = new ActionMessages();
               errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.attachment", maxSize));
               saveErrors(req, errors);
           }

	} catch (Exception e) {
		logger.error("saveAttachment: "+e);
	}
       prepareAttachmentPage(req);
	return mapping.findForward("next");
}
 
Example 5
Source File: ComMailingComponentsForm.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setNewFile(int index, FormFile newImage) {
	if(newImage != null && StringUtils.isNotEmpty(newImage.getFileName()) && newImage.getFileSize() != 0) {
		newFiles.put(index, newImage);
	}
}
 
Example 6
Source File: ComMailingComponentsAction.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void addUploadedFiles(ComMailingComponentsForm componentForm, Mailing mailing, HttpServletRequest req, ActionMessages messages, ActionMessages errors) throws Exception {
	Set<Integer> indices = componentForm.getIndices();

	int foundItemsToStore = 0;
	int successfullyStoredItems = 0;
	
	for (int index : indices) {
		// Check if any part of this item was filled at all
           FormFile file = componentForm.getNewFile(index);
           if (file != null && StringUtils.isNotBlank(file.getFileName()) && file.getFileName().toLowerCase().endsWith(".zip")) {
               ComMailingComponentsService.UploadStatistics statistics = mailingComponentService.uploadZipArchive(mailing, file);
               foundItemsToStore += statistics.getFound();
               successfullyStoredItems += statistics.getStored();
               writeUserActivityLog(AgnUtils.getAdmin(req), "upload mailing component file", "Mailing ID: " + mailing.getId() + ", type: ZIP, Name: " + file.getFileName() + ", found items to store: " + statistics.getFound() + ", successfully stored items: " + statistics.getStored());
           } else {
            String link = componentForm.getLink(index);
            String description = componentForm.getDescriptionByIndex(index);
            String baseComponentForMobileComponent = componentForm.getMobileComponentBaseComponent(index);

			if ((file != null && StringUtils.isNotBlank(file.getFileName()))
					|| StringUtils.isNotBlank(link)
					|| StringUtils.isNotBlank(description)
					|| StringUtils.isNotBlank(baseComponentForMobileComponent)) {
				foundItemsToStore++;
				// Check if mandatory parts are missing
				if (file == null || StringUtils.isBlank(file.getFileName())) {
	                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("mailing.errors.no_component_file"));
	            } else {
					String newComponentName = null;
					if (StringUtils.isNotBlank(baseComponentForMobileComponent)) {
						newComponentName = ShowImageServlet.MOBILE_IMAGE_PREFIX + baseComponentForMobileComponent;
						if (StringUtils.isBlank(description)) {
                            description = "Mobile component for " + baseComponentForMobileComponent;
						} else {
                            description = description + " / Mobile component for " + baseComponentForMobileComponent;
						}
					}
	
					if (StringUtils.isBlank(newComponentName)) {
                        newComponentName = file.getFileName();
                    }

                    try {
                        if (file.getFileSize() > 0) {
                        	MailingComponent component = mailing.getComponents().get(newComponentName);
							if (component != null && component.getType() == MailingComponent.TYPE_HOSTED_IMAGE) {
								// Update existing image
								component.setBinaryBlock(file.getFileData(), file.getContentType());
								component.setLink(link);
								component.setDescription(description);
							} else {
								// Store new image
								component = new MailingComponentImpl();
								component.setCompanyID(mailing.getCompanyID());
								component.setMailingID(componentForm.getMailingID());
								component.setType(MailingComponent.TYPE_HOSTED_IMAGE);
								component.setDescription(description);
								component.setComponentName(newComponentName);
								component.setBinaryBlock(file.getFileData(), file.getContentType());
								component.setLink(link);
								mailing.addComponent(component);
							}
						}
					} catch (Exception e) {
						logger.error("saveComponent: " + e);
					}

					if (componentForm.getAction() == ACTION_SAVE_COMPONENT_EDIT) {
						req.setAttribute("file_path",
								AgnUtils.getAdmin(req).getCompany().getRdirDomain() + "/image?ci=" + mailing.getCompanyID() + "&mi=" + componentForm.getMailingID() + "&name=" + file.getFileName());
					}
					
					// Reset MobileComponentBaseComponent for next upload request from gui
                    componentForm.setMobileComponentBaseComponent(index, "");
					successfullyStoredItems++;
                       writeUserActivityLog(AgnUtils.getAdmin(req), "upload mailing component file", "Mailing ID: "+mailing.getId() + ", type: image, name: " + newComponentName);
	            }
			}
           }
	}
	
	if (foundItemsToStore > 0) {
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("items_saved", successfullyStoredItems, foundItemsToStore));
	}
}
 
Example 7
Source File: ComMailingAttachmentsAction.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
* Saves attachement
*/
  protected void saveAttachment(ComMailingAttachmentsForm aForm, HttpServletRequest req, ActionMessages errors) {
      MailingComponent aComp=null;
      String aParam=null;
      UploadData uploadData = null;
      Vector<MailingComponent> deleteEm=new Vector<>();

      Mailing aMailing=mailingDao.getMailing(aForm.getMailingID(), AgnUtils.getCompanyID(req));

      FormFile background = aForm.getNewAttachmentBackground();
      try {
          if (aForm.isUsePdfUpload()) {
              if (aForm.getAttachmentPdfFileID() != 0) {
                  aComp = mailingComponentFactory.newMailingComponent();
                  aComp.setCompanyID(AgnUtils.getCompanyID(req));
                  aComp.setMailingID(aForm.getMailingID());
                  uploadData = uploadDao.loadData(aForm.getAttachmentPdfFileID());
                  if (aForm.getNewAttachmentType() == 0) {
                      aComp.setType(MailingComponent.TYPE_ATTACHMENT);
                      aComp.setComponentName(uploadData.getFilename());
                      aComp.setBinaryBlock(uploadData.getData(), "application/pdf");
                  } else {
                      aComp.setType(MailingComponent.TYPE_PERSONALIZED_ATTACHMENT);
                      aComp.setComponentName(uploadData.getFilename());
                      aComp.setBinaryBlock(background.getFileData(), "application/pdf");
                      aMailing.findDynTagsInTemplates(new String(uploadData.getData(), "UTF-8"), getApplicationContext(req));
                  }
                  aComp.setTargetID(aForm.getAttachmentTargetID());
                  aMailing.addComponent(aComp);
              }
          } else {
              FormFile newAttachment = aForm.getNewAttachment();
              if (newAttachment != null && newAttachment.getFileSize() != 0) {
                  aComp = mailingComponentFactory.newMailingComponent();
                  aComp.setCompanyID(AgnUtils.getCompanyID(req));
                  aComp.setMailingID(aForm.getMailingID());
                  if (aForm.getNewAttachmentType() == 0) {
                      aComp.setType(MailingComponent.TYPE_ATTACHMENT);
                      aComp.setComponentName(aForm.getNewAttachmentName());
                      aComp.setBinaryBlock(newAttachment.getFileData(), newAttachment.getContentType());
                  } else {
                      aComp.setType(MailingComponent.TYPE_PERSONALIZED_ATTACHMENT);
                      aComp.setComponentName(aForm.getNewAttachmentName());
                      aComp.setBinaryBlock(background.getFileData(), "application/pdf");
                      aMailing.findDynTagsInTemplates(new String(newAttachment.getFileData(), "UTF-8"), getApplicationContext(req));
                  }
                  aComp.setTargetID(aForm.getAttachmentTargetID());
                  aMailing.addComponent(aComp);
                  writeUserActivityLog(AgnUtils.getAdmin(req), "upload mailing attachment", "Mailing ID: " + aForm.getMailingID() + ", attachment name: " + aForm.getNewAttachmentName());
              }
          }
      } catch (Exception e) {
          logger.error("saveAttachment: " + e.getMessage(), e);
          errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception", configService.getValue(ConfigValue.SupportEmergencyUrl)));
      }

      for (MailingComponent component : aMailing.getComponents().values()) {
          switch (component.getType()) {
              case MailingComponent.TYPE_PERSONALIZED_ATTACHMENT:
              case MailingComponent.TYPE_ATTACHMENT:
                  aParam = req.getParameter("delete" + component.getId());
                  if (aParam != null && aParam.equals("delete")) {
                      deleteEm.add(component);
                  }
                  aParam = req.getParameter("target" + component.getId());
                  if (aParam != null) {
                      component.setTargetID(Integer.parseInt(aParam));
                  }
                  break;
		default:
			break;
          }
      }

      Enumeration<MailingComponent> en=deleteEm.elements();
      while(en.hasMoreElements()) {

      	MailingComponent mailingComponent = en.nextElement();
      	componentDao.deleteMailingComponent(mailingComponent);
      	aMailing.getComponents().remove( mailingComponent.getComponentName());
      }

      mailingDao.saveMailing(aMailing, false);
  }
 
Example 8
Source File: TestServiceExecute.java    From iaf with Apache License 2.0 4 votes vote down vote up
public ActionForward executeSub(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {

        // Initialize action
        initAction(request);

        DynaActionForm serviceTestForm = (DynaActionForm) form;
//        List form_services = (List) serviceTestForm.get("services");
        String form_serviceName = (String) serviceTestForm.get("serviceName");
        String form_message = (String) serviceTestForm.get("message");
        String form_result = (String) serviceTestForm.get("message");
        FormFile form_file = (FormFile) serviceTestForm.get("file");

        // if no message and no formfile, send an error
        if ((form_message == null) || (form_message.length() == 0)) {
            if ((form_file == null) || (form_file.getFileSize() == 0)) {
                storeFormData(null, null, serviceTestForm);
                warn("Nothing to send or test");
            }
        }
        // Report any errors we have discovered back to the original form
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            storeFormData(null, null, serviceTestForm);
            return (new ActionForward(mapping.getInput()));
        }
        if ((form_serviceName == null) || (form_serviceName.length() == 0)) {
            warn("No service selected");
        }
        // Report any errors we have discovered back to the original form
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            storeFormData(null, form_message, serviceTestForm);
            return (new ActionForward(mapping.getInput()));
        }
        // Execute the request
        if (!(ServiceDispatcher.getInstance().isRegisteredServiceListener(form_serviceName)))
        	warn("Servicer with specified name [" + form_serviceName
                        + "] is not registered at the Dispatcher");
        // Report any errors we have discovered back to the original form
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            storeFormData(null, form_message, serviceTestForm);
            return (new ActionForward(mapping.getInput()));
        }

        // if upload is choosen, it prevails over the message
        if ((form_file != null) && (form_file.getFileSize() > 0)) {
            form_message = XmlUtils.readXml(form_file.getFileData(),request.getCharacterEncoding(),false);
            log.debug(
                "Upload of file ["
                    + form_file.getFileName()
                    + "] ContentType["
                    + form_file.getContentType()
                    + "]");

        } else {
			form_message=new String(form_message.getBytes(),Misc.DEFAULT_INPUT_STREAM_ENCODING);
        }
        form_result = "";
        // Execute the request
        try {
        	Map context = new HashMap();
            form_result =
                ServiceDispatcher.getInstance().dispatchRequest(form_serviceName, null, form_message, context);
        } catch (Exception e) {
        	warn("Service with specified name [" + form_serviceName + "] got error",e);
        }
        storeFormData(form_result, form_message, serviceTestForm);

        // Report any errors we have discovered back to the original form
        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            return (new ActionForward(mapping.getInput()));
        }

        // Forward control to the specified success URI
        log.debug("forward to success");
        return (mapping.findForward("success"));

    }