/** * @see HttpServlet#doPost(javax.servlet.http.HttpServletRequest request, * javax.servlet.http.HttpServletResponse response) */ @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sImageID = ParseUtil.checkNull(request.getParameter("img")); if (!Utility.isNullOrEmpty(sImageID)) { UploadRequestBean uploadRequestBean = new UploadRequestBean(); uploadRequestBean.setUploadId(sImageID); UploadFile uploadFile = new UploadFile(); UploadResponseBean uploadResponseBean = uploadFile.getUploadFileInfo(uploadRequestBean); if (uploadResponseBean != null) {} } }
/** * 提取上传的文件和表单数据 * * @param inputStream HttpRequest流 * @param encoding 编码 * @throws IOException */ public void parseRequestStream(InputStream inputStream, String encoding) throws IOException { setLoaded(); MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream); input.readBoundary(); while (true) { UploadFileHeader header = input.readDataHeader(encoding); if (header == null) { break; } if (header.isFile == true) { // 文件类型的表单项 String fileName = header.fileName; if (fileName.length() > 0 && header.contentType.contains("application/x-macbinary")) { input.skipBytes(128); } UploadFile newFile = new UploadFile(header, setting); newFile.processStream(input); putFile(header.formFieldName, newFile); } else { // 标准表单项 ByteArrayOutputStream fbos = new ByteArrayOutputStream(1024); input.copy(fbos); String value = (encoding != null) ? new String(fbos.toByteArray(), encoding) : new String(fbos.toByteArray()); putParameter(header.formFieldName, value); } input.skipBytes(1); input.mark(1); // read byte, but may be end of stream int nextByte = input.read(); if (nextByte == -1 || nextByte == '-') { input.reset(); break; } input.reset(); } }
/** * Disables the data logger, closes the file and notifies the system that a new file is available * also sends the file to the cloud */ protected void disableLogging() { File f1 = null; if (mLoggingEnabled && (mDataLogger != null)) { try { f1 = mDataLogger.getFile(); // notify media scanner context.sendBroadcast( new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mDataLogger.getFile()))); // close logger mDataLogger.close(); Toast.makeText(context, "Logging Disabled", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(context, "Error disabling logging " + e.getMessage(), Toast.LENGTH_LONG) .show(); } } final File f2 = f1; String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) .getAbsolutePath(); MediaScannerConnection.scanFile(context, new String[] {dir + "/" + latestFilename}, null, null); Toast.makeText(context, "File written", Toast.LENGTH_SHORT).show(); // sends file to the cloud UploadFile toTheCloud = new UploadFile(context); toTheCloud.beginUpload(f2.getAbsolutePath()); // set disabled flag mLoggingEnabled = false; }
public static Task createUploadTask( ApiSession sess, String servicename, Path local, CommonPath remote, Struct storeParams, boolean allowResume) { UploadFile work = new UploadFile(); work.session = sess; return new Task() .withTitle("Upload file " + local) .withWork(work) .withSubContext() .withParams( new RecordStruct( new FieldStruct("LocalPath", local), new FieldStruct("RemotePath", remote), new FieldStruct("ServiceName", servicename), new FieldStruct("TransferParams", storeParams), new FieldStruct("ForceOverwrite", !allowResume))) .withTimeout(1) .withDeadline(0); }
private void processRequest(HttpServletRequest req, HttpServletResponse resp) { StringBuffer auditTrailSb = new StringBuffer(); auditTrailSb.append(StringPool.SPACE + req.getRemoteAddr()); auditTrailSb.append(" -- " + req.getMethod() + " -- "); Map<String, Object[]> params = Maps.newHashMap(); params.putAll(req.getParameterMap()); Map<String, String> cookies = cookiesToMap(req.getCookies()); String sessionKey = cookies.get(ApiConstants.SESSION_KEY); String reqStr = auditTrailSb.toString(); LOG.debug("===START=== " + reqStr); try { Object[] commandObj = params.get("command"); if (commandObj != null && StringUtils.isNotBlank((String) commandObj[0])) { String command = (String) commandObj[0]; if (ApiConstants.LOGOUT_COMMAND.equalsIgnoreCase(command)) { _apiServer.userLogout(sessionKey); auditTrailSb.append("command=" + ApiConstants.LOGOUT_COMMAND); auditTrailSb.append(StringPool.SPACE + HttpServletResponse.SC_OK); writeResponse(resp, getLogoutResponse(), HttpServletResponse.SC_OK); return; } else if (ApiConstants.LOGIN_COMMAND.equalsIgnoreCase(command)) { auditTrailSb.append("command=" + ApiConstants.LOGIN_COMMAND); String[] username = (String[]) params.get("username"); String[] password = (String[]) params.get("password"); if (username != null) { String pwd = ((password == null) ? null : password[0]); try { String loginSessionKey = _apiServer.userLogin(username[0], pwd); writeResponse( resp, "{\" " + ApiConstants.SESSION_KEY + " \":\"" + loginSessionKey + "\"}", 200); return; } catch (ApolloAuthenticationException e) { auditTrailSb.append(e.getMessage() != null ? e.getMessage() : "无法验证用户,检查用户名/密码是正确的"); String serializedResponse = getSerializedApiError( ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), e.getMessage() != null ? e.getMessage() : "无法验证用户,检查用户名/密码是正确的"); writeResponse(resp, serializedResponse, ApiErrorCode.ACCOUNT_ERROR.getHttpCode()); return; } } } } else { auditTrailSb.append(StringPool.SPACE + HttpServletResponse.SC_BAD_REQUEST + " command为空"); String serializedResponse = getSerializedApiError(HttpServletResponse.SC_BAD_REQUEST, "command为空"); writeResponse(resp, serializedResponse, HttpServletResponse.SC_BAD_REQUEST); return; } if (_apiServer.verifyUser(sessionKey)) { // 验证sessionKey是否为null if (StringUtils.isNotBlank(sessionKey)) { params.put(ApiConstants.SESSION_KEY, new String[] {sessionKey}); } if (_apiServer.verifyRequest(params)) { params.put(ApiConstants.HTTP_METHOD, new String[] {req.getMethod()}); String response; if (req.getContentType() != null && req.getContentType().toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) { // 包含文件 Map<String, String> fileMap = UploadFile.uploadFile(req, WORKPATH); response = _apiServer.handleFileRequest(params, auditTrailSb, fileMap); } else { response = _apiServer.handleRequest(params, auditTrailSb); } writeResponse(resp, response != null ? response : "", HttpServletResponse.SC_OK); } else { auditTrailSb.append( StringPool.SPACE + HttpServletResponse.SC_UNAUTHORIZED + " 无法验证用户凭证或没有命令执行权限"); String serializedResponse = getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "无法验证用户凭证或没有命令执行权限"); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED); } } else { auditTrailSb.append( StringPool.SPACE + HttpServletResponse.SC_UNAUTHORIZED + " sessionKey无效"); String serializedResponse = getSerializedApiError(HttpServletResponse.SC_UNAUTHORIZED, "sessionKey无效"); writeResponse(resp, serializedResponse, HttpServletResponse.SC_UNAUTHORIZED); } } catch (ApiException e) { String serializedResponseText = getSerializedApiError(e); resp.setHeader("X-Description", e.getMessage()); writeResponse(resp, serializedResponseText, e.getErrorCode().getHttpCode()); auditTrailSb.append(StringPool.SPACE + e.getErrorCode() + StringPool.SPACE + e.getMessage()); } catch (Exception e) { LOG.error("响应出现未知异常", e); auditTrailSb.append("响应出现未知异常"); } finally { ACCESS_LOG.info(auditTrailSb.toString()); LOG.debug("===END=== " + reqStr); } }
@Override @SuppressWarnings("unchecked") public final Map<String, Object> parse(final HttpServletRequest request) throws UWSException { LinkedHashMap<String, Object> parameters = new LinkedHashMap<String, Object>(); MultipartRequest multipart = null; try { // Parse the request body: multipart = new MultipartRequest( request, UWSFileManager.TMP_UPLOAD_DIR.getPath(), (SIZE_LIMIT < 0 ? DEFAULT_SIZE_LIMIT : SIZE_LIMIT), new FileRenamePolicy() { @Override public File rename(File file) { Object reqID = request.getAttribute(UWS.REQ_ATTRIBUTE_ID); if (reqID == null || !(reqID instanceof String)) reqID = (new Date()).getTime(); char uniq = 'A'; File f = new File( file.getParentFile(), "UPLOAD_" + reqID + uniq + "_" + file.getName()); while (f.exists()) { uniq++; f = new File(file.getParentFile(), "UPLOAD_" + reqID + "_" + file.getName()); } return f; } }); // Extract all "normal" parameters: String param; Enumeration<String> e = multipart.getParameterNames(); while (e.hasMoreElements()) { param = e.nextElement(); for (String occurence : multipart.getParameterValues(param)) consumeParameter(param, occurence, parameters); } // Extract all inline files as additional parameters: e = multipart.getFileNames(); if (!allowUpload && e.hasMoreElements()) throw new UWSException( UWSException.BAD_REQUEST, "Uploads are not allowed by this service!"); while (e.hasMoreElements()) { param = e.nextElement(); if (multipart.getFile(param) == null) continue; /* * TODO !!!POSSIBLE ISSUE!!! * MultipartRequest is not able to deal with multiple files having the same parameter name. However, all files are created/uploaded * but only the last one is accessible through this object....so only the last can be deleted, which could be a problem later * (hence the usage of the system temporary directory). */ // build its description/pointer: UploadFile lob = new UploadFile( param, multipart.getOriginalFileName(param), multipart.getFile(param).toURI().toString(), fileManager); lob.mimeType = multipart.getContentType(param); lob.length = multipart.getFile(param).length(); // add it inside the parameters map: consumeParameter(param, lob, parameters); } } catch (IOException ioe) { throw new UWSException( UWSException.INTERNAL_SERVER_ERROR, ioe, "Internal Error => Impossible to extract parameters from the Multipart HTTP request!"); } catch (IllegalArgumentException iae) { String confError = iae.getMessage(); if (UWSFileManager.TMP_UPLOAD_DIR == null) confError = "Missing upload directory!"; throw new UWSException( UWSException.INTERNAL_SERVER_ERROR, iae, "Internal Error: Incorrect UPLOAD configuration: " + confError); } return parameters; }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RespObjectProc responseObject = new RespObjectProc(); JSONObject jsonResponseObj = new JSONObject(); ArrayList<Text> arrOkText = new ArrayList<Text>(); ArrayList<Text> arrErrorText = new ArrayList<Text>(); RespConstants.Status responseStatus = RespConstants.Status.ERROR; try { if (!DataSecurityChecker.isInsecureInputResponse(request)) { UserBean loggedInUserBean = (UserBean) request.getSession().getAttribute(Constants.USER_LOGGED_IN_BEAN); if (loggedInUserBean != null && !Utility.isNullOrEmpty(loggedInUserBean.getUserId())) { String sUploadId = ParseUtil.checkNull(request.getParameter("upload_id")); if (!Utility.isNullOrEmpty(sUploadId)) { AccessUsers accessUser = new AccessUsers(); ParentTypeBean parentTypeBean = accessUser.getParentTypeBeanFromUser(loggedInUserBean); if (parentTypeBean != null && parentTypeBean.isUserAVendor()) { UploadRequestBean uploadRequestBean = new UploadRequestBean(); uploadRequestBean.setUploadId(sUploadId); UploadFile uploadFile = new UploadFile(); UploadResponseBean uploadResponseBean = uploadFile.getUploadFileInfo(uploadRequestBean); if (uploadResponseBean != null) { UploadBean uploadBean = uploadResponseBean.getUploadBean(); SharedFilesRequestBean sharedFilesRequestBean = new SharedFilesRequestBean(); sharedFilesRequestBean.setUploadId(sUploadId); AccessSharedFiles accessSharedFiles = new AccessSharedFiles(); SharedFilesBean sharedFilesBean = accessSharedFiles.getSharedFilesFromUploadId(sharedFilesRequestBean); if (sharedFilesBean != null) { sharedFilesRequestBean.setSharedFileId(sharedFilesBean.getSharedFilesId()); Folder folder = new Folder(); boolean isFileDeleted = folder.deleteS3File(uploadBean.getFilename(), uploadBean.getPath()); BuildSharedFiles buildSharedFiles = new BuildSharedFiles(); buildSharedFiles.deleteSharedFiles(sharedFilesRequestBean); jsonResponseObj.put("is_deleted", true); jsonResponseObj.put("deleted_upload_id", sUploadId); Text okText = new OkText("The file was deleted successfully", "status_mssg"); arrOkText.add(okText); responseStatus = RespConstants.Status.OK; } } else { Text errorText = new ErrorText("The file you are trying to delete does not exist.", "err_mssg"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } } else { Text errorText = new ErrorText( "You are not allowed to perform this action. Please contact your support representative.", "err_mssg"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } } else { Text errorText = new ErrorText( "We were unable to delete the file. Please select a valid file", "err_mssg"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } } else { appLogging.info( "Invalid request in Proc Page (loggedInUserBean)" + ParseUtil.checkNullObject(loggedInUserBean)); Text errorText = new ErrorText( "Oops!! We were unable to process your request at this time. Please try again later.(loadFileGroup - 002)", "err_mssg"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } } else { appLogging.info( "Insecure Parameters used in this Proc Page " + Utility.dumpRequestParameters(request).toString() + " --> " + this.getClass().getName()); Text errorText = new ErrorText( "Please use valid parameters. We have identified insecure parameters in your form.", "account_num"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } } catch (Exception e) { appLogging.info( "An exception occurred in the Proc Page " + ExceptionHandler.getStackTrace(e)); Text errorText = new ErrorText( "Oops!! We were unable to process your request at this time. Please try again later.(loadFileGroup - 001)", "err_mssg"); arrErrorText.add(errorText); responseStatus = RespConstants.Status.ERROR; } responseObject.setErrorMessages(arrErrorText); responseObject.setOkMessages(arrOkText); responseObject.setResponseStatus(responseStatus); responseObject.setJsonResponseObj(jsonResponseObj); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(responseObject.getJson().toString()); }