List of usage examples for java.net FileNameMap getContentTypeFor
public String getContentTypeFor(String fileName);
From source file:com.openerp.base.ir.Attachment.java
@SuppressWarnings("deprecation") private Notification setFileIntent(Uri uri) { Log.v(TAG, "setFileIntent()"); Intent intent = new Intent(Intent.ACTION_VIEW); FileNameMap mime = URLConnection.getFileNameMap(); String mimeType = mime.getContentTypeFor(uri.getPath()); intent.setDataAndType(uri, mimeType); mNotificationResultIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mNotificationBuilder.addAction(R.drawable.ic_oe_notification, "Download attachment", mNotificationResultIntent);// w w w . j a v a 2 s . c om mNotificationBuilder.setOngoing(false); mNotificationBuilder.setAutoCancel(true); mNotificationBuilder.setContentTitle("Attachment downloaded"); mNotificationBuilder.setContentText("Download Complete"); mNotificationBuilder.setProgress(0, 0, false); mNotification = mNotificationBuilder.build(); mNotification.setLatestEventInfo(mContext, "Attachment downloaded", "Download complete", mNotificationResultIntent); return mNotification; }
From source file:es.alvsanand.webpage.web.beans.admin.ImageBean.java
public void handleFileUpload(FileUploadEvent fileUploadEvent) { logger.info("Uploaded: {" + fileUploadEvent.getFile().getFileName() + "}"); FacesContext context = FacesContext.getCurrentInstance(); UIComponent fileUploadComponent = FacesUtils.findComponent(context.getViewRoot(), "fileUpload"); InputStream inputStream = null; try {/*from ww w. j a v a 2 s. c om*/ inputStream = fileUploadEvent.getFile().getInputstream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int length; while ((length = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, length); } inputStream.close(); photoData = outputStream.toByteArray(); outputStream.close(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); photoMediaType = fileNameMap.getContentTypeFor(fileUploadEvent.getFile().getFileName()); FacesMessage message = new FacesMessage(); message.setDetail(MessageResources.getMessage(MessageResources.ADMIN_RESOURCE_BUNDLE_NAME, "admin.uploadedFile.message.detail", null)); message.setSummary(MessageResources.getMessage(MessageResources.ADMIN_RESOURCE_BUNDLE_NAME, "admin.uploadedFile.message.summary", null)); message.setSeverity(FacesMessage.SEVERITY_INFO); FacesContext.getCurrentInstance().addMessage(null, message); } catch (IOException ioException) { FacesMessage message = new FacesMessage(); message.setDetail(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME, "error.form.validation.loadArticleBulkUpload.badFile.detail", null)); message.setSummary(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME, "error.form.validation.loadArticleBulkUpload.badFile.summary", null)); message.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(fileUploadComponent.getClientId(context), message); return; } catch (Exception exception) { logger.error("Error uploading file:", exception); return; } }
From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java
private OwncloudLocalResourceExtension createOwncloudResourceOf(Path path) { Path rootPath = getRootLocationOfAuthenticatedUser(); Path relativePath = rootPath.toAbsolutePath().relativize(path.toAbsolutePath()); URI href = URI.create(UriComponentsBuilder.fromPath("/").path(relativePath.toString()).toUriString()); String name = path.getFileName().toString(); MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; if (Files.isDirectory(path)) { href = URI.create(UriComponentsBuilder.fromUri(href).path("/").toUriString()); mediaType = OwncloudUtils.getDirectoryMediaType(); } else {/*from w w w . ja v a 2 s .c o m*/ FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentType = fileNameMap.getContentTypeFor(path.getFileName().toString()); if (StringUtils.isNotBlank(contentType)) { mediaType = MediaType.valueOf(contentType); } } try { LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(), ZoneId.systemDefault()); Optional<String> checksum = checksumService.getChecksum(path); if (Files.isSameFile(rootPath, path)) { name = "/"; checksum = Optional.empty(); } OwncloudLocalResourceExtension resource = OwncloudLocalResourceImpl.builder().href(href).name(name) .eTag(checksum.orElse(null)).mediaType(mediaType).lastModifiedAt(lastModifiedAt).build(); if (Files.isDirectory(path)) { return resource; } return OwncloudLocalFileResourceImpl.fileBuilder().owncloudResource(resource) .contentLength(Files.size(path)).build(); } catch (NoSuchFileException e) { throw new OwncloudResourceNotFoundException(href, getUsername()); } catch (IOException e) { val logMessage = String.format("Cannot create OwncloudResource from Path %s", path); log.error(logMessage, e); throw new OwncloudLocalResourceException(logMessage, e); } }
From source file:es.alvsanand.webpage.web.beans.session.RegistrationBean.java
public void handleFileUpload(FileUploadEvent fileUploadEvent) { logger.info("Uploaded: {" + fileUploadEvent.getFile().getFileName() + "}"); FacesContext context = FacesContext.getCurrentInstance(); UIComponent fileUploadComponent = FacesUtils.findComponent(context.getViewRoot(), "fileUpload"); InputStream inputStream = null; try {//from w w w .j a v a2 s. co m inputStream = fileUploadEvent.getFile().getInputstream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int length; while ((length = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, length); } inputStream.close(); photoData = outputStream.toByteArray(); outputStream.close(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); photoMediaType = fileNameMap.getContentTypeFor(fileUploadEvent.getFile().getFileName()); showFileUpload = false; } catch (IOException e1) { FacesMessage message = new FacesMessage(); message.setDetail(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME, "error.modifyPersonalData.fileUpload.detail", null)); message.setSummary(MessageResources.getMessage(MessageResources.ERROR_RESOURCE_BUNDLE_NAME, "error.modifyPersonalData.fileUpload.summary", null)); message.setSeverity(FacesMessage.SEVERITY_ERROR); FacesContext.getCurrentInstance().addMessage(fileUploadComponent.getClientId(context), message); showFileUpload = false; return; } }
From source file:no.met.jtimeseries.service.TimeSeriesService.java
/** * Create the Response object for serving a file. * @param f The file to serve//ww w .j a v a 2 s .c om * @return A Response object that will serve the file with the correct headers set. */ private Response serveFile(File f) { ContentDisposition cd = ContentDisposition.type("inline").fileName(f.getName()).build(); // TODO this way of getting the mime type could be slow. Should be // tested. FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mt = fileNameMap.getContentTypeFor(f.getAbsolutePath()); CacheControl cc = new CacheControl(); cc.setMustRevalidate(true); Map<String, String> cacheExtension = cc.getCacheExtension(); cacheExtension.put("post-check", "0"); cacheExtension.put("pre-check", "0"); // to be able to clean up the temporary files generated by the service // we read all the bytes in the file into memory and this might not be efficient enough. // TODO We need to look into this when we do performance testing. byte[] fileBytes = new byte[(int) f.length()]; try { new FileInputStream(f).read(fileBytes); } catch (FileNotFoundException e) { throw new WebApplicationException(e, 500); } catch (IOException e) { throw new WebApplicationException(e, 500); } f.delete(); String contentType = mt; return Response.ok(fileBytes, mt).header("Content-Disposition", cd).header("Content-Type", contentType) .cacheControl(cc).build(); }
From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java
/** * Converts a byte[] into a FileVO./*from ww w. j a v a 2 s. co m*/ * * @param file * @param name * @param user * @return FileVO * @throws Exception */ private FileVO convertToFileAndAdd(InputStream zipinputstream, String name, AccountUserVO user, ZipEntry zipEntry) throws Exception { MdsFileVO mdSet = new MdsFileVO(); FileVO fileVO = new FileVO(); // ByteArrayInputStream in = new ByteArrayInputStream(file); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(name); // Hack: FileNameMap class does not know tei, bibtex and endnote if (name.endsWith(".tei")) { mimeType = "application/xml"; } if (name.endsWith(".bib") || name.endsWith(".enl")) { mimeType = "text/plain"; } URL fileURL = this.uploadFile(zipinputstream, mimeType, user.getHandle(), zipEntry); if (fileURL != null && !fileURL.toString().trim().equals("")) { if (this.currentDeposit.getContentDisposition() != null && !this.currentDeposit.getContentDisposition().equals("")) { name = this.currentDeposit.getContentDisposition(); } fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED); fileVO.setVisibility(FileVO.Visibility.PUBLIC); fileVO.setDefaultMetadata(mdSet); fileVO.getDefaultMetadata().setTitle(name); fileVO.setMimeType(mimeType); fileVO.setName(name); FormatVO formatVO = new FormatVO(); formatVO.setType("dcterms:IMT"); formatVO.setValue(mimeType); fileVO.getDefaultMetadata().getFormats().add(formatVO); fileVO.setContent(fileURL.toString()); fileVO.getDefaultMetadata().setSize((int) zipEntry.getSize()); // This is the provided metadata file which we store as a component if (!name.endsWith(".pdf")) { String contentCategory = null; if (PubFileVOPresentation.getContentCategoryUri("SUPPLEMENTARY_MATERIAL") != null) { contentCategory = PubFileVOPresentation.getContentCategoryUri("SUPPLEMENTARY_MATERIAL"); } else { Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap(); if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) { contentCategory = contentCategoryMap.values().iterator().next(); } else { error("There is no content category available."); Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); } else { String contentCategory = null; if (PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION") != null) { contentCategory = PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION"); } else { Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap(); if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) { contentCategory = contentCategoryMap.values().iterator().next(); } else { error("There is no content category available."); Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); } // if escidoc item: check if it has already components with this filename. If true, use // existing file information. /* * if(this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) { for(FileVO * existingFile : itemVO.getFiles()) { if(existingFile.getName().replaceAll("/", * "_slsh_").equals(name)) { existingFile.setContent(fileURL.toString()); * existingFile.getDefaultMetadata().setSize(file.length); existing = true; * if(existingFile.getVisibility().equals(Visibility.PRIVATE)) { * existingFile.setVisibility(Visibility.AUDIENCE); } } } * * //If the file is the metadata file, do not add it for escidoc format * if(name.equals(depositXmlFileName)) { existing = true; } * * * } */ } /* * if(!existing) { itemVO.getFiles().add(fileVO); } */ return fileVO; }
From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java
/** * Converts a byte[] into a FileVO.//from ww w . ja va2s.c om * @param file * @param name * @param user * @return FileVO * @throws Exception */ private FileVO convertToFileAndAdd(InputStream zipinputstream, String name, AccountUserVO user, ZipEntry zipEntry) throws Exception { MdsFileVO mdSet = new MdsFileVO(); FileVO fileVO = new FileVO(); //ByteArrayInputStream in = new ByteArrayInputStream(file); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(name); //Hack: FileNameMap class does not know tei, bibtex and endnote if (name.endsWith(".tei")) { mimeType = "application/xml"; } if (name.endsWith(".bib") || name.endsWith(".enl")) { mimeType = "text/plain"; } URL fileURL = this.uploadFile(zipinputstream, mimeType, user.getHandle(), zipEntry); if (fileURL != null && !fileURL.toString().trim().equals("")) { if (this.currentDeposit.getContentDisposition() != null && !this.currentDeposit.getContentDisposition().equals("")) { name = this.currentDeposit.getContentDisposition(); } fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED); fileVO.setVisibility(FileVO.Visibility.PUBLIC); fileVO.setDefaultMetadata(mdSet); fileVO.getDefaultMetadata().setTitle(new TextVO(name)); fileVO.setMimeType(mimeType); fileVO.setName(name); FormatVO formatVO = new FormatVO(); formatVO.setType("dcterms:IMT"); formatVO.setValue(mimeType); fileVO.getDefaultMetadata().getFormats().add(formatVO); fileVO.setContent(fileURL.toString()); fileVO.getDefaultMetadata().setSize((int) zipEntry.getSize()); //This is the provided metadata file which we store as a component if (!name.endsWith(".pdf")) { String contentCategory = null; if (PubFileVOPresentation.getContentCategoryUri("SUPPLEMENTARY_MATERIAL") != null) { contentCategory = PubFileVOPresentation.getContentCategoryUri("SUPPLEMENTARY_MATERIAL"); } else { Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap(); if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) { contentCategory = contentCategoryMap.values().iterator().next(); } else { error("There is no content category available."); Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); } else { String contentCategory = null; if (PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION") != null) { contentCategory = PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION"); } else { Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap(); if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) { contentCategory = contentCategoryMap.values().iterator().next(); } else { error("There is no content category available."); Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); } //if escidoc item: check if it has already components with this filename. If true, use existing file information. /* if(this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) { for(FileVO existingFile : itemVO.getFiles()) { if(existingFile.getName().replaceAll("/", "_slsh_").equals(name)) { existingFile.setContent(fileURL.toString()); existingFile.getDefaultMetadata().setSize(file.length); existing = true; if(existingFile.getVisibility().equals(Visibility.PRIVATE)) { existingFile.setVisibility(Visibility.AUDIENCE); } } } //If the file is the metadata file, do not add it for escidoc format if(name.equals(depositXmlFileName)) { existing = true; } } */ } /* if(!existing) { itemVO.getFiles().add(fileVO); } */ return fileVO; }
From source file:com.fabernovel.alertevoirie.ReportDetailsActivity.java
public String getMimeType(String fileUrl) throws java.io.IOException { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileUrl); if (type == null) return "unknown"; return type;//from www . j a v a2 s . co m }
From source file:org.craftercms.cstudio.alfresco.service.impl.PersistenceManagerServiceImpl.java
protected DmContentItemTO createDmContentItem(String site, String fullPath, NodeRef nodeRef, Map<QName, Serializable> nodeProperties) { DmPathTO path = new DmPathTO(fullPath); String name = DefaultTypeConverter.INSTANCE.convert(String.class, nodeProperties.get(ContentModel.PROP_NAME)); String relativePath = path.getRelativePath(); ServicesConfig servicesConfig = getService(ServicesConfig.class); String timeZone = servicesConfig.getDefaultTimezone(site); DmContentItemTO item = new DmContentItemTO(); item.setTimezone(timeZone);/*from ww w .j a v a 2 s .c o m*/ item.setInternalName(name); item.setNodeRef(nodeRef.toString()); boolean isDisabled = false; Serializable value = nodeProperties.get(CStudioContentModel.PROP_DISABLED); if (value != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("isDisabled: " + value.toString()); } isDisabled = DefaultTypeConverter.INSTANCE.convert(Boolean.class, value); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("isDisabled property not found"); } } item.setDisabled(isDisabled); /** * Setting isNavigation property */ boolean placeInNav = false; Serializable placeInNavProp = nodeProperties.get(CStudioContentModel.PROP_PLACEINNAV); if (placeInNavProp != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("placeInNav: " + placeInNavProp.toString()); } placeInNav = DefaultTypeConverter.INSTANCE.convert(Boolean.class, placeInNavProp); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("placeInNav property not found"); } } item.setNavigation(placeInNav); item.setName(name); //Checks that the node is a folder, not if cont boolean isFolder = this.getFileInfo(nodeRef).isFolder(); item.setContainer(isFolder || fullPath.endsWith(DmConstants.INDEX_FILE)); if (isFolder) { item.setUri(relativePath); String folderPath = (name.equals(DmConstants.INDEX_FILE)) ? relativePath.replace("/" + name, "") : relativePath; item.setPath(folderPath); } else { item.setUri(relativePath); if (relativePath != null) { int index = path.getRelativePath().lastIndexOf("/"); if (index > 0) { item.setPath(relativePath.substring(0, index)); } } } item.setDefaultWebApp(path.getDmSitePath()); SimpleDateFormat sdf = new SimpleDateFormat(); try { Serializable strLastEditDate = nodeProperties.get(CStudioContentModel.PROP_WEB_LAST_EDIT_DATE); if (strLastEditDate != null && !StringUtils.isEmpty(strLastEditDate.toString())) { Date lastEditDate = sdf.parse(strLastEditDate.toString()); item.setLastEditDate(lastEditDate); } } catch (ParseException e) { // do nothing } // default event date is the modified date item.setEventDate( DefaultTypeConverter.INSTANCE.convert(Date.class, nodeProperties.get(ContentModel.PROP_MODIFIED))); // read the author information String modifier = DefaultTypeConverter.INSTANCE.convert(String.class, nodeProperties.get(CStudioContentModel.PROP_LAST_MODIFIED_BY)); if (modifier != null && !StringUtils.isEmpty(modifier.toString())) { item.setUser(modifier); ProfileService profileService = getService(ProfileService.class); UserProfileTO profile = profileService.getUserProfile(modifier, site, false); if (profile != null) { item.setUserFirstName(profile.getProfile().get(ContentModel.PROP_FIRSTNAME.getLocalName())); item.setUserLastName(profile.getProfile().get(ContentModel.PROP_LASTNAME.getLocalName())); } } // get the content type and form page info String contentType = DefaultTypeConverter.INSTANCE.convert(String.class, nodeProperties.get(CStudioContentModel.PROP_CONTENT_TYPE)); if (contentType != null && !StringUtils.isEmpty(contentType)) { item.setContentType(contentType); loadContentTypeProperties(site, item, contentType); } else { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(item.getUri()); if (mimeType != null && !StringUtils.isEmpty(mimeType)) { item.setPreviewable( DmUtils.matchesPattern(mimeType, servicesConfig.getPreviewableMimetypesPaterns(site))); } } item.setTimezone(servicesConfig.getDefaultTimezone(site)); return item; }
From source file:cx.fbn.nevernote.gui.BrowserWindow.java
public void handleUrls(QMimeData mime) { logger.log(logger.EXTREME, "Starting handleUrls"); FileNameMap fileNameMap = URLConnection.getFileNameMap(); List<QUrl> urlList = mime.urls(); String url = new String(); String script_start = new String("document.execCommand('createLink', false, '"); String script_end = new String("');"); for (int i = 0; i < urlList.size(); i++) { url = urlList.get(i).toString(); // Find out what type of file we have String mimeType = fileNameMap.getContentTypeFor(url); // If null returned, we need to guess at the file type if (mimeType == null) mimeType = "application/" + url.substring(url.lastIndexOf(".") + 1); // Check if we have an image or some other type of file if (url.substring(0, 5).equalsIgnoreCase("file:") && mimeType.substring(0, 5).equalsIgnoreCase("image")) { handleLocalImageURLPaste(mime, mimeType); return; }//from w w w .java2 s .c om boolean smallEnough = checkFileAttachmentSize(url); if (smallEnough && url.substring(0, 5).equalsIgnoreCase("file:") && !mimeType.substring(0, 5).equalsIgnoreCase("image")) { handleLocalAttachment(mime, mimeType); return; } browser.page().mainFrame().evaluateJavaScript(script_start + url + script_end); } return; }