List of usage examples for java.net URLConnection getFileNameMap
public static FileNameMap getFileNameMap()
From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java
@Override public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException { // test to determine whether this is a file upload or not. Boolean isFileUpload = false; for (Object o : postParams.values()) { if (o instanceof File) { isFileUpload = true;// w w w. j a v a2s. co m break; } } if (isFileUpload) { try { HttpPost httpPost = new HttpPost(createUrl(url, getParams)); httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Object o : postParams.entrySet()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o; if (entry.getValue() instanceof File) { // For File parameters File file = (File) entry.getValue(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(file.toURL().toString()); entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type)); } else { // For usual String parameters entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT))); } } httpPost.setEntity(entity); return execute(httpPost); } catch (Exception e) { throw new HttpRequestException(e); } } else { return super.postData(url, getParams, postParams); } }
From source file:com.zimbra.cs.client.soap.LmcSendMsgRequest.java
public String postAttachment(String uploadURL, LmcSession session, File f, String domain, // cookie domain e.g. ".example.zimbra.com" int msTimeout) throws LmcSoapClientException, IOException { String aid = null;/*from w w w. ja va 2 s . c o m*/ // set the cookie. if (session == null) System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcSendMsgRequest.postAttachment session=null"); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); PostMethod post = new PostMethod(uploadURL); ZAuthToken zat = session.getAuthToken(); Map<String, String> cookieMap = zat.cookieMap(false); if (cookieMap != null) { HttpState initialState = new HttpState(); for (Map.Entry<String, String> ck : cookieMap.entrySet()) { Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false); initialState.addCookie(cookie); } client.setState(initialState); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } post.getParams().setSoTimeout(msTimeout); int statusCode = -1; try { String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName()); Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); statusCode = HttpClientUtil.executeMethod(client, post); // parse the response if (statusCode == 200) { // paw through the returned HTML and get the attachment id String response = post.getResponseBodyAsString(); //System.out.println("response is\n" + response); int lastQuote = response.lastIndexOf("'"); int firstQuote = response.indexOf("','") + 3; if (lastQuote == -1 || firstQuote == -1) throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response); aid = response.substring(firstQuote, lastQuote); } else { throw new LmcSoapClientException("Attachment post failed, status=" + statusCode); } } catch (IOException e) { System.err.println("Attachment post failed"); e.printStackTrace(); throw e; } finally { post.releaseConnection(); } return aid; }
From source file:org.yes.cart.service.vo.impl.VoIOSupportImpl.java
static String getMimeType(String fileName) { final FileNameMap mimeTypes = URLConnection.getFileNameMap(); final String contentType = mimeTypes.getContentTypeFor(fileName); // 2. nothing found -> lookup our in extension map to find types like ".doc" or ".docx" if (contentType == null) { final String extension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length()); ;/*ww w. j ava 2 s . c om*/ return EXT_MIMETYPE_MAP.get(extension); } return contentType; }
From source file:com.asto.move.util.qcloud.pic.VideoCloud.java
/** * Upload ?SliceUpload//from w ww .j av a 2 s. c o m * @param userid ?,0 * @param fileName ?? * @param title * @param desc ?? * @param magicContext ????url * @param result ? * @return ?0? */ public int Upload(String userid, String fileName, String title, String desc, String magicContext, UploadResult result) { String req_url = "http://" + QCLOUD_DOMAIN + "/" + m_appid + "/" + userid; String BOUNDARY = "---------------------------abcdefg1234567"; String rsp = ""; // create sign long expired = System.currentTimeMillis() / 1000 + 2592000; String sign = FileCloudSign.appSign(m_appid, m_secret_id, m_secret_key, expired); if (null == sign) { return SetError(-1, "create app sign failed"); } System.out.println("sign=" + sign); try { URL realUrl = new URL(req_url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setRequestMethod("POST"); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Host", "web.video.myqcloud.com"); connection.setRequestProperty("user-agent", "qcloud-java-sdk"); connection.setRequestProperty("Authorization", sign); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(connection.getOutputStream()); StringBuilder strBuf = new StringBuilder(); if (fileName != null) { File file = new File(fileName); String filename = file.getName(); String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"FileContent\"; filename=\"").append(fileName) .append("\"\r\n"); strBuf.append("Content-Type:").append(contentType).append("\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream ins = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = ins.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } } byte[] endData = ("\r\n--" + BOUNDARY + "\r\n").getBytes(); out.write(endData); byte[] arrTitle = ("Content-Disposition: form-data; name=\"Title\";\r\n\r\n" + title + "\r\n--" + BOUNDARY + "\r\n").getBytes(); out.write(arrTitle); byte[] arrDesc = ("Content-Disposition: form-data; name=\"Desc\";\r\n\r\n" + desc + "\r\n--" + BOUNDARY + "\r\n").getBytes(); out.write(arrDesc); byte[] arrMagicContext = ("Content-Disposition: form-data; name=\"magiccontext\";\r\n\r\n" + magicContext + "\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(arrMagicContext); out.flush(); out.close(); connection.connect(); rsp = GetResponse(connection); } catch (Exception e) { return SetError(-1, "url exception, e=" + e.toString()); } try { JSONObject jsonObject = new JSONObject(rsp); int code = jsonObject.getInt("code"); String msg = jsonObject.getString("message"); if (0 != code) { return SetError(code, msg); } result.url = jsonObject.getJSONObject("data").getString("url"); result.download_url = jsonObject.getJSONObject("data").getString("download_url"); result.fileid = jsonObject.getJSONObject("data").getString("fileid"); if (jsonObject.getJSONObject("data").has("cover_url")) result.cover_url = jsonObject.getJSONObject("data").getString("cover_url"); } catch (JSONException e) { return SetError(-1, "json exception, e=" + e.toString()); } return SetError(0, "success"); }
From source file:wicket.util.resource.UrlResourceStream.java
/** * Method to test the content type on null or unknown. if this is the case * the content type is tried to be resolved throw the servlet context *///from ww w.j av a 2 s .c o m private void testContentType() { if (contentType == null || contentType.indexOf("unknown") != -1) { Application application = Application.get(); if (application instanceof WebApplication) { // TODO Post 1.2: General: For non webapplication another method // should be implemented (getMimeType on application?) contentType = ((WebApplication) application).getServletContext().getMimeType(url.getFile()); if (contentType == null) { contentType = URLConnection.getFileNameMap().getContentTypeFor(url.getFile()); } } else { contentType = URLConnection.getFileNameMap().getContentTypeFor(url.getFile()); } } }
From source file:com.openmeap.admin.web.servlet.WebViewServlet.java
@SuppressWarnings("unchecked") @Override//from w w w . j ava2 s .c o m public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { logger.trace("in service"); ModelManager mgr = getModelManager(); GlobalSettings settings = mgr.getGlobalSettings(); String validTempPath = settings.validateTemporaryStoragePath(); if (validTempPath != null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath); } String pathInfo = request.getPathInfo(); String[] pathParts = pathInfo.split("[/]"); if (pathParts.length < 4) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3]; String fileRelative = pathInfo.replace(remove, ""); String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT); String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT); Application app = mgr.getModelService().findApplicationByName(applicationNameString); ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash, "MD5"); String authSalt = app.getProxyAuthSalt(); String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT); try { if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } } catch (DigestException e1) { throw new GenericRuntimeException(e1); } File fileFull = new File( arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative); try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString()); response.setContentType(mimeType); response.setContentLength(Long.valueOf(fileFull.length()).intValue()); InputStream inputStream = null; OutputStream outputStream = null; try { //response.setStatus(HttpServletResponse.SC_FOUND); inputStream = new FileInputStream(fileFull); outputStream = response.getOutputStream(); Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream); } finally { if (inputStream != null) { inputStream.close(); } response.getOutputStream().flush(); response.getOutputStream().close(); } } catch (FileNotFoundException e) { logger.error("Exception {}", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException ioe) { logger.error("Exception {}", ioe); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.ow2.proactive_grid_cloud_portal.cli.cmd.sched.SubmitJobCommand.java
private Boolean isValidFileMimeType(String pathname) { String contentType = URLConnection.getFileNameMap().getContentTypeFor(pathname); if (contentType != null) return (contentType.toLowerCase().equals("application/xml") || contentType.toLowerCase().equals("application/zip")); return false; }
From source file:edu.utah.bmi.ibiomes.parse.AbstractLocalFileImpl.java
/** * Get file MIME type//from w ww. jav a 2 s . c o m * @return MIME type */ public String getMimeType() { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(this.getAbsolutePath()); return mimeType; }
From source file:me.neatmonster.spacertk.actions.FileActions.java
/** * Gets information about a File//from www . j a v a 2 s.c o m * @param file File to get information about * @return Information about a file */ @Action(aliases = { "getFileInformations", "fileInformations", "informations" }) public TreeMap<String, Object> getFileInformations(final String file) { final TreeMap<String, Object> fileInformations = new TreeMap<String, Object>(); final File file_ = new File(file); if (file_.exists()) { fileInformations.put("Name", file_.getName()); fileInformations.put("Path", file_.getPath()); fileInformations.put("Size", file_.length()); fileInformations.put("Execute", file_.canExecute()); fileInformations.put("Read", file_.canRead()); fileInformations.put("Write", file_.canWrite()); fileInformations.put("IsDirectory", file_.isDirectory()); fileInformations.put("IsFile", file_.isFile()); fileInformations.put("IsHidden", file_.isHidden()); final FileNameMap fileNameMap = URLConnection.getFileNameMap(); fileInformations.put("Mime", fileNameMap.getContentTypeFor("file://" + file_.getPath())); return fileInformations; } return new TreeMap<String, Object>(); }
From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java
/** * Converts an inputstream into a FileVO. * @param file/*from w ww. ja v a2 s.com*/ * @param name * @param user * @return FileVO * @throws Exception */ private FileVO createPubFile(InputStream in, AccountUserVO user) throws Exception { this.logger.debug("Creating PubFile: " + this.getCurrentFile()); MdsFileVO mdSet = new MdsFileVO(); FileVO fileVO = new FileVO(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(this.getCurrentFile()); URL fileURL = this.uploadFile(in, mimeType, user.getHandle()); if (fileURL != null && !fileURL.toString().trim().equals("")) { fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED); fileVO.setVisibility(FileVO.Visibility.PUBLIC); fileVO.setDefaultMetadata(mdSet); fileVO.getDefaultMetadata().setTitle(new TextVO(this.getCurrentFile())); fileVO.setMimeType(mimeType); fileVO.setName(this.getCurrentFile()); fileVO.setContent(fileURL.toString()); System.out.println("SIZE:" + this.fileSize); fileVO.getDefaultMetadata().setSize(this.fileSize); 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 { Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); fileVO.getDefaultMetadata().setLicense(this.getConfig().get("License")); FormatVO formatVO = new FormatVO(); formatVO.setType("dcterms:IMT"); formatVO.setValue(mimeType); fileVO.getDefaultMetadata().getFormats().add(formatVO); } this.setCurrentFile(""); this.fileNames.remove(0); return fileVO; }