Java Examples for org.springframework.web.multipart.commons.CommonsMultipartFile
The following java examples will help you to understand the usage of org.springframework.web.multipart.commons.CommonsMultipartFile. These source code samples are taken from different open source projects.
Example 1
| Project: head-master File: LoanAccountController.java View source code |
@SuppressWarnings("PMD")
public LoanCreationLoanDetailsDto retrieveLoanCreationDetails(int customerId, int productId, String eventId, String fileToDelete, LoanAccountFormBean formBean) {
if ("newFileSelected".equals(eventId)) {
if (formBean.getSelectedFile() != null) {
CommonsMultipartFile file = formBean.getSelectedFile();
formBean.getFiles().add(file);
formBean.getFilesMetadata().add(new UploadedFileDto(file.getOriginalFilename(), file.getContentType(), (int) file.getSize(), formBean.getSelectedFileDescription()));
}
return dto;
} else if ("fileDeleted".equals(eventId)) {
if (fileToDelete != null) {
int index = 0;
for (CommonsMultipartFile formFile : formBean.getFiles()) {
if (formFile.getOriginalFilename().equals(fileToDelete)) {
index = formBean.getFiles().indexOf(formFile);
break;
}
}
if (index >= 0) {
formBean.getFiles().remove(index);
formBean.getFilesMetadata().remove(index);
}
}
return dto;
}
MandatoryHiddenFieldsDto mandatoryHidden = this.adminServiceFacade.retrieveHiddenMandatoryFieldsToRead();
dto = this.loanAccountServiceFacade.retrieveLoanDetailsForLoanAccountCreation(customerId, Integer.valueOf(productId).shortValue(), formBean.isRedoLoanAccount());
formBean.setLocale(Locale.getDefault());
formBean.setDigitsBeforeDecimalForInterest(dto.getAppConfig().getDigitsBeforeDecimalForInterest());
formBean.setDigitsAfterDecimalForInterest(dto.getAppConfig().getDigitsAfterDecimalForInterest());
formBean.setDigitsBeforeDecimalForMonetaryAmounts(dto.getAppConfig().getDigitsBeforeDecimalForMonetaryAmounts());
formBean.setDigitsAfterDecimalForMonetaryAmounts(dto.getAppConfig().getDigitsAfterDecimalForMonetaryAmounts());
formBean.setProductId(productId);
formBean.setCustomerId(dto.getCustomerDetailDto().getCustomerId());
formBean.setRepaymentScheduleIndependentOfCustomerMeeting(dto.isRepaymentIndependentOfMeetingEnabled());
formBean.setGraceDuration(dto.getGracePeriodInInstallments());
formBean.setMaxGraceDuration(dto.getGracePeriodInInstallments());
if (dto.isRepaymentIndependentOfMeetingEnabled()) {
// use loan product to default meeting details
Integer recursEvery = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getEvery();
Integer dayOfMonth = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayNumber();
Integer weekOfMonth = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getWeekOfMonth();
Integer dayOfWeek = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayOfWeek();
Integer recurrenceType = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceTypeId();
Integer customerRecurrenceType = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceTypeId();
if (recurrenceType.equals(customerRecurrenceType)) {
// if customer and product meeting frequencies are the same e.g. weekly or monthly, then default to customer details except for recurrence details
dayOfMonth = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayNumber();
weekOfMonth = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getWeekOfMonth();
dayOfWeek = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayOfWeek();
}
// sometimes it seems customer meeting information can be setup wrong (i.e. has a day of month even though its weekly)
if (recurrenceType == 1) {
if (dateInformationIsAvailable(dayOfWeek)) {
formBean.setWeeklyDetails(dayOfWeek, recursEvery);
}
} else if (recurrenceType == 2) {
if (dateInformationIsAvailable(weekOfMonth) && dateInformationIsAvailable(dayOfWeek)) {
formBean.setWeekOfMonthDetails(weekOfMonth, dayOfWeek, recursEvery);
} else if (dateInformationIsAvailable(dayOfMonth)) {
formBean.setDayOfMonthDetails(dayOfMonth, recursEvery);
}
} else if (recurrenceType == 3) {
formBean.setRepaymentRecursEvery(recursEvery);
}
}
formBean.setVariableInstallmentsAllowed(dto.isVariableInstallmentsAllowed());
if (dto.isVariableInstallmentsAllowed()) {
formBean.setMinGapInDays(dto.getMinGapInDays());
formBean.setMaxGapInDays(dto.getMaxGapInDays());
formBean.setMinInstallmentAmount(dto.getMinInstallmentAmount());
}
formBean.setGlimApplicable(dto.isGlimApplicable());
if (dto.isGroup()) {
formBean.setGroupLoanWithMembersEnabled(dto.isGroupLoanWithMembersEnabled());
}
if (dto.isGlimApplicable() || (dto.isGroup() && dto.isGroupLoanWithMembersEnabled())) {
List<LoanAccountDetailsDto> clientData = dto.getClientDetails();
String[] clientGlobalIdArray = new String[clientData.size()];
int index = 0;
for (LoanAccountDetailsDto loanAccountDetailsDto : clientData) {
clientGlobalIdArray[index] = loanAccountDetailsDto.getClientId();
index++;
}
formBean.setClientGlobalId(clientGlobalIdArray);
formBean.setClientSelectForGroup(new Boolean[clientData.size()]);
formBean.setClientAmount(new Number[clientData.size()]);
Integer[] loanPurpose = new Integer[clientData.size()];
formBean.setClientLoanPurposeId(loanPurpose);
Number[][] selectedFeeIndividualAmounts = new Number[3][clientData.size()];
formBean.setSelectedFeeIndividualAmounts(selectedFeeIndividualAmounts);
Number[][] defaultFeeIndividualAmounts = new Number[dto.getDefaultFees().size()][clientData.size()];
formBean.setDefaultFeeIndividualAmounts(defaultFeeIndividualAmounts);
} else {
formBean.setAmount(Double.valueOf(dto.getDefaultLoanAmount().toPlainString()));
}
formBean.setMinAllowedAmount(dto.getMinLoanAmount());
formBean.setMaxAllowedAmount(dto.getMaxLoanAmount());
formBean.setInterestRate(dto.getDefaultInterestRate());
formBean.setMinAllowedInterestRate(dto.getMinInterestRate());
formBean.setMaxAllowedInterestRate(dto.getMaxInterestRate());
formBean.setNumberOfInstallments(dto.getDefaultNumberOfInstallments());
formBean.setMinNumberOfInstallments(dto.getMinNumberOfInstallments());
formBean.setMaxNumberOfInstallments(dto.getMaxNumberOfInstallments());
formBean.setSourceOfFundsMandatory(mandatoryHidden.isMandatoryLoanSourceOfFund());
formBean.setPurposeOfLoanMandatory(mandatoryHidden.isMandatoryLoanAccountPurpose());
formBean.setCollateralTypeAndNotesHidden(mandatoryHidden.isHideSystemCollateralTypeNotes());
formBean.setExternalIdHidden(mandatoryHidden.isHideSystemExternalId());
if (!mandatoryHidden.isHideSystemExternalId()) {
formBean.setExternalIdMandatory(mandatoryHidden.isMandatorySystemExternalId());
}
LocalDate possibleDisbursementDate = dto.getNextPossibleDisbursementDate();
if (possibleDisbursementDate != null) {
formBean.setDisbursementDateDD(possibleDisbursementDate.getDayOfMonth());
formBean.setDisbursementDateMM(possibleDisbursementDate.getMonthOfYear());
formBean.setDisbursementDateYY(possibleDisbursementDate.getYearOfEra());
}
formBean.setCollateralNotes("");
Number[] defaultFeeId = new Number[dto.getDefaultFees().size()];
Number[] defaultFeeAmountOrRate = new Number[dto.getDefaultFees().size()];
int index = 0;
for (FeeDto defaultFee : dto.getDefaultFees()) {
if (defaultFee.isRateBasedFee()) {
defaultFeeAmountOrRate[index] = defaultFee.getRate();
} else {
defaultFeeAmountOrRate[index] = defaultFee.getAmountAsNumber();
}
defaultFeeId[index] = Long.valueOf(defaultFee.getId());
index++;
}
formBean.setDefaultFeeAmountOrRate(defaultFeeAmountOrRate);
formBean.setDefaultFeeId(defaultFeeId);
formBean.setDefaultFeeSelected(new Boolean[dto.getDefaultFees().size()]);
formBean.setDefaultFees(dto.getDefaultFees());
Number[] defaultPenaltyId = new Number[dto.getDefaultPenalties().size()];
Number[] defaultPenaltyAmountOrRate = new Number[dto.getDefaultPenalties().size()];
int idx = 0;
for (PenaltyDto defaultPenalty : dto.getDefaultPenalties()) {
if (defaultPenalty.isRateBasedPenalty()) {
defaultPenaltyAmountOrRate[idx] = defaultPenalty.getRate();
} else {
defaultPenaltyAmountOrRate[idx] = defaultPenalty.getAmountAsNumber();
}
defaultPenaltyId[idx] = Long.valueOf(defaultPenalty.getPenaltyId());
idx++;
}
formBean.setDefaultPenaltyAmountOrRate(defaultPenaltyAmountOrRate);
formBean.setDefaultPenaltyId(defaultPenaltyId);
formBean.setDefaultPenaltySelected(new Boolean[dto.getDefaultPenalties().size()]);
formBean.setDefaultPenalties(dto.getDefaultPenalties());
Number[] selectedFeeId = new Number[3];
formBean.setSelectedFeeId(selectedFeeId);
Number[] selectedFeeAmount = new Number[3];
formBean.setSelectedFeeAmount(selectedFeeAmount);
formBean.setAdditionalFees(dto.getAdditionalFees());
if (formBean.getFiles() == null) {
formBean.setFiles(new ArrayList<CommonsMultipartFile>());
formBean.setFilesMetadata(new ArrayList<UploadedFileDto>());
}
formBean.setLoanInformationOrder(informationOrderServiceFacade.getInformationOrder("CreateLoan"));
return dto;
}Example 2
| Project: mifos-head-master File: LoanAccountController.java View source code |
@SuppressWarnings("PMD")
public LoanCreationLoanDetailsDto retrieveLoanCreationDetails(int customerId, int productId, String eventId, String fileToDelete, LoanAccountFormBean formBean) {
if ("newFileSelected".equals(eventId)) {
if (formBean.getSelectedFile() != null) {
CommonsMultipartFile file = formBean.getSelectedFile();
formBean.getFiles().add(file);
formBean.getFilesMetadata().add(new UploadedFileDto(file.getOriginalFilename(), file.getContentType(), (int) file.getSize(), formBean.getSelectedFileDescription()));
}
return dto;
} else if ("fileDeleted".equals(eventId)) {
if (fileToDelete != null) {
int index = 0;
for (CommonsMultipartFile formFile : formBean.getFiles()) {
if (formFile.getOriginalFilename().equals(fileToDelete)) {
index = formBean.getFiles().indexOf(formFile);
break;
}
}
if (index >= 0) {
formBean.getFiles().remove(index);
formBean.getFilesMetadata().remove(index);
}
}
return dto;
}
MandatoryHiddenFieldsDto mandatoryHidden = this.adminServiceFacade.retrieveHiddenMandatoryFieldsToRead();
dto = this.loanAccountServiceFacade.retrieveLoanDetailsForLoanAccountCreation(customerId, Integer.valueOf(productId).shortValue(), formBean.isRedoLoanAccount());
formBean.setLocale(Locale.getDefault());
formBean.setDigitsBeforeDecimalForInterest(dto.getAppConfig().getDigitsBeforeDecimalForInterest());
formBean.setDigitsAfterDecimalForInterest(dto.getAppConfig().getDigitsAfterDecimalForInterest());
formBean.setDigitsBeforeDecimalForMonetaryAmounts(dto.getAppConfig().getDigitsBeforeDecimalForMonetaryAmounts());
formBean.setDigitsAfterDecimalForMonetaryAmounts(dto.getAppConfig().getDigitsAfterDecimalForMonetaryAmounts());
formBean.setProductId(productId);
formBean.setCustomerId(dto.getCustomerDetailDto().getCustomerId());
formBean.setRepaymentScheduleIndependentOfCustomerMeeting(dto.isRepaymentIndependentOfMeetingEnabled());
formBean.setGraceDuration(dto.getGracePeriodInInstallments());
formBean.setMaxGraceDuration(dto.getGracePeriodInInstallments());
if (dto.isRepaymentIndependentOfMeetingEnabled()) {
// use loan product to default meeting details
Integer recursEvery = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getEvery();
Integer dayOfMonth = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayNumber();
Integer weekOfMonth = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getWeekOfMonth();
Integer dayOfWeek = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayOfWeek();
Integer recurrenceType = dto.getLoanOfferingMeetingDetail().getMeetingDetailsDto().getRecurrenceTypeId();
Integer customerRecurrenceType = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceTypeId();
if (recurrenceType.equals(customerRecurrenceType)) {
// if customer and product meeting frequencies are the same e.g. weekly or monthly, then default to customer details except for recurrence details
dayOfMonth = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayNumber();
weekOfMonth = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getWeekOfMonth();
dayOfWeek = dto.getCustomerMeetingDetail().getMeetingDetailsDto().getRecurrenceDetails().getDayOfWeek();
}
// sometimes it seems customer meeting information can be setup wrong (i.e. has a day of month even though its weekly)
if (recurrenceType == 1) {
if (dateInformationIsAvailable(dayOfWeek)) {
formBean.setWeeklyDetails(dayOfWeek, recursEvery);
}
} else if (recurrenceType == 2) {
if (dateInformationIsAvailable(weekOfMonth) && dateInformationIsAvailable(dayOfWeek)) {
formBean.setWeekOfMonthDetails(weekOfMonth, dayOfWeek, recursEvery);
} else if (dateInformationIsAvailable(dayOfMonth)) {
formBean.setDayOfMonthDetails(dayOfMonth, recursEvery);
}
} else if (recurrenceType == 3) {
formBean.setRepaymentRecursEvery(recursEvery);
}
}
formBean.setVariableInstallmentsAllowed(dto.isVariableInstallmentsAllowed());
if (dto.isVariableInstallmentsAllowed()) {
formBean.setMinGapInDays(dto.getMinGapInDays());
formBean.setMaxGapInDays(dto.getMaxGapInDays());
formBean.setMinInstallmentAmount(dto.getMinInstallmentAmount());
}
formBean.setGlimApplicable(dto.isGlimApplicable());
if (dto.isGroup()) {
formBean.setGroupLoanWithMembersEnabled(dto.isGroupLoanWithMembersEnabled());
}
if (dto.isGlimApplicable() || (dto.isGroup() && dto.isGroupLoanWithMembersEnabled())) {
List<LoanAccountDetailsDto> clientData = dto.getClientDetails();
String[] clientGlobalIdArray = new String[clientData.size()];
int index = 0;
for (LoanAccountDetailsDto loanAccountDetailsDto : clientData) {
clientGlobalIdArray[index] = loanAccountDetailsDto.getClientId();
index++;
}
formBean.setClientGlobalId(clientGlobalIdArray);
formBean.setClientSelectForGroup(new Boolean[clientData.size()]);
formBean.setClientAmount(new Number[clientData.size()]);
Integer[] loanPurpose = new Integer[clientData.size()];
formBean.setClientLoanPurposeId(loanPurpose);
Number[][] selectedFeeIndividualAmounts = new Number[3][clientData.size()];
formBean.setSelectedFeeIndividualAmounts(selectedFeeIndividualAmounts);
Number[][] defaultFeeIndividualAmounts = new Number[dto.getDefaultFees().size()][clientData.size()];
formBean.setDefaultFeeIndividualAmounts(defaultFeeIndividualAmounts);
} else {
formBean.setAmount(Double.valueOf(dto.getDefaultLoanAmount().toPlainString()));
}
formBean.setMinAllowedAmount(dto.getMinLoanAmount());
formBean.setMaxAllowedAmount(dto.getMaxLoanAmount());
formBean.setInterestRate(dto.getDefaultInterestRate());
formBean.setMinAllowedInterestRate(dto.getMinInterestRate());
formBean.setMaxAllowedInterestRate(dto.getMaxInterestRate());
formBean.setNumberOfInstallments(dto.getDefaultNumberOfInstallments());
formBean.setMinNumberOfInstallments(dto.getMinNumberOfInstallments());
formBean.setMaxNumberOfInstallments(dto.getMaxNumberOfInstallments());
formBean.setSourceOfFundsMandatory(mandatoryHidden.isMandatoryLoanSourceOfFund());
formBean.setPurposeOfLoanMandatory(mandatoryHidden.isMandatoryLoanAccountPurpose());
formBean.setCollateralTypeAndNotesHidden(mandatoryHidden.isHideSystemCollateralTypeNotes());
formBean.setExternalIdHidden(mandatoryHidden.isHideSystemExternalId());
if (!mandatoryHidden.isHideSystemExternalId()) {
formBean.setExternalIdMandatory(mandatoryHidden.isMandatorySystemExternalId());
}
LocalDate possibleDisbursementDate = dto.getNextPossibleDisbursementDate();
if (possibleDisbursementDate != null) {
formBean.setDisbursementDateDD(possibleDisbursementDate.getDayOfMonth());
formBean.setDisbursementDateMM(possibleDisbursementDate.getMonthOfYear());
formBean.setDisbursementDateYY(possibleDisbursementDate.getYearOfEra());
}
formBean.setCollateralNotes("");
Number[] defaultFeeId = new Number[dto.getDefaultFees().size()];
Number[] defaultFeeAmountOrRate = new Number[dto.getDefaultFees().size()];
int index = 0;
for (FeeDto defaultFee : dto.getDefaultFees()) {
if (defaultFee.isRateBasedFee()) {
defaultFeeAmountOrRate[index] = defaultFee.getRate();
} else {
defaultFeeAmountOrRate[index] = defaultFee.getAmountAsNumber();
}
defaultFeeId[index] = Long.valueOf(defaultFee.getId());
index++;
}
formBean.setDefaultFeeAmountOrRate(defaultFeeAmountOrRate);
formBean.setDefaultFeeId(defaultFeeId);
formBean.setDefaultFeeSelected(new Boolean[dto.getDefaultFees().size()]);
formBean.setDefaultFees(dto.getDefaultFees());
Number[] defaultPenaltyId = new Number[dto.getDefaultPenalties().size()];
Number[] defaultPenaltyAmountOrRate = new Number[dto.getDefaultPenalties().size()];
int idx = 0;
for (PenaltyDto defaultPenalty : dto.getDefaultPenalties()) {
if (defaultPenalty.isRateBasedPenalty()) {
defaultPenaltyAmountOrRate[idx] = defaultPenalty.getRate();
} else {
defaultPenaltyAmountOrRate[idx] = defaultPenalty.getAmountAsNumber();
}
defaultPenaltyId[idx] = Long.valueOf(defaultPenalty.getPenaltyId());
idx++;
}
formBean.setDefaultPenaltyAmountOrRate(defaultPenaltyAmountOrRate);
formBean.setDefaultPenaltyId(defaultPenaltyId);
formBean.setDefaultPenaltySelected(new Boolean[dto.getDefaultPenalties().size()]);
formBean.setDefaultPenalties(dto.getDefaultPenalties());
Number[] selectedFeeId = new Number[3];
formBean.setSelectedFeeId(selectedFeeId);
Number[] selectedFeeAmount = new Number[3];
formBean.setSelectedFeeAmount(selectedFeeAmount);
formBean.setAdditionalFees(dto.getAdditionalFees());
if (formBean.getFiles() == null) {
formBean.setFiles(new ArrayList<CommonsMultipartFile>());
formBean.setFilesMetadata(new ArrayList<UploadedFileDto>());
}
formBean.setLoanInformationOrder(informationOrderServiceFacade.getInformationOrder("CreateLoan"));
return dto;
}Example 3
| Project: appfuse-master File: FileUploadController.java View source code |
@RequestMapping(method = RequestMethod.POST)
public void onSubmit(@ModelAttribute FileUpload fileUpload, BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject jsonObject = new JSONObject();
if (StringUtils.isBlank(fileUpload.getName())) {
Object[] args = new Object[] { messages.getMessage("uploadForm.name", request.getLocale()) };
errors.rejectValue("name", "errors.required", args, "Name");
}
// validate a file was entered
if (fileUpload.getFile().length == 0) {
Object[] args = new Object[] { messages.getMessage("uploadForm.file", request.getLocale()) };
errors.rejectValue("file", "errors.required", args, "File");
}
if (errors.hasErrors()) {
List<String> errorMessages = new ArrayList<String>();
for (ObjectError error : errors.getAllErrors()) {
errorMessages.add(messages.getMessage(error));
}
jsonObject.put("errorMessages", errorMessages);
sendResponse(response, jsonObject);
return;
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
// the directory to upload to
String uploadDir = servletContext.getRealPath("/resources") + "/" + request.getRemoteUser() + "/";
// Create the directory if it doesn't exist
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// retrieve the file data
InputStream stream = file.getInputStream();
// write the file to the file specified
OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
// close the stream
stream.close();
// place the data into the request for retrieval on next page
jsonObject.put("name", fileUpload.getName());
jsonObject.put("fileName", file.getOriginalFilename());
jsonObject.put("contentType", file.getContentType());
jsonObject.put("size", file.getSize() + " bytes");
jsonObject.put("location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());
String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
jsonObject.put("link", link + file.getOriginalFilename());
sendResponse(response, jsonObject);
}Example 4
| Project: Tanaguru-master File: AddScenarioFormValidator.java View source code |
/**
*
* @param addScenarioCommand
* @param errors
* @return whether the scenario handled by the current AddScenarioCommand
* has a correct type and size
*/
public boolean checkScenarioFileTypeAndSize(AddScenarioCommand addScenarioCommand, Errors errors) {
if (addScenarioCommand.getScenarioFile() == null) {
// if no file uploaded
LOGGER.debug("empty Scenario File");
errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
return false;
}
Metadata metadata = new Metadata();
MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
String mime;
try {
CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile();
if (cmf.getSize() > maxFileSize) {
Long maxFileSizeInMega = maxFileSize / 1000000;
String[] arg = { maxFileSizeInMega.toString() };
errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
return false;
} else if (cmf.getSize() > 0) {
mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
LOGGER.debug("mime " + mime + " " + cmf.getOriginalFilename());
if (!authorizedMimeType.contains(mime)) {
errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
return false;
}
} else {
LOGGER.debug("File with size null");
errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
return false;
}
} catch (IOException ex) {
LOGGER.warn(ex);
errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
return false;
}
return true;
}Example 5
| Project: ALP-master File: LogController.java View source code |
@RequestMapping(method = RequestMethod.POST, value = "/results/test-method/{testMethodId}/log")
void saveLog(@PathVariable("testMethodId") long id, @ModelAttribute("uploadItem") UploadItem uploadItem, HttpServletRequest request, HttpServletResponse response) throws IOException {
CommonsMultipartFile fileData = uploadItem.getFileData();
// TODO Handle unexpected form data
String name = fileData.getOriginalFilename();
InputStream is = fileData.getInputStream();
ServletContext sc = request.getSession().getServletContext();
// geting parameter from context.xml stored under META-INF folder . Default value will be /var/lib/tomcat6/data/logs
String datalogsPath = sc.getInitParameter("datalogsPath");
// If file extension is '.xml' or none save it as 'index.xml'
if (name.toLowerCase().endsWith(".xml") || !name.matches(".*\\.\\w{1,3}$")) {
logStorage.saveLog(id, "index.xml", is, datalogsPath);
// TODO TestMethod database creation should be performed with Spring
// and REST web services, not from test listeners directly
TestMethod testMethod = testMethodDAO.getTestMethod(id);
// Set into DB that TestMethod has index log file
testMethod.setHasLog(true);
testMethodDAO.saveTestMethod(testMethod);
} else {
// Else save it with its original name
logStorage.saveLog(id, name, is, datalogsPath);
}
response.setStatus(HttpServletResponse.SC_CREATED);
// TODO add log URL to response according REST principles
}Example 6
| Project: JAppJUp-master File: FileServiceImp.java View source code |
@Override
public synchronized String saveMultipartFile(CommonsMultipartFile multipartFile) throws IOException {
logger.debug("Attempting to save MultipartFile: " + multipartFile.getName());
String storagePath = createStoragePath();
saveFile(getStorageDirectory() + storagePath, multipartFile.getBytes());
logger.debug("Saved MultipartFile: " + multipartFile.getName());
return storagePath;
}Example 7
| Project: toobs-master File: MultipartController.java View source code |
protected MultipartParsingResult parseFileItems(List fileItems, String encoding, int IHateYouJuergenHoeller) {
Map multipartFiles = new LinkedHashMap();
Map multipartParameters = new LinkedHashMap();
// Extract multipart files and multipart parameters.
for (Iterator it = fileItems.iterator(); it.hasNext(); ) {
FileItem fileItem = (FileItem) it.next();
if (fileItem.isFormField()) {
String value = null;
if (encoding != null) {
try {
value = fileItem.getString(encoding);
} catch (UnsupportedEncodingException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + encoding + "': using platform default");
}
value = fileItem.getString();
}
} else {
value = fileItem.getString();
}
String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
if (curParam == null) {
// simple form field
multipartParameters.put(fileItem.getFieldName(), new String[] { value });
} else {
// array of simple form fields
String[] newParam = StringUtils.addStringToArray(curParam, value);
multipartParameters.put(fileItem.getFieldName(), newParam);
}
} else {
// multipart file field
CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
multipartFiles.put(file.getName(), file);
if (logger.isDebugEnabled()) {
logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription());
}
}
}
return new MultipartParsingResult(multipartFiles, multipartParameters);
}Example 8
| Project: jdyna-master File: ImportConfigurazione.java View source code |
/** Performa l'import da file xml di configurazioni di oggetti;
* Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring
* e salvate su db.
*/
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws RuntimeException, IOException {
FileUploadConfiguration bean = (FileUploadConfiguration) object;
MultipartFile file = (CommonsMultipartFile) bean.getFile();
File a = null;
//creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti
a = File.createTempFile("jdyna", ".xml", new File(path));
file.transferTo(a);
ApplicationContext context = null;
try {
context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() }, getApplicationContext());
} catch (XmlBeanDefinitionStoreException exc) {
logger.warn("Errore nell'importazione della configurazione dal file: " + file.getOriginalFilename(), exc);
a.delete();
saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() }, request.getLocale()));
return new ModelAndView(getErrorView());
}
//cancello il file dalla directory temporanea
a.delete();
String[] tpDefinitions = context.getBeanNamesForType(tpClass);
//la variabile i conta le tipologie caricate con successo
int i = 0;
//la variabile j conta le tipologie non caricate
int j = 0;
for (String tpNameDefinition : tpDefinitions) {
try {
TP tipologiaDaImportare = (TP) context.getBean(tpNameDefinition);
applicationService.saveOrUpdate(tpClass, tipologiaDaImportare);
} catch (Exception ecc) {
saveMessage(request, getText("action.file.nosuccess.metadato.upload", new Object[] { ecc.getMessage() }, request.getLocale()));
j++;
i--;
}
i++;
}
String[] areeDefinitions = context.getBeanNamesForType(areaClass);
int w = 0;
int v = 0;
for (String areaNameDefinition : areeDefinitions) {
try {
A areaDaImportare = (A) context.getBean(areaNameDefinition);
applicationService.saveOrUpdate(areaClass, areaDaImportare);
} catch (Exception ecc) {
saveMessage(request, getText("action.file.nosuccess.metadato.upload", new Object[] { ecc.getMessage() }, request.getLocale()));
v++;
w--;
}
w++;
}
// check sulla tipologia poiche' ci sono oggetti che non hanno la tipologia tipo Opera e Parte
if (typeClass != null) {
String[] typeDefinitions = context.getBeanNamesForType(typeClass);
int r = 0;
int t = 0;
for (String typeDefinition : typeDefinitions) {
try {
TY tipologiaDaImportare = (TY) context.getBean(typeDefinition);
applicationService.saveOrUpdate(typeClass, tipologiaDaImportare);
} catch (Exception ecc) {
saveMessage(request, getText("action.file.nosuccess.metadato.upload", new Object[] { ecc.getMessage() }, request.getLocale()));
t++;
r--;
}
r++;
}
saveMessage(request, getText("action.file.success.upload.tipologie", new Object[] { new String("Totale Tipologie:" + (t + r) + " [" + r + "caricate con successo/" + t + " fallito caricamento]") }, request.getLocale()));
}
saveMessage(request, getText("action.file.success.upload", new Object[] { new String("Totale TP:" + (i + j) + "" + "[" + i + " caricate con successo/" + j + " fallito caricamento]"), new String("Totale Aree:" + (w + v) + " [" + w + "caricate con successo/" + v + " fallito caricamento]") }, request.getLocale()));
return new ModelAndView(getDetailsView());
}Example 9
| Project: niths-master File: FadderGroupControllerImpl.java View source code |
/**
* {@inheritDoc}
*/
@Override
@RequestMapping(value = "scan-qr-code/{studentId}", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK, reason = "Added to group")
public void scanImage(@PathVariable Long studentId, HttpServletRequest req, HttpServletResponse response) throws QRCodeException {
if (req instanceof MultipartHttpServletRequest) {
Map<String, MultipartFile> files = ((MultipartHttpServletRequest) req).getFileMap();
// Iterate over maps like a boss
for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
CommonsMultipartFile file = (CommonsMultipartFile) entry.getValue();
Long groupId = new QRCodeDecoder().decodeFadderGroupQRCode(file.getBytes());
// Add the student to the group,
// will throw exceptions if group/student does not exist
// or student is already added
service.addChild(groupId, studentId);
response.setHeader("group", groupId + "");
}
}
}Example 10
| Project: ame-master File: DynamoDbUserDaoImpl.java View source code |
/**
* Upload the profile pic to S3 and return it's URL
* @param profilePic
* @return The fully-qualified URL of the photo in S3
* @throws IOException
*/
public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException {
// Profile pic prefix
String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX);
// Date string
String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date());
String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_" + profilePic.getOriginalFilename();
// Get bucket
String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET);
// Create a ObjectMetadata instance to set the ACL, content type and length
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(profilePic.getContentType());
metadata.setContentLength(profilePic.getSize());
// Create a PutRequest to upload the image
PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata);
// Put the image into S3
s3Client.putObject(putObject);
s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead);
return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key;
}Example 11
| Project: amediamanager-master File: DynamoDbUserDaoImpl.java View source code |
/**
* Upload the profile pic to S3 and return it's URL
* @param profilePic
* @return The fully-qualified URL of the photo in S3
* @throws IOException
*/
public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException {
// Profile pic prefix
String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX);
// Date string
String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date());
String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_" + profilePic.getOriginalFilename();
// Get bucket
String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET);
// Create a ObjectMetadata instance to set the ACL, content type and length
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(profilePic.getContentType());
metadata.setContentLength(profilePic.getSize());
// Create a PutRequest to upload the image
PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata);
// Put the image into S3
s3Client.putObject(putObject);
s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead);
return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key;
}Example 12
| Project: hdiv-archive-master File: SpringMVCMultipartConfig.java View source code |
/**
* Adds a file parameter to the set of file parameters for this request and
* also to the list of all parameters.
*
* @param request
* The request in which the parameter was specified.
* @param item
* The file item for the parameter to add.
*/
public void addFileParameter(RequestWrapper request, FileItem item) {
CommonsMultipartFile file = new CommonsMultipartFile(item);
if (request.getFileElements().put(file.getName(), file) != null) {
throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver");
}
if (log.isDebugEnabled()) {
log.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription());
}
}Example 13
| Project: helium-master File: TascaTramitacioController.java View source code |
@RequestMapping(value = "/{tascaId}/document/{documentCodi}/adjuntar", method = RequestMethod.POST)
public String documentAdjuntar(HttpServletRequest request, @PathVariable String tascaId, @PathVariable String documentCodi, @RequestParam(value = "arxiu", required = false) final CommonsMultipartFile arxiu, @RequestParam(value = "data", required = false) Date data, Model model) {
try {
byte[] contingutArxiu = IOUtils.toByteArray(arxiu.getInputStream());
String nomArxiu = arxiu.getOriginalFilename();
ExpedientTascaDto tasca = tascaService.findAmbIdPerTramitacio(tascaId);
if (!tasca.isValidada()) {
MissatgesHelper.error(request, getMessage(request, "error.validar.dades"));
} else if (!expedientService.isExtensioDocumentPermesa(nomArxiu)) {
MissatgesHelper.error(request, getMessage(request, "error.extensio.document"));
} else if (nomArxiu.isEmpty() || contingutArxiu.length == 0) {
MissatgesHelper.error(request, getMessage(request, "error.especificar.document"));
} else {
accioDocumentAdjuntar(request, tascaId, documentCodi, nomArxiu, contingutArxiu, (data == null) ? new Date() : data).toString();
}
} catch (Exception ex) {
MissatgesHelper.error(request, getMessage(request, "error.guardar.document") + ": " + ex.getLocalizedMessage());
logger.error("Error al adjuntar el document a la tasca(" + "tascaId=" + tascaId + ", " + "documentCodi=" + documentCodi + ")", ex);
}
return mostrarInformacioTascaPerPipelles(request, tascaId, model, "document");
}Example 14
| Project: molgenis-master File: ImportWizardControllerTest.java View source code |
@Test
public void testImportFile() throws IOException, URISyntaxException {
// set up the test
HttpServletRequest request = mock(HttpServletRequest.class);
File file = new File("/src/test/resources/example.xlsx");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(), file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
ArgumentCaptor<InputStream> streamCaptor = ArgumentCaptor.forClass(InputStream.class);
when(fileStore.store(streamCaptor.capture(), eq("example.xlsx"))).thenReturn(file);
when(fileRepositoryCollectionFactory.createFileRepositoryCollection(file)).thenReturn(repositoryCollection);
when(importServiceFactory.getImportService(file.getName())).thenReturn(importService);
ImportRun importRun = importRunFactory.create();
importRun.setStartDate(date);
importRun.setProgress(0);
importRun.setStatus(ImportStatus.RUNNING.toString());
importRun.setOwner("Harry");
importRun.setNotify(false);
when(importRunService.addImportRun(SecurityUtils.getCurrentUsername(), false)).thenReturn(importRun);
// the actual test
ResponseEntity<String> response = controller.importFile(request, multipartFile, null, "add", null);
assertEquals(response.getStatusCode(), HttpStatus.CREATED);
ArgumentCaptor<ImportJob> captor = ArgumentCaptor.forClass(ImportJob.class);
verify(executorService, times(1)).execute(captor.capture());
}Example 15
| Project: SOCIETIES-Platform-master File: ServiceControlController.java View source code |
@SuppressWarnings("unchecked")
@RequestMapping(value = "/servicecontrol.html", method = RequestMethod.POST)
public ModelAndView serviceControlPost(@Valid ServiceControlForm scForm, BindingResult result, Map model) {
String returnPage = "servicediscoveryresult";
if (result.hasErrors()) {
model.put("result", "service control form error");
return new ModelAndView("servicecontrol", model);
}
if (getSCService() == null) {
model.put("errormsg", "Service Control Service reference not available");
return new ModelAndView("error", model);
}
String node = scForm.getNode();
String method = scForm.getMethod();
String url = scForm.getUrl();
//Service service = scForm.getService();
String serviceUri = scForm.getService();
String endpoint = scForm.getEndpoint();
CommonsMultipartFile filePart = scForm.getFileData();
if (logger.isDebugEnabled()) {
logger.debug("node = " + node);
logger.debug("method=" + method);
logger.debug("url: " + url);
logger.debug("Service Id (encoded): " + serviceUri);
logger.debug("Endpoint: " + endpoint);
logger.debug("filePart: " + filePart);
if (filePart != null) {
logger.debug("filePart.getName: " + filePart.getName());
logger.debug("filePart.getOriginalFilename: " + filePart.getOriginalFilename());
logger.debug("filePart.getStorageDescription: " + filePart.getStorageDescription());
}
}
if (method.equalsIgnoreCase("NONE")) {
model.put("result", "No method selected");
model.put("scResult", "NOTHING");
return new ModelAndView("servicecontrolresult", model);
}
ServiceResourceIdentifier serviceId = null;
if (serviceUri != null && !serviceUri.equals("NONE"))
serviceId = ServiceModelUtils.getServiceId64Decode(serviceUri);
if (!method.equalsIgnoreCase("InstallService") && !endpoint.isEmpty() && (serviceUri.equals("REMOTE") || serviceUri.equals("NONE"))) {
if (logger.isDebugEnabled())
logger.debug("It's a remote service, so we need to check it: " + endpoint);
Future<List<Service>> asynchResult = null;
List<Service> services = new ArrayList<Service>();
int index = endpoint.indexOf('/');
String remoteJid = endpoint.substring(0, index);
if (logger.isDebugEnabled())
logger.debug("Remote JID is: " + remoteJid);
try {
asynchResult = this.getSDService().getServices(remoteJid);
services = asynchResult.get();
} catch (Exception e) {
logger.error("exception getting services from remote node: " + e.getMessage());
e.printStackTrace();
}
for (Service remoteService : services) {
if (logger.isDebugEnabled())
logger.debug("Remote service: " + remoteService.getServiceName());
if (remoteService.getServiceEndpoint().equals(endpoint)) {
if (logger.isDebugEnabled())
logger.debug("Found the correct service: " + remoteService.getServiceEndpoint());
serviceId = remoteService.getServiceIdentifier();
break;
}
}
}
Future<ServiceControlResult> asynchResult = null;
ServiceControlResult scresult;
String res = "";
try {
model.put("myNode", getCommManager().getIdManager().getThisNetworkNode().getJid());
if (method.equalsIgnoreCase("InstallService")) {
if (filePart != null && !filePart.isEmpty()) {
InputStream is = filePart.getFileItem().getInputStream();
String originalFileName = filePart.getOriginalFilename();
File tmpFile = new File("3p-services/server/" + originalFileName);
File directory = tmpFile.getParentFile();
if (!directory.isDirectory()) {
if (logger.isDebugEnabled())
logger.debug("folder " + directory + " doesn't exist yet, creating it...");
directory.mkdirs();
}
FileOutputStream os = new FileOutputStream(tmpFile);
// Read in the bytes and write on the fly
int numRead = 0;
byte[] bytes = new byte[1024 * 1024];
while ((bytes.length > 0) && (numRead = is.read(bytes, 0, bytes.length)) >= 0) {
os.write(bytes, 0, numRead);
}
// Close input and output streams
is.close();
os.close();
URL serviceUrl = tmpFile.toURI().toURL();
if (logger.isDebugEnabled())
logger.debug("InstallService Remote Method on: " + serviceUrl + " on node " + node);
asynchResult = this.getSCService().installService(serviceUrl);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
/*
if(node != null && !node.isEmpty())
res="ServiceControl Result for Node : [" + node + "]: " + scresult.getMessage();
else
res="ServiceControl Result Installing in Local Node: " + scresult.getMessage();
*/
model.put("serviceResult", scresult.getMessage());
if (scresult.getMessage().equals(ResultMessage.SUCCESS)) {
res = "My Services: ";
returnPage = "servicediscoveryresult";
} else {
res = "Problem installing service!";
returnPage = "servicecontrolresult";
if (tmpFile.exists())
if (!tmpFile.delete())
tmpFile.deleteOnExit();
}
} else {
res = "Couldn't upload file!";
returnPage = "servicecontrolresult";
}
} else if (method.equalsIgnoreCase("InstallServiceRemote")) {
URL serviceUrl = new URL(url);
if (logger.isDebugEnabled())
logger.debug("InstallService Remote Method on:" + serviceUrl + " on node " + node);
asynchResult = this.getSCService().installService(serviceUrl, node);
res = "ServiceControl Result for Node : [" + node + "]";
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
model.put("serviceResult", scresult.getMessage());
} else if (method.equalsIgnoreCase("StartService")) {
if (logger.isDebugEnabled())
logger.debug("StartService:" + serviceId);
asynchResult = this.getSCService().startService(serviceId);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
model.put("serviceResult", scresult.getMessage());
Future<Service> asyncService = getSDService().getService(serviceId);
Service myService = asyncService.get();
res = "Started service: " + myService.getServiceName();
returnPage = "servicediscoveryresult";
} else if (method.equalsIgnoreCase("UnshareService")) {
if (logger.isDebugEnabled())
logger.debug("UnshareService:" + serviceId);
//GENERATE SERVICE OBJECT
Future<Service> asyncService = this.getSDService().getService(serviceId);
Service serviceToShare = asyncService.get();
//SHARE SERVICE
asynchResult = this.getSCService().unshareService(serviceToShare, node);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
//GET REMOTE SERVICES
Future<List<Service>> asynchServices = this.getSDService().getServices(node);
List<Service> cisServices = asynchServices.get();
if (logger.isDebugEnabled())
logger.debug("CIS has " + cisServices.size() + " services shared.");
model.put("cisservices", cisServices);
//Get CIS Name
ICis cis = this.getCisManager().getCis(node);
model.put("cis", cis);
//scresult.getMessage().toString();
res = "My Services to Share: ";
returnPage = "servicediscoveryresult";
} else if (method.equalsIgnoreCase("StopService")) {
if (logger.isDebugEnabled())
logger.debug("StopService:" + serviceId);
asynchResult = this.getSCService().stopService(serviceId);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
model.put("serviceResult", scresult.getMessage());
Future<Service> asyncService = getSDService().getService(serviceId);
Service myService = asyncService.get();
res = "Stopped service: " + myService.getServiceName();
returnPage = "servicediscoveryresult";
} else if (method.equalsIgnoreCase("UninstallService")) {
if (logger.isDebugEnabled())
logger.debug("UninstallService:" + serviceId);
Future<Service> asyncService = getSDService().getService(serviceId);
Service myService = asyncService.get();
asynchResult = this.getSCService().uninstallService(serviceId);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
model.put("serviceResult", scresult.getMessage());
if (scresult.getMessage().equals(ResultMessage.SUCCESS))
res = "Uninstalled service: " + myService.getServiceName();
else
res = "My Services: ";
returnPage = "servicediscoveryresult";
//>>>>>>>>>>>> SHARE SERVICE <<<<<<<<<<<<<<<
} else if (method.equalsIgnoreCase("ShareService")) {
if (logger.isDebugEnabled())
logger.debug("ShareService:" + serviceId);
//GENERATE SERVICE OBJECT
Future<Service> asyncService = this.getSDService().getService(serviceId);
Service serviceToShare = asyncService.get();
//SHARE SERVICE
asynchResult = this.getSCService().shareService(serviceToShare, node);
scresult = asynchResult.get();
if (logger.isDebugEnabled())
logger.debug("Result of operation was " + scresult.getMessage());
//GET REMOTE SERVICES
Future<List<Service>> asynchServices = this.getSDService().getServices(node);
List<Service> cisServices = asynchServices.get();
if (logger.isDebugEnabled())
logger.debug("CIS has " + cisServices.size() + " services shared.");
model.put("cisservices", cisServices);
//Get CIS Name
ICis cis = this.getCisManager().getCis(node);
model.put("cis", cis);
//scresult.getMessage().toString();
res = "My Services to Share: ";
returnPage = "servicediscoveryresult";
} else if (method.equalsIgnoreCase("Install3PService")) {
if (logger.isDebugEnabled())
logger.debug("Install3PService:" + serviceId);
//GENERATE SERVICE OBJECT
Future<Service> asyncService = this.getSDService().getService(serviceId);
Service serviceToInstall = asyncService.get();
//SHARE SERVICE
asynchResult = this.getSCService().installService(serviceToInstall);
if (logger.isDebugEnabled())
logger.debug("Called it, now should continue!");
//scresult = asynchResult.get();
//if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage());
/*
//GET REMOTE SERVICES
Future<List<Service>> asynchServices = this.getSDService().getServices(node);
List<Service> cisServices = asynchServices.get();
model.put("cisservices", cisServices);
*/
//res = scresult.getMessage().toString();
res = "Waiting...";
returnPage = "servicecontrolresult";
} else {
res = "error unknown method";
}
if (returnPage.equals("servicediscoveryresult")) {
Future<List<Service>> asynchServices = this.getSDService().getLocalServices();
List<Service> services = asynchServices.get();
model.put("services", services);
}
} catch (ServiceControlException e) {
e.printStackTrace();
res = "Oops!!!! Service Control Exception <br/>" + e.getMessage();
returnPage = "servicecontrolresult";
} catch (Exception ex) {
ex.printStackTrace();
res = "Oops!!!! " + ex.getMessage() + " <br/>";
returnPage = "servicecontrolresult";
}
;
model.put("result", res);
return new ModelAndView(returnPage, model);
}Example 16
| Project: podcastpedia-master File: UploadFileForm.java View source code |
public CommonsMultipartFile getFileData() {
return fileData;
}Example 17
| Project: spring-social-flickr-master File: UploadItem.java View source code |
public CommonsMultipartFile getFileData() {
return fileData;
}Example 18
| Project: summerb-master File: ArticleAttachmentVm.java View source code |
public CommonsMultipartFile getFile() {
return file;
}Example 19
| Project: Distributed-Speaker-Diarization-System-master File: WhoWhenRequestForm.java View source code |
public CommonsMultipartFile getFile() {
return file;
}Example 20
| Project: mateo-master File: UploadFileForm.java View source code |
/**
* @return the file
*/
public CommonsMultipartFile getFile() {
return file;
}Example 21
| Project: odo-master File: Upload.java View source code |
public CommonsMultipartFile getFileData() {
return this.fileData;
}Example 22
| Project: hospitalcore-master File: UploadFile.java View source code |
public CommonsMultipartFile getDiagnosisFile() {
return diagnosisFile;
}Example 23
| Project: xDams-core-master File: UploadBean.java View source code |
public CommonsMultipartFile getFiledata() {
return filedata;
}