List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:org.owasp.dependencytrack.dao.LibraryVersionDaoImpl.java
public void uploadLicense(final int licenseid, final MultipartFile file, final String editlicensename) { Session session = getSession();/* w ww. ja v a2s .co m*/ InputStream licenseInputStream = null; try { Blob blob; final Query query; if (file.isEmpty()) { query = session.createQuery("update License set licensename=:lname where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.executeUpdate(); } else { licenseInputStream = file.getInputStream(); String licenceFileContent = new String(IOUtils.toCharArray(licenseInputStream)); blob = Hibernate.getLobCreator(session).createBlob(licenceFileContent.getBytes()); query = session.createQuery("update License set licensename=:lname," + "text=:blobfile," + "filename=:filename," + "contenttype=:contenttype " + "where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.setParameter("blobfile", blob); query.setParameter("filename", file.getOriginalFilename()); query.setParameter("contenttype", file.getContentType()); query.executeUpdate(); } } catch (IOException e) { LOGGER.error("An error occurred while uploading a license"); LOGGER.error(e.getMessage()); } finally { IOUtils.closeQuietly(licenseInputStream); } }
From source file:org.sakaiproject.evaluation.tool.settings.ConfigSettingsPropertiesFileParser.java
/** * @return "uploadSuccess" if the parsing was completed without issue. Otherwise, return "uploadFailure". *//* www. jav a 2 s . c o m*/ public String parse() { MultipartFile file = (MultipartFile) multipartMap.get("configFile"); HashMap<String, String> result = new HashMap<>(); /* We manually parse the properties file rather than using the java.util.Properties due to the keys having a ':' in * the string (':' is one of the three valid separator values in the Java properties file definition). */ BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(file.getInputStream())); while (reader.ready()) { String linein = reader.readLine(); String[] keyValuePair = linein.split("="); result.put(keyValuePair[0], keyValuePair[1]); } } catch (IOException ioe) { LOG.error("Error reading uploaded properties file for overwrite settings", ioe); return "uploadFailure"; } finally { IOUtils.closeQuietly(reader); } // Update the producer so it can show the results on the html template importConfigProducer.setUploadedConfigValues(result); // Update the handler so the settings can be saved if the user chooses to do so overwriteSettingHandler.setUploadedConfigValues(result); return "uploadSuccess"; }
From source file:org.sakaiproject.gradebook.gwt.server.ImportExportUtilityImpl.java
public Upload parseImportXLS(MultipartFile file, ImportSettings settings) throws InvalidInputException, FatalException, IOException { log.debug("parseImportXLS() called"); // Strip off extension String fileName = removeFileExenstion(file.getOriginalFilename().toLowerCase()); String realFileName = fileName; boolean isOriginalName; try {//from ww w. j av a 2 s . c om realFileName = getUniqueItemName(fileName, settings.getGradebookUid()); } catch (GradebookImportException e) { return emptyUploadFileWithNotes(e.getMessage()); } isOriginalName = realFileName.equals(fileName); log.debug("realFileName=" + realFileName); log.debug("isOriginalName=" + isOriginalName); org.apache.poi.ss.usermodel.Workbook inspread = null; BufferedInputStream bufStream = new BufferedInputStream(file.getInputStream()); //inspread = readPoiSpreadsheet(tempfi); ///TODO: this is broken buonly called by the *Test class for this class and not by default if (inspread != null) { log.debug("Found a POI readable spreadsheet"); bufStream.close(); return handlePoiSpreadSheet(inspread, realFileName, isOriginalName, settings); } // else log.debug("POI couldn't handle the spreadsheet, using jexcelapi"); bufStream.reset(); return handleJExcelAPISpreadSheet(bufStream, realFileName, isOriginalName, settings); }
From source file:org.sakaiproject.gradebook.gwt.server.ImportExportUtilityImpl.java
public Upload getImportFile(MultipartFile file, ImportSettings importSettings) { Upload rv = null;//from w w w . j a v a 2 s. c o m boolean typeOK = true; final FileType type = FileType.valueOf(importSettings.getExportTypeName()); String errorMessage = ""; final String unexpectedTypeErrorMessage = i18n.getString("filetypeExtensionMismatch", "top.") + lookupI18nExportType(importSettings.getExportTypeName()); final String unexpectedFormatErrorMessage = i18n.getString("expectedFormat", "The file format did not match your selection: ") + lookupI18nFileFormat(importSettings.getFileFormatName()); String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')); String itemNameFromFile = removeFileExenstion(file.getOriginalFilename()); String newItemName = null; if (importSettings.getFileFormatName().equals(FileFormat.SCANTRON.name())) { try { newItemName = getUniqueItemName(itemNameFromFile, importSettings.getGradebookUid()); importSettings.setNameUniquenessCheckDone(true); } catch (GradebookImportException e) { return emptyUploadFileWithNotes(e.getMessage()); } } InputStream origFile = null; /* get the file and save it locally so we can abuse it */ File tempFile = null; String prefix = Thread.currentThread().hashCode() + "_"; try { origFile = file.getInputStream(); byte[] buf = new byte[1024]; tempFile = File.createTempFile(prefix, suffix); FileOutputStream fos = new FileOutputStream(tempFile, true); BufferedOutputStream bos = new BufferedOutputStream(fos); int cnt; while ((cnt = origFile.read(buf)) != -1) bos.write(buf, 0, cnt); bos.close(); tempFile.deleteOnExit(); } catch (Exception e1) { return emptyUploadFileWithNotes(e1.getMessage()); } // first level of problems would be from declared/detected type mismatch errorMessage = unexpectedTypeErrorMessage; org.apache.poi.ss.usermodel.Workbook wbPoi = null; jxl.Workbook wbJxl = null; try { if (FileType.XLSX.equals(type)) { String detected = null; try { detected = getMimeType(new FileInputStream(tempFile)); } catch (FileNotFoundException e1) { log.error("tempfile read failed: " + tempFile.getPath()); e1.printStackTrace(); typeOK = false; //I18N errorMessage = "File IO"; } typeOK = DETECTOR_OOXML_CONTAINER_MIMETYPE.equals(detected) //shallow detection || DETECTOR_OOXML_SPREADSHEET_MIME_TYPE.equals(detected); //deep detection wbPoi = readPoiSpreadsheet(tempFile); typeOK = typeOK && wbPoi != null; if (typeOK) { //proceed rv = handlePoiSpreadSheet(wbPoi, newItemName, itemNameFromFile.equalsIgnoreCase(newItemName), importSettings); } else { errorMessage = unexpectedTypeErrorMessage; } } if (FileType.XLS97.equals(type)) { /* * since POI is needed read newer xls files we need to make sure * that the detected mime type is compatible with XLS97 * (and not XLSX, for example)typeOk = getMimeType(bis) */ String detected = getMimeType(new FileInputStream(tempFile)); typeOK = DETECTOR_MS_OFFICE_GENERIC_MIMETYPE.equals(detected) || DETECTOR_MS_EXCEL_MIMETYPE.equals(detected); wbPoi = readPoiSpreadsheet(tempFile); typeOK = wbPoi != null; if (typeOK) { //proceed rv = handlePoiSpreadSheet(wbPoi, newItemName, itemNameFromFile.equalsIgnoreCase(newItemName), importSettings); } else { wbJxl = getJexcelWorkbook(new BufferedInputStream(new FileInputStream(tempFile))); typeOK = wbJxl != null; if (typeOK) { try { rv = handleJExcelAPISpreadSheet(file.getInputStream(), newItemName, itemNameFromFile.equalsIgnoreCase(newItemName), importSettings); } catch (InvalidInputException e) { typeOK = false; } catch (FatalException e) { log.error("cannot read Jexcel File: " + file.getOriginalFilename()); errorMessage = unexpectedTypeErrorMessage; } } else { errorMessage = unexpectedTypeErrorMessage; } } } if (FileType.CSV.equals(type) || FileType.TEMPLATE.equals(type)) { ImportExportDataFile rawData = new ImportExportDataFile(); String[] ent; String detected = getMimeType(new FileInputStream(tempFile)); if (!DETECTOR_CSV_MIMETYPE.equals(detected)) { typeOK = false; errorMessage = unexpectedTypeErrorMessage; } else { /// if there is an error after this is it a format error errorMessage = unexpectedFormatErrorMessage; InputStreamReader reader = new InputStreamReader(new FileInputStream(tempFile)); CSVReader csvReader = new CSVReader(reader); while ((ent = csvReader.readNext()) != null) { rawData.addRow(ent); } csvReader.close(); /* * If the above did not throw up * it does ##not necessarily mean## that * the file is a well formed CSV file */ /* * for now just check for headers and then, * if they are ok, then pass * the lot to the generic handler... */ if (FileFormat.SCANTRON.equals(FileFormat.valueOf(importSettings.getFileFormatName()))) { rawData.setScantronFile(true); if (!isScantronSheetCSV(rawData)) { typeOK = false; } else { /* now that the file format is validated * swap out the header for one based on the filename */ rawData.setAllRows(convertScantronRowsToTemplate(rawData.getAllRows(), newItemName)); rawData.setNewAssignment(itemNameFromFile.equalsIgnoreCase(newItemName)); } } else if (FileFormat.TEMPLATE.equals(FileFormat.valueOf(importSettings.getFileFormatName())) || FileFormat.CLICKER.equals(FileFormat.valueOf(importSettings.getFileFormatName()))) { if (!couldBeNewItemTemplate(rawData)) { typeOK = false; } else { rawData.setNewAssignment(true); } } else if (FileFormat.FULL.equals(FileFormat.valueOf(importSettings.getFileFormatName()))) { if (0 >= readDataForStructureInformation(rawData, buildRowIndicatorMap(), new HashMap<StructureRow, String[]>())) { typeOK = false; } } else if (FileFormat.NO_STRUCTURE .equals(FileFormat.valueOf(importSettings.getFileFormatName()))) { if (0 < readDataForStructureInformation(rawData, buildRowIndicatorMap(), new HashMap<StructureRow, String[]>())) { typeOK = false; } } } if (typeOK) { rawData.setImportSettings(importSettings); rv = parseImportGeneric(rawData); } } } catch (IOException e) { // file isn't CSV? errorMessage = i18n.getString("errorReadingFile", "The file could not be read."); log.error(e); typeOK = false; } if (!typeOK) { rv = emptyUploadFileWithNotes(errorMessage); } else { /// TODO: this scantron flag is being too overloaded methinks FileFormat format = null; try { format = FileFormat.valueOf(importSettings.getFileFormatName()); rv.getImportSettings().setScantron(format.equals(FileFormat.CLICKER) || format.equals(FileFormat.SCANTRON) || format.equals(FileFormat.TEMPLATE)); } catch (Exception e) { rv = emptyUploadFileWithNotes(unexpectedFormatErrorMessage); } } if (tempFile != null) tempFile.delete(); return rv; }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
private String uploadFile(String collectionId) { String name = null;//from w ww . jav a 2s.co m String mimeType = null; MultipartFile file = null; if (multipartMap.size() > 0) { // user specified a file, create it file = multipartMap.values().iterator().next(); } if (file != null) { // uploadsizeok would otherwise complain about 0 length file. For // this case it's valid. Means no file. if (file.getSize() == 0) return null; if (!uploadSizeOk(file)) return null; try { contentHostingService.checkCollection(collectionId); } catch (Exception ex) { try { ContentCollectionEdit edit = contentHostingService.addCollection(collectionId); edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, "LB-CSS"); contentHostingService.commitCollection(edit); } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.permissions-general")); return null; } } //String collectionId = getCollectionIdfalse); // user specified a file, create it name = file.getOriginalFilename(); if (name == null || name.length() == 0) name = file.getName(); int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String base = name; String extension = ""; i = name.lastIndexOf("."); if (i > 0) { base = name.substring(0, i); extension = name.substring(i + 1); } mimeType = file.getContentType(); try { ContentResourceEdit res = contentHostingService .addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(base), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); res.setContentType(mimeType); res.setContent(file.getInputStream()); try { contentHostingService.commitResource(res, NotificationService.NOTI_NONE); // there's a bug in the kernel that can cause // a null pointer if it can't determine the encoding // type. Since we want this code to work on old // systems, work around it. } catch (java.lang.NullPointerException e) { setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror")); } return res.getId(); } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return null; } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 1 " + e); return null; } } else { return null; } }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public void addMultimediaFile(MultipartFile file) { try {// ww w .j a v a 2 s .co m String name = null; String sakaiId = null; String mimeType = null; if (file != null) { if (!uploadSizeOk(file)) return; String collectionId = getCollectionId(false); // user specified a file, create it name = file.getOriginalFilename(); if (name == null || name.length() == 0) name = file.getName(); int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String base = name; String extension = ""; i = name.lastIndexOf("."); if (i > 0) { base = name.substring(0, i); extension = name.substring(i + 1); } mimeType = file.getContentType(); try { ContentResourceEdit res = null; if (itemId != -1 && replacefile) { // upload new version -- get existing file SimplePageItem item = findItem(itemId); String resId = item.getSakaiId(); res = contentHostingService.editResource(resId); } else { // otherwise create a new file res = contentHostingService.addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(base), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); } if (isCaption) res.setContentType("text/vtt"); else res.setContentType(mimeType); res.setContent(file.getInputStream()); try { contentHostingService.commitResource(res, NotificationService.NOTI_NONE); // there's a bug in the kernel that can cause // a null pointer if it can't determine the encoding // type. Since we want this code to work on old // systems, work around it. } catch (java.lang.NullPointerException e) { setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror")); } sakaiId = res.getId(); if (("application/zip".equals(mimeType) || "application/x-zip-compressed".equals(mimeType)) && isWebsite) { // We need to set the sakaiId to the resource id of the index file sakaiId = expandZippedResource(sakaiId); if (sakaiId == null) return; // We set this special type for the html field in the db. This allows us to // map an icon onto website links in applicationContext.xml mimeType = "LBWEBSITE"; } } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return; } catch (Exception e) { setErrMessage( messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 1 " + e); return; } ; } else if (mmUrl != null && !mmUrl.trim().equals("") && multimediaDisplayType != 1 && multimediaDisplayType != 3) { // user specified a URL, create the item String url = mmUrl.trim(); // if user gives a plain hostname, make it a URL. // ui add https if page is displayed with https. I'm reluctant to use protocol-relative // urls, because I don't know whether all the players understand it. if (!url.startsWith("http:") && !url.startsWith("https:") && !url.startsWith("/")) { String atom = url; int i = atom.indexOf("/"); if (i >= 0) atom = atom.substring(0, i); // first atom is hostname if (atom.indexOf(".") >= 0) { String server = ServerConfigurationService.getServerUrl(); if (server.startsWith("https:")) url = "https://" + url; else url = "http://" + url; } } name = url; String basename = url; // SAK-11816 method for creating resource ID String extension = ".url"; if (basename != null && basename.length() > 32) { // lose the http first if (basename.startsWith("http:")) { basename = basename.substring(7); } else if (basename.startsWith("https:")) { basename = basename.substring(8); } if (basename.length() > 32) { // max of 18 chars from the URL itself basename = basename.substring(0, 18); // add a timestamp to differentiate it (+14 chars) Format f = new SimpleDateFormat("yyyyMMddHHmmss"); basename += f.format(new Date()); // total new length of 32 chars } } String collectionId; SimplePage page = getCurrentPage(); collectionId = getCollectionId(true); try { // urls aren't something people normally think of as resources. Let's hide them ContentResourceEdit res = contentHostingService .addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(basename), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); res.setContentType("text/url"); res.setResourceType("org.sakaiproject.content.types.urlResource"); res.setContent(url.getBytes()); contentHostingService.commitResource(res, NotificationService.NOTI_NONE); sakaiId = res.getId(); } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return; } catch (Exception e) { setErrMessage( messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 2 " + e); return; } // connect to url and get mime type // new dialog passes the mime type if (multimediaMimeType != null && !"".equals(multimediaMimeType)) mimeType = multimediaMimeType; else mimeType = getTypeOfUrl(url); } else if (mmUrl != null && !mmUrl.trim().equals("") && (multimediaDisplayType == 1 || multimediaDisplayType == 3)) { // fall through. we have an embed code, don't need file } else // nothing to do return; // itemId tells us whether it's an existing item // isMultimedia tells us whether resource or multimedia // sameWindow is only passed for existing items of type HTML/XHTML // for new items it should be set true for HTML/XTML, false otherwise // for existing items it should be set to the passed value for HTML/XMTL, false otherwise // it is ignored for isMultimedia, as those are always displayed inline in the current page SimplePageItem item = null; if (itemId == -1 && isMultimedia) { item = appendItem(sakaiId, name, SimplePageItem.MULTIMEDIA); } else if (itemId == -1 && isWebsite) { String websiteName = name.substring(0, name.indexOf(".")); item = appendItem(sakaiId, websiteName, SimplePageItem.RESOURCE); } else if (itemId == -1) { item = appendItem(sakaiId, name, SimplePageItem.RESOURCE); } else if (isCaption) { item = findItem(itemId); if (item == null) return; item.setAttribute("captionfile", sakaiId); update(item); return; } else { item = findItem(itemId); if (item == null) return; // editing an existing item which might have customized properties // retrieve original resource and check for customizations ResourceHelper resHelp = new ResourceHelper(getContentResource(item.getSakaiId())); // if replacing file, keep existing name boolean hasCustomName = resHelp.isNameCustom(item.getName()) || replacefile; item.setSakaiId(sakaiId); if (!hasCustomName) { item.setName(name); } } // for new file, old captions don't make sense item.removeAttribute("captionfile"); // remember who added it, for permission checks item.setAttribute("addedby", getCurrentUserId()); item.setPrerequisite(this.prerequisite); if (mimeType != null) { item.setHtml(mimeType); } else { item.setHtml(null); } if (mmUrl != null && !mmUrl.trim().equals("") && isMultimedia) { if (multimediaDisplayType == 1) // the code is filtered by the UI, so the user can see the effect. // This protects against someone handcrafting a post. // The code is similar to that in submit, but currently doesn't // have folder-specific override (because there are no folders involved) item.setAttribute("multimediaEmbedCode", AjaxServer.filterHtml(mmUrl.trim())); else if (multimediaDisplayType == 3) item.setAttribute("multimediaUrl", mmUrl.trim()); item.setAttribute("multimediaDisplayType", Integer.toString(multimediaDisplayType)); } // if this is an existing item and a resource, leave it alone // otherwise initialize to false if (isMultimedia || itemId == -1) item.setSameWindow(false); clearImageSize(item); try { // if (itemId == -1) // saveItem(item); // else update(item); } catch (Exception e) { System.out.println("save error " + e); // saveItem and update produce the errors } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public void importCc() { if (!canEditPage()) return;//w w w. java 2 s.c om if (!checkCsrf()) return; // Import an uploaded file MultipartFile file = null; if (multipartMap.size() > 0) { // user specified a file, create it file = multipartMap.values().iterator().next(); } InputStream fis = null; if (file != null) { if (!uploadSizeOk(file)) return; try { fis = file.getInputStream(); } catch (IOException e) { setErrKey("simplepage.cc-error", ""); e.printStackTrace(); return; } long length = importCcFromStream(fis); setTopRefresh(); } }
From source file:org.sparkcommerce.cms.file.service.StaticAssetServiceImpl.java
@Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public StaticAsset createStaticAssetFromFile(MultipartFile file, Map<String, String> properties) { if (properties == null) { properties = new HashMap<String, String>(); }/*from w w w. ja v a 2 s . co m*/ String fullUrl = buildAssetURL(properties, file.getOriginalFilename()); StaticAsset newAsset = staticAssetDao.readStaticAssetByFullUrl(fullUrl); int count = 0; while (newAsset != null) { count++; //try the new format first, then the old newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, false)); if (newAsset == null) { newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, true)); } } if (count > 0) { fullUrl = getCountUrl(fullUrl, count, false); } try { ImageMetadata metadata = imageArtifactProcessor.getImageMetadata(file.getInputStream()); newAsset = new ImageStaticAssetImpl(); ((ImageStaticAsset) newAsset).setWidth(metadata.getWidth()); ((ImageStaticAsset) newAsset).setHeight(metadata.getHeight()); } catch (Exception e) { //must not be an image stream newAsset = new StaticAssetImpl(); } if (storeAssetsOnFileSystem) { newAsset.setStorageType(StorageType.FILESYSTEM); } else { newAsset.setStorageType(StorageType.DATABASE); } newAsset.setName(file.getOriginalFilename()); getMimeType(file, newAsset); newAsset.setFileExtension(getFileExtension(file.getOriginalFilename())); newAsset.setFileSize(file.getSize()); newAsset.setFullUrl(fullUrl); return staticAssetDao.addOrUpdateStaticAsset(newAsset, false); }
From source file:org.sparkcommerce.cms.file.service.StaticAssetServiceImpl.java
protected void getMimeType(MultipartFile file, StaticAsset newAsset) { Collection mimeTypes = MimeUtil.getMimeTypes(file.getOriginalFilename()); if (!mimeTypes.isEmpty()) { MimeType mimeType = (MimeType) mimeTypes.iterator().next(); newAsset.setMimeType(mimeType.toString()); } else {//w w w .j av a2 s . c om try { mimeTypes = MimeUtil.getMimeTypes(file.getInputStream()); } catch (IOException ioe) { throw new RuntimeException(ioe); } if (!mimeTypes.isEmpty()) { MimeType mimeType = (MimeType) mimeTypes.iterator().next(); newAsset.setMimeType(mimeType.toString()); } } }