List of usage examples for java.net URLConnection getFileNameMap
public static FileNameMap getFileNameMap()
From source file:no.met.jtimeseries.service.TimeSeriesService.java
/** * Create the Response object for serving a file. * @param f The file to serve/*from w w w. j a v a2 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: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 w ww . j a v a2 s . com*/ 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:org.dataconservancy.ui.it.FileHttpAPIIT.java
/** * Tests attempting getting a file that is no longer a part of a DataItem (DataItem). Expected return code 404 *///from w ww. j ava2 s. com @Test public void testGetFile_DeprecatedFile() throws Exception { logStart("testGetFile_DeprecatedFile"); // Get all the original stuff back HttpAssert.assertStatus(httpClient, adminUserLogin, 300, 399, "Unable to login as admin user!"); final String fileId = dataSetToUpdate.getFiles().get(0).getId(); HttpGet request = new HttpGet(fileId); HttpResponse response = httpClient.execute(request); assertEquals("Expected a 200 response code!", 200, response.getStatusLine().getStatusCode()); assertNotNull("Expected an ETAG code!", response.getFirstHeader(ETAG)); assertNotNull("Expected a content disposition header!", response.getFirstHeader(CONTENT_DISPOSITION)); assertTrue("Expected content disposition to contain the file name!", response.getFirstHeader(CONTENT_DISPOSITION).getValue().contains(dataFileToUpdate.getName())); assertNotNull("Expected a content type header!", response.getFirstHeader(CONTENT_TYPE)); assertEquals("Expected a content type header of " + dataFileToUpdate.getFormat() + "!", dataFileToUpdate.getFormat(), response.getFirstHeader(CONTENT_TYPE).getValue()); assertNotNull("Expected a last modified header!", response.getFirstHeader(LAST_MODIFIED)); // I would like to test for the contents of the last modified header thusly // assertEquals("Expected a last modified header of " + dataSetToUpdate.getDepositDate() + "!", // dataSetToUpdate.getDepositDate().toString(), response.getFirstHeader(LAST_MODIFIED).getValue()); assertEquals(dataFileToUpdateContents, IOUtils.toString(response.getEntity().getContent())); // Set up a new file and update the dataset // A generic data file java.io.File newTempFile = java.io.File.createTempFile("FileHttpAPIITUpdated", ".txt"); newTempFile.deleteOnExit(); PrintWriter out = new PrintWriter(newTempFile); updatedDataFileContents = "Can haz MOAR data?"; out.print(updatedDataFileContents); out.close(); updatedDataFile = new DataFile(null, newTempFile.getName(), newTempFile.toURI().toURL().toExternalForm(), URLConnection.getFileNameMap().getContentTypeFor(newTempFile.getName()), newTempFile.getPath(), newTempFile.getTotalSpace(), new ArrayList<String>()); // A list of data files List<DataFile> newDataFileList = new ArrayList<DataFile>(); newDataFileList.add(updatedDataFile); // A dataset to contain the data file DateTime newDataSetDateTime = DateTime.now(); updatedDataSet = new DataItem("FileToUpdateHttpAPIIT Test DataItem", "Test DataItem to update for TestHttpAPIIT", dataSetToUpdate.getId(), approvedUser.getId(), newDataSetDateTime, newDataFileList, new ArrayList<String>(), collection.getId()); org.dataconservancy.ui.model.Package updatedPackage = new org.dataconservancy.ui.model.Package(); updatedPackage.setId(reqFactory.createIdApiRequest(PACKAGE).execute(httpClient)); DepositRequest updateRequest = reqFactory.createSingleFileDataItemDepositRequest(updatedPackage, dataSetToUpdate, collection.getId(), newTempFile); updateRequest.setIsUpdate(true); httpClient.execute(updateRequest.asHttpPost()).getEntity().getContent().close(); assertNotNull(archiveSupport.pollAndQueryArchiveForDataItem(updatedDataSet.getId())); String content; tryCount = 0; do { final String packageId = updatedPackage.getId(); final URI depositStatusUri = urlConfig.getDepositStatusUrl(packageId).toURI(); final HttpGet depositStatusRequest = new HttpGet(depositStatusUri); response = httpClient.execute(depositStatusRequest); assertFalse(404 == response.getStatusLine().getStatusCode()); assertTrue(response.getStatusLine().getStatusCode() < 500); content = IOUtils.toString(response.getEntity().getContent()); Thread.sleep(1000L); } while (!content.contains("DEPOSITED") && tryCount++ < maxTries); // Check for the old file request = buildGetRequest(getIDPart(dataSetToUpdate.getFiles().get(0).getId()), false); response = httpClient.execute(request); assertEquals("Expected a 404 response code!", 404, response.getStatusLine().getStatusCode()); response.getEntity().getContent().close(); httpClient.execute(logout).getEntity().getContent().close(); }
From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java
/** * Replace <code>url(<<i>relative-path</i>>)</code> references in the * input CSS with//from w w w .j a v a 2 s . c o m * <code>url(data:<<i>mime-type</i>>;<<i>base64-encoded-data</i>></code> * ). The conversion is controlled by option settings as described in * {@link CSSModuleBuilder}. * * @param req * The request associated with the call. * @param css * The input CSS * @param res * The resource for the CSS file * @return The transformed CSS with images in-lined as determined by option * settings. */ protected String inlineImageUrls(HttpServletRequest req, String css, IResource res) { if (imageSizeThreshold == 0 && inlinedImageIncludeList.size() == 0) { // nothing to do return css; } // In-lining of imports can be disabled by request parameter for debugging if (!TypeUtil.asBoolean(req.getParameter(INLINEIMAGES_REQPARAM_NAME), true)) { return css; } StringBuffer buf = new StringBuffer(); Matcher m = urlPattern.matcher(css); while (m.find()) { String fullMatch = m.group(0); String urlMatch = m.group(1); // remove quotes. urlMatch = dequote(urlMatch); urlMatch = forwardSlashPattern.matcher(urlMatch).replaceAll("/"); //$NON-NLS-1$ // Don't do anything with non-relative URLs if (urlMatch.startsWith("/") || urlMatch.startsWith("#") || protocolPattern.matcher(urlMatch).find()) { //$NON-NLS-1$ //$NON-NLS-2$ m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } URI imageUri = res.resolve(urlMatch).getURI(); boolean exclude = false, include = false; // Determine if this image is in the include list for (Pattern regex : inlinedImageIncludeList) { if (regex.matcher(imageUri.getPath()).find()) { include = true; break; } } // Determine if this image is in the exclude list for (Pattern regex : inlinedImageExcludeList) { if (regex.matcher(imageUri.getPath()).find()) { exclude = true; break; } } // If there's an include list, then only the files in the include list // will be inlined if (inlinedImageIncludeList.size() > 0 && !include || exclude) { m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); continue; } boolean imageInlined = false; String type = URLConnection.getFileNameMap().getContentTypeFor(imageUri.getPath()); String extension = PathUtil.getExtension(imageUri.getPath()); if (type == null) { type = inlineableImageTypeMap.get(extension); } if (type == null) { type = "content/unknown"; //$NON-NLS-1$ } if (include || inlineableImageTypes.contains(type) || inlineableImageTypeMap.containsKey(extension)) { InputStream in = null; try { // In-line the image. URLConnection connection = imageUri.toURL().openConnection(); if (include || connection.getContentLength() <= imageSizeThreshold) { in = connection.getInputStream(); String base64 = getBase64(connection); m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append("url('data:" + type + //$NON-NLS-1$ ";base64," + base64 + "')"); //$NON-NLS-1$ //$NON-NLS-2$ imageInlined = true; } } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, MessageFormat.format(Messages.CSSModuleBuilder_0, new Object[] { imageUri }), ex); } } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } if (!imageInlined) { // Image not in-lined. Write the original URL m.appendReplacement(buf, ""); //$NON-NLS-1$ buf.append(fullMatch); } } m.appendTail(buf); return buf.toString(); }
From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java
/** * Converts a byte[] into a FileVO./* w w w . jav a 2 s .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(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 w w w .j av a 2s.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(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 w ww . java2 s. com*/ }
From source file:org.apache.ofbiz.base.util.UtilHttp.java
public static String getContentTypeByFileName(String fileName) { FileNameMap mime = URLConnection.getFileNameMap(); return mime.getContentTypeFor(fileName); }
From source file:cx.fbn.nevernote.gui.BrowserWindow.java
@SuppressWarnings("unused") private void todoClicked() { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String script_start = new String("document.execCommand('insertHtml', false, '"); String script_end = new String("');"); String todo = new String( "<input TYPE=\"CHECKBOX\" value=\"false\" " + "onMouseOver=\"style.cursor=\\'hand\\'\" " + "onClick=\"value=checked; window.jambi.contentChanged(); \" />"); browser.page().mainFrame().evaluateJavaScript(script_start + todo + script_end); browser.setFocus();//from ww w . j a va 2 s. com }
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; }// w ww .j ava2 s .c o m 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; }