List of usage examples for com.liferay.portal.kernel.util MimeTypesUtil getContentType
public static String getContentType(String fileName)
From source file:au.com.permeance.liferay.portlet.documentlibrary.action.DownloadFolderZipAction.java
License:Open Source License
protected void sendZipFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse, File zipFile, String zipFileName) throws Exception { FileInputStream zipFileInputStream = null; try {//from w ww.j a v a2 s.c o m if (StringUtils.isEmpty(zipFileName)) { zipFileName = FilenameUtils.getBaseName(zipFile.getName()); } String zipFileMimeType = MimeTypesUtil.getContentType(zipFileName); resourceResponse.setContentType(zipFileMimeType); int folderDownloadCacheMaxAge = DownloadFolderZipPropsValues.DL_FOLDER_DOWNLOAD_CACHE_MAX_AGE; if (folderDownloadCacheMaxAge > 0) { String cacheControlValue = "max-age=" + folderDownloadCacheMaxAge + ", must-revalidate"; resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, cacheControlValue); } String contentDispositionValue = "attachment; filename=\"" + zipFileName + "\""; resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue); // NOTE: java.io.File may return a length of 0 (zero) for a valid file // @see java.io.File#length() long zipFileLength = zipFile.length(); if ((zipFileLength > 0L) && (zipFileLength < (long) Integer.MAX_VALUE)) { resourceResponse.setContentLength((int) zipFileLength); } zipFileInputStream = new FileInputStream(zipFile); OutputStream responseOutputStream = resourceResponse.getPortletOutputStream(); long responseByteCount = IOUtils.copy(zipFileInputStream, responseOutputStream); responseOutputStream.flush(); responseOutputStream.close(); zipFileInputStream.close(); zipFileInputStream = null; if (s_log.isDebugEnabled()) { s_log.debug("sent " + responseByteCount + " byte(s) for ZIP file " + zipFileName); } } catch (Exception e) { String name = StringPool.BLANK; if (zipFile != null) { name = zipFile.getName(); } String msg = "Error sending ZIP file " + name + " : " + e.getMessage(); s_log.error(msg); throw new PortalException(msg, e); } finally { if (zipFileInputStream != null) { try { zipFileInputStream.close(); zipFileInputStream = null; } catch (Exception e) { String msg = "Error closing ZIP input stream : " + e.getMessage(); s_log.error(msg); } } } }
From source file:bean.ExportData.java
public void fileUploadByDL(String fileStr, String folderName, ThemeDisplay themeDisplay, RenderRequest renderRequest) {// w w w. j a v a 2 s.co m File file = new File(fileStr); long userId = themeDisplay.getUserId(); long groupId = themeDisplay.getScopeGroupId(); long repositoryId = themeDisplay.getScopeGroupId(); String mimeType = MimeTypesUtil.getContentType(file); String title = file.getName(); String description = "This file is added via programatically"; String changeLog = "Change log ver 1.0"; try { DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), 0, folderName); long fileEntryTypeId = dlFolder.getDefaultFileEntryTypeId(); LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance(); ServiceContext serviceContext = liferayFacesContext.getServiceContext(); InputStream is = new FileInputStream(file); Integer dlExist = (Integer) getCustomEntityManagerFactory().getLportalMemOrgEntityManagerFactory() .createEntityManager() .createQuery("" + "SELECT d " + "FROM Dlfileentry d " + "WHERE d.title = :title " + "AND d.folderid = :folderid") .setParameter("title", file.getName()).setParameter("folderid", dlFolder.getFolderId()) .getResultList().size(); if (dlExist < 1) { DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, repositoryId, dlFolder.getFolderId(), file.getName(), mimeType, title, description, changeLog, fileEntryTypeId, null, file, is, file.length(), serviceContext); AssetEntryLocalServiceUtil.updateEntry(userId, groupId, null, null, "com.liferay.portlet.documentlibrary.model.DLFileEntry", dlFileEntry.getFileEntryId(), dlFileEntry.getUuid(), 0, null, null, true, null, null, null, mimeType, title, description, null, null, null, 0, 0, 0, false); DLFileEntryLocalServiceUtil.updateFileEntry(userId, dlFileEntry.getFileEntryId(), file.getName(), mimeType, title, description, changeLog, true, dlFileEntry.getFileEntryTypeId(), null, file, null, file.length(), serviceContext); FacesContext facesContext = FacesContext.getCurrentInstance(); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "File exported successfully", "")); } else { FacesContext facesContext = FacesContext.getCurrentInstance(); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Filename already exists", "")); } } catch (PortalException | SystemException | FileNotFoundException e) { System.out.print("exportData().fileUploadByDL() " + e); } }
From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java
License:Open Source License
/** * Uploads the file into the destination folder * If the file does not exist, adds the file. If exists, updates the existing file * Adds tags and categories to documents * * @param file/*from w w w . j a va 2s. c om*/ * @param fileDescription * @param fileName * @param changeLog * @param serviceContext * @return FileEntry * @throws PortalException */ public FileEntry uploadFile(File file, String fileDescription, String fileName, String changeLog, ServiceContext serviceContext) throws PortalException { if (_log.isDebugEnabled()) { _log.debug("Invoking uploadFile...."); } long companyId = serviceContext.getCompanyId(); long groupId = serviceContext.getScopeGroupId(); long userId = serviceContext.getUserId(); // see https://issues.liferay.com/browse/LPS-66607 User user = userLocalService.getUser(userId); // Check permissions _fileUploadHelper.checkPermission(companyId, groupId, userId); String title = FilenameUtils.removeExtension(fileName); long folderId = GetterUtil.getLong(serviceContext.getAttribute(DESTINATION_FOLDER_ID)); fileName = file.getName(); String mimeType = MimeTypesUtil.getContentType(fileName); boolean majorVersion = true; DLFileEntry dlFileEntry = _dlFileEntryLocalService.fetchFileEntry(groupId, folderId, title); FileEntry fileEntry = null; if (Validator.isNull(dlFileEntry)) { fileEntry = addFileEntry(userId, groupId, folderId, fileName, mimeType, title, fileDescription, changeLog, file, serviceContext); } else { fileEntry = updateFileEntry(userId, dlFileEntry, fileName, mimeType, title, fileDescription, changeLog, majorVersion, file, serviceContext); } FileVersion fileVersion = fileEntry.getFileVersion(); long[] assetCategoryIds = _fileUploadHelper.getAssetCategoryIds(groupId, title, serviceContext); String[] assetTagNames = serviceContext.getAssetTagNames(); if (_log.isDebugEnabled()) { _log.debug(">>> Updating FileEntry with tags and categories"); } _dlAppLocalService.updateAsset(userId, fileEntry, fileVersion, assetCategoryIds, assetTagNames, null); // Post processing uploaded file _fileUploadHelper.postProcessUpload(file, fileEntry.getFileEntryId(), serviceContext); return fileEntry; }
From source file:com.custom.portal.verify.CustomVerifyDynamicDataMapping.java
License:Open Source License
protected FileEntry addFileEntry(long companyId, long userId, long groupId, long folderId, String fileName, String filePath, int status) throws Exception { String contentType = MimeTypesUtil.getContentType(fileName); String title = fileName;// w w w. j av a2 s . c o m int index = title.indexOf(CharPool.PERIOD); if (index > 0) { title = title.substring(0, index); } try { File file = DLStoreUtil.getFile(companyId, CompanyConstants.SYSTEM, filePath); ServiceContext serviceContext = createServiceContext(); FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(userId, groupId, folderId, fileName, contentType, title, StringPool.BLANK, StringPool.BLANK, file, serviceContext); updateFileEntryStatus(fileEntry, status, serviceContext); return fileEntry; } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn("Unable to add file entry " + fileName, e); } return null; } }
From source file:com.fmdp.webform.portlet.WebFormPortlet.java
License:Open Source License
public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); String portletId = PortalUtil.getPortletId(actionRequest); PortletPreferences preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletId); boolean requireCaptcha = GetterUtil.getBoolean(preferences.getValue("requireCaptcha", StringPool.BLANK)); String successURL = GetterUtil.getString(preferences.getValue("successURL", StringPool.BLANK)); boolean sendAsEmail = GetterUtil.getBoolean(preferences.getValue("sendAsEmail", StringPool.BLANK)); boolean sendThanksEmail = GetterUtil.getBoolean(preferences.getValue("sendThanksEmail", StringPool.BLANK)); boolean saveToDatabase = GetterUtil.getBoolean(preferences.getValue("saveToDatabase", StringPool.BLANK)); String databaseTableName = GetterUtil .getString(preferences.getValue("databaseTableName", StringPool.BLANK)); boolean saveToFile = GetterUtil.getBoolean(preferences.getValue("saveToFile", StringPool.BLANK)); boolean uploadToDisk = GetterUtil.getBoolean(preferences.getValue("uploadToDisk", StringPool.BLANK)); boolean uploadToDM = GetterUtil.getBoolean(preferences.getValue("uploadToDM", StringPool.BLANK)); long newFolderId = GetterUtil.getLong(preferences.getValue("newFolderId", StringPool.BLANK)); String fileName = GetterUtil.getString(preferences.getValue("fileName", StringPool.BLANK)); String uploadDiskDir = GetterUtil.getString(preferences.getValue("uploadDiskDir", StringPool.BLANK)); if (requireCaptcha) { try {/* w w w .ja v a 2 s . com*/ CaptchaUtil.check(actionRequest); } catch (CaptchaTextException cte) { SessionErrors.add(actionRequest, CaptchaTextException.class.getName()); return; } } UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); Map<String, String> fieldsMap = new LinkedHashMap<String, String>(); String fileAttachment = ""; for (int i = 1; true; i++) { String fieldLabel = preferences.getValue("fieldLabel" + i, StringPool.BLANK); String fieldType = preferences.getValue("fieldType" + i, StringPool.BLANK); if (Validator.isNull(fieldLabel)) { break; } if (StringUtil.equalsIgnoreCase(fieldType, "paragraph")) { continue; } if (StringUtil.equalsIgnoreCase(fieldType, "file")) { if (_log.isDebugEnabled()) { _log.debug("Field name for file: " + fieldLabel); } File file = uploadRequest.getFile("field" + i); String sourceFileName = uploadRequest.getFileName("field" + i); if (_log.isDebugEnabled()) { _log.debug("File attachment: " + sourceFileName); } JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); if (Validator.isNotNull(sourceFileName) && !"".equals(sourceFileName)) { if (uploadRequest.getSize("field" + i) == 0) { SessionErrors.add(actionRequest, "uploadToDiskError", "Uploaded file size is 0"); if (_log.isDebugEnabled()) { _log.debug("Uploaded file size is 0"); } return; } // List<String> uploadResults = new ArrayList<String>(); String uploadResult = ""; if (uploadToDisk) { uploadResult = uploadFile(file, sourceFileName, uploadDiskDir); if (uploadResult.equalsIgnoreCase("File Upload Error")) { SessionErrors.add(actionRequest, "uploadToDiskError", uploadResult); return; } fileAttachment = uploadDiskDir + File.separator + uploadResult; //uploadResults.add(uploadResult); jsonObject.put("fsOriginalName", sourceFileName); jsonObject.put("fsName", uploadResult); } if (uploadToDM) { uploadResult = ""; String contentType = MimeTypesUtil.getContentType(file); Folder folderName = DLAppLocalServiceUtil.getFolder(newFolderId); if (_log.isDebugEnabled()) { _log.debug("DM Folder: " + folderName.getName()); } InputStream inputStream = new FileInputStream(file); long repositoryId = folderName.getRepositoryId(); try { String selectedFileName = sourceFileName; while (true) { try { DLAppLocalServiceUtil.getFileEntry(themeDisplay.getScopeGroupId(), newFolderId, selectedFileName); StringBundler sb = new StringBundler(5); sb.append(FileUtil.stripExtension(selectedFileName)); sb.append(StringPool.DASH); sb.append(StringUtil.randomString()); sb.append(StringPool.PERIOD); sb.append(FileUtil.getExtension(selectedFileName)); selectedFileName = sb.toString(); } catch (Exception e) { break; } } FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(), repositoryId, newFolderId, selectedFileName, //file.getName(), contentType, selectedFileName, "", "", inputStream, file.length(), serviceContext); if (_log.isDebugEnabled()) { _log.debug("DM file uploade: " + fileEntry.getTitle()); } //Map<String, Serializable> workflowContext = new HashMap<String, Serializable>(); //workflowContext.put("event",DLSyncConstants.EVENT_UPDATE); //DLFileEntryLocalServiceUtil.updateStatus(themeDisplay.getUserId(), fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.STATUS_APPROVED, workflowContext, serviceContext); uploadResult = String.valueOf(fileEntry.getFileEntryId()); //uploadResults.add(uploadResult); String docUrl = themeDisplay.getPortalURL() + "/c/document_library/get_file?uuid=" + fileEntry.getUuid() + "&groupId=" + themeDisplay.getScopeGroupId(); jsonObject.put("fe", uploadResult); jsonObject.put("feOriginalName", sourceFileName); jsonObject.put("feName", fileEntry.getTitle()); jsonObject.put("feUrl", docUrl); } catch (PortalException pe) { SessionErrors.add(actionRequest, "uploadToDmError"); _log.error("The upload to DM failed", pe); return; } catch (Exception e) { _log.error("The upload to DM failed", e); return; } } jsonObject.put("Status", "With Attachment"); } else { jsonObject.put("Status", "No Attachment"); } fieldsMap.put(fieldLabel, jsonObject.toString()); } else { fieldsMap.put(fieldLabel, uploadRequest.getParameter("field" + i)); } } Set<String> validationErrors = null; try { validationErrors = validate(fieldsMap, preferences); } catch (Exception e) { SessionErrors.add(actionRequest, "validationScriptError", e.getMessage().trim()); return; } User currentUser = PortalUtil.getUser(actionRequest); String userEmail = ""; if (!Validator.isNull(currentUser)) { userEmail = currentUser.getEmailAddress(); if (_log.isDebugEnabled()) { _log.debug("User email for the form author: " + userEmail); } fieldsMap.put("email-from", userEmail); } else { fieldsMap.put("email-from", "guest"); } DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone(themeDisplay.getTimeZone().getID())); Date dateobj = new Date(); fieldsMap.put("email-sent-on", df.format(dateobj)); if (validationErrors.isEmpty()) { boolean emailSuccess = true; boolean databaseSuccess = true; boolean fileSuccess = true; boolean emailThanksSuccess = true; if (sendAsEmail) { emailSuccess = WebFormUtil.sendEmail(themeDisplay.getCompanyId(), fieldsMap, preferences, fileAttachment); } if (sendThanksEmail && !Validator.isNull(currentUser)) { emailThanksSuccess = WebFormUtil.sendThanksEmail(themeDisplay.getCompanyId(), fieldsMap, preferences, userEmail); } if (saveToDatabase) { if (Validator.isNull(databaseTableName)) { databaseTableName = WebFormUtil.getNewDatabaseTableName(portletId); preferences.setValue("databaseTableName", databaseTableName); preferences.store(); } databaseSuccess = saveDatabase(themeDisplay.getCompanyId(), fieldsMap, preferences, databaseTableName); } if (saveToFile) { fileSuccess = saveFile(fieldsMap, fileName); } if (emailSuccess && emailThanksSuccess && databaseSuccess && fileSuccess) { if (Validator.isNull(successURL)) { SessionMessages.add(actionRequest, "success"); } else { SessionMessages.add(actionRequest, portletId + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE); } } else { SessionErrors.add(actionRequest, "error"); } } else { for (String badField : validationErrors) { SessionErrors.add(actionRequest, "error" + badField); } } if (SessionErrors.isEmpty(actionRequest) && Validator.isNotNull(successURL)) { actionResponse.sendRedirect(successURL); } }
From source file:com.liferay.blogs.attachments.test.BaseBlogsEntryImageTestCase.java
License:Open Source License
protected FileEntry getFileEntry(long userId, String title, ServiceContext serviceContext) throws PortalException { Class<?> clazz = getClass(); ClassLoader classLoader = clazz.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("com/liferay/blogs/dependencies/test.jpg"); return PortletFileRepositoryUtil.addPortletFileEntry(serviceContext.getScopeGroupId(), userId, BlogsEntry.class.getName(), 0, StringUtil.randomString(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, inputStream, title, MimeTypesUtil.getContentType(title), false);/*from w ww. j a v a2 s .c o m*/ }
From source file:com.liferay.blogs.attachments.test.BaseBlogsEntryImageTestCase.java
License:Open Source License
protected FileEntry getTempFileEntry(long userId, String title, ServiceContext serviceContext) throws PortalException { Class<?> clazz = getClass(); ClassLoader classLoader = clazz.getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("com/liferay/blogs/dependencies/test.jpg"); return TempFileEntryUtil.addTempFileEntry(serviceContext.getScopeGroupId(), userId, BlogsEntry.class.getName(), title, inputStream, MimeTypesUtil.getContentType(title)); }
From source file:com.liferay.blogs.attachments.test.BlogsEntryImageSelectorHelperTest.java
License:Open Source License
@Test public void testGetImageSelectorWithDLImageFileEntry() throws Exception { InputStream inputStream = null; try {//from ww w . jav a 2s. com inputStream = getInputStream(); byte[] bytes = FileUtil.getBytes(inputStream); ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId()); FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(TestPropsValues.getUserId(), _group.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, _IMAGE_TITLE, MimeTypesUtil.getContentType(_IMAGE_TITLE), "image", StringPool.BLANK, StringPool.BLANK, bytes, serviceContext); BlogsEntryImageSelectorHelper blogsEntryImageSelectorHelper = new BlogsEntryImageSelectorHelper( fileEntry.getFileEntryId(), fileEntry.getFileEntryId() + 1, _IMAGE_CROP_REGION, StringPool.BLANK, StringPool.BLANK); ImageSelector imageSelector = blogsEntryImageSelectorHelper.getImageSelector(); Assert.assertArrayEquals(bytes, imageSelector.getImageBytes()); Assert.assertEquals(_IMAGE_TITLE, imageSelector.getImageTitle()); Assert.assertEquals(MimeTypesUtil.getContentType(_IMAGE_TITLE), imageSelector.getImageMimeType()); Assert.assertEquals(_IMAGE_CROP_REGION, imageSelector.getImageCropRegion()); Assert.assertEquals(StringPool.BLANK, imageSelector.getImageURL()); Assert.assertFalse(blogsEntryImageSelectorHelper.isFileEntryTempFile()); } finally { StreamUtil.cleanUp(inputStream); } }
From source file:com.liferay.blogs.attachments.test.BlogsEntryImageSelectorHelperTest.java
License:Open Source License
@Test public void testGetImageSelectorWithSameDLImageFileEntry() throws Exception { InputStream inputStream = null; try {//from ww w. j a va 2 s . co m inputStream = getInputStream(); byte[] bytes = FileUtil.getBytes(inputStream); ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(_group.getGroupId()); FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(TestPropsValues.getUserId(), _group.getGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, _IMAGE_TITLE, MimeTypesUtil.getContentType(_IMAGE_TITLE), "image", StringPool.BLANK, StringPool.BLANK, bytes, serviceContext); BlogsEntryImageSelectorHelper blogsEntryImageSelectorHelper = new BlogsEntryImageSelectorHelper( fileEntry.getFileEntryId(), fileEntry.getFileEntryId(), _IMAGE_CROP_REGION, StringPool.BLANK, StringPool.BLANK); Assert.assertNull(blogsEntryImageSelectorHelper.getImageSelector()); Assert.assertFalse(blogsEntryImageSelectorHelper.isFileEntryTempFile()); } finally { StreamUtil.cleanUp(inputStream); } }
From source file:com.liferay.blogs.attachments.test.BlogsEntryImageSelectorHelperTest.java
License:Open Source License
@Test public void testGetImageSelectorWithTempImageFileEntry() throws Exception { InputStream inputStream = null; try {/*ww w .jav a2 s . c om*/ inputStream = getInputStream(); byte[] bytes = FileUtil.getBytes(inputStream); FileEntry tempFileEntry = TempFileEntryUtil.addTempFileEntry(_group.getGroupId(), TestPropsValues.getUserId(), _TEMP_FOLDER_NAME, _IMAGE_TITLE, getInputStream(), ContentTypes.IMAGE_JPEG); BlogsEntryImageSelectorHelper blogsEntryImageSelectorHelper = new BlogsEntryImageSelectorHelper( tempFileEntry.getFileEntryId(), tempFileEntry.getFileEntryId() + 1, _IMAGE_CROP_REGION, StringPool.BLANK, StringPool.BLANK); ImageSelector imageSelector = blogsEntryImageSelectorHelper.getImageSelector(); Assert.assertArrayEquals(bytes, imageSelector.getImageBytes()); Assert.assertEquals(_IMAGE_TITLE, imageSelector.getImageTitle()); Assert.assertEquals(MimeTypesUtil.getContentType(_IMAGE_TITLE), imageSelector.getImageMimeType()); Assert.assertEquals(_IMAGE_CROP_REGION, imageSelector.getImageCropRegion()); Assert.assertEquals(StringPool.BLANK, imageSelector.getImageURL()); Assert.assertTrue(blogsEntryImageSelectorHelper.isFileEntryTempFile()); } finally { StreamUtil.cleanUp(inputStream); } }