获取文件或者目录的属性

@param request
文件或者目录的属性请求, 类型为StatFileRequest或者StatFolderRequest
@return JSON格式的字符串, 格式为{"code":$code, "message":"$mess"}, code为0表示成功,
其他为失败, message为success或者失败原因
@throws AbstractCosException
SDK定义的COS异常, 通常是输入参数有误或者环境问题(如网络不通)
346796
protected String statBase(final AbstractStatRequest request) throws AbstractCosException {
		request.check_param();

		String url = buildUrl(request);
		long signExpired = System.currentTimeMillis() / 1000 + this.config.getSignExpired();
		String sign = Sign.getPeriodEffectiveSign(request.getBucketName(),request.getCosPath(), this.cred, signExpired);

		HttpRequest httpRequest = new HttpRequest();
		httpRequest.setUrl(url);
		httpRequest.addHeader(RequestHeaderKey.Authorization, sign);
		httpRequest.addHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());
		httpRequest.addParam(RequestBodyKey.OP, RequestBodyValue.OP.STAT);
		httpRequest.setMethod(HttpMethod.GET);

		return httpClient.sendHttpRequest(httpRequest);
	}
870117
public RequestCtx makeRequestCtx(String request)
            throws MelcoeXacmlException {
        RequestCtx reqCtx = null;
        try {
            ByteArrayInputStream is =
                    new ByteArrayInputStream(request.getBytes());
            reqCtx = BasicRequestCtx.getInstance(is);
        } catch (ParsingException pe) {
            throw new MelcoeXacmlException("Error parsing response.", pe);
        }
        return reqCtx;
    }
432437
protected JSONObject requestServer(AipRequest request) {
        // 请求API
        AipResponse response = AipHttpClient.post(request);
        String resData = response.getBodyStr();
        Integer status = response.getStatus();
        if (status.equals(200) && !resData.equals("")) {
            try {
                JSONObject res =  new JSONObject(resData);
                if (state.getState().equals(EAuthState.STATE_POSSIBLE_CLOUD_USER)) {
                    boolean cloudAuthState = res.isNull("error_code")
                            || res.getInt("error_code") != AipClientConst.IAM_ERROR_CODE;
                    state.transfer(cloudAuthState);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("state after cloud auth: " + state.toString());
                    }
                    if (!cloudAuthState) {
                        return Util.getGeneralError(
                                AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
                                AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
                    }
                }
                return res;
            } catch (JSONException e) {
                return Util.getGeneralError(-1, resData);
            }
        }
        else {
            LOGGER.warn(String.format("call failed! response status: %d, data: %s", status, resData));
            return AipError.NET_TIMEOUT_ERROR.toJsonResult();

        }
    }
253297
private function requestToJson($request)
  {
    $jsonRequest = null;
    try {
      $jsonRequest = $this->serializer->serialize($request, 'json');
    } catch (RuntimeException $e) {
      throw new RuntimeException('Unable to serialize request ' . var_dump($request));
    }

    return $jsonRequest;
  }
728527
public static <T> String resolveResourcePath(Request<T> request) {
		infixPotentialPathDefaults(request, request.getClass());

		Class<?> clazz = request.getClass();

		String unresolvedPath = ClassUtil.getClassAnnotationValue(clazz, Path.class, "value", String.class);

		Map<String, String> patternMap = new HashMap<String, String>();
		for (Field field : clazz.getDeclaredFields()) {
			PathVariable part = field.getAnnotation(PathVariable.class);
			if (part != null) {
				try {
					String pattern = part.value();
					field.setAccessible(true);
					String value = (String) field.get(request);
					patternMap.put(pattern, value);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}

		Pattern pattern = Pattern.compile(PATTERN);
		Matcher matcher = pattern.matcher(unresolvedPath);

		LinkedHashSet<String> placeholder = new LinkedHashSet<String>();
		while (matcher.find()) {
			placeholder.add(matcher.group());
		}

		for (String key : placeholder) {
			String found = patternMap.get(key);
			if (found != null) {
				unresolvedPath = unresolvedPath.replace((String) key, found);
			}
		}

		if (unresolvedPath.endsWith("/")) {
			unresolvedPath = unresolvedPath.substring(0, unresolvedPath.length() - 1);
		}
		return unresolvedPath;
	}
630836
public function folder(Request $request)
    {
        $json = [];

        $validator = $this->validatorFolder($request->all())->fails();

        if ($validator) {
            $json['error'] = trans('admin::image.error.folder_alpha_num');
        }

        if (!$json) {
            $dir = '';
            if ($request->get('directory')) {
                $dir = $request->get('directory') . '/';
            }
            $dir .= $request->get('folder');
            $result = $this->storage->makeDirectory($dir);

            if ($result) {
                $json['success'] = trans('admin::image.success.folder');
            } else {
                $json['error'] = trans('admin::image.error.folder');
            }
        }

        return response()
            ->json($json);
    }
48661
public static void downloadAsync(ImageRequest request) {
        if (request == null) {
            return;
        }

        // NOTE: This is the ONLY place where the original request's Url is read. From here on,
        // we will keep track of the Url separately. This is because we might be dealing with a
        // redirect response and the Url might change. We can't create our own new ImageRequests
        // for these changed Urls since the caller might be doing some book-keeping with the request's
        // object reference. So we keep the old references and just map them to new urls in the downloader
        RequestKey key = new RequestKey(request.getImageUri(), request.getCallerTag());
        synchronized (pendingRequests) {
            DownloaderContext downloaderContext = pendingRequests.get(key);
            if (downloaderContext != null) {
                downloaderContext.request = request;
                downloaderContext.isCancelled = false;
                downloaderContext.workItem.moveToFront();
            } else {
                enqueueCacheRead(request, key, request.isCachedRedirectAllowed());
            }
        }
    }
801700
public CreateDocumentFromBosResponse createDocumentFromBos(CreateDocumentFromBosRequest request) {
        checkNotNull(request, "request should not be null.");
        checkNotNull(request.getBucket(), "bucket should not be null.");
        checkNotNull(request.getObject(), "object should not be null.");
        checkNotNull(request.getTitle(), "title should not be null.");
        checkNotNull(request.getFormat(), "format should not be null.");
        InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, DOC);
        internalRequest.addParameter("source", "bos");
        String strJson = JsonUtils.toJsonString(request);
        byte[] requestJson = null;
        try {
            requestJson = strJson.getBytes(DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new BceClientException("Unsupported encode.", e);
        }

        internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(requestJson.length));
        internalRequest.addHeader(Headers.CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
        internalRequest.setContent(RestartableInputStream.wrap(requestJson));
        return invokeHttpClient(internalRequest, CreateDocumentFromBosResponse.class);
    }
1105149
public String uploadFile(UploadFileRequest request) throws AbstractCosException {
		request.check_param();

		String localPath = request.getLocalPath();
		long fileSize = 0;
		try {
			fileSize = CommonFileUtils.getFileLength(localPath);
		} catch (Exception e) {
			throw new UnknownException(e.toString());
		}

		long suitSingleFileSize = 8 * 1024 * 1024;
		if (fileSize < suitSingleFileSize) {
			return uploadSingleFile(request);
		} else {
			UploadSliceFileRequest sliceRequest = new UploadSliceFileRequest(request);
			sliceRequest.setInsertOnly(request.getInsertOnly());
			return uploadSliceFile(sliceRequest);
		}
	}
954575
protected FileInfo getFileInfoFromRequestImpl(HTTPRequest request,Map<String,String> queryStringMap)
    {
        //get file name
        String name=queryStringMap.get("file");
        if(name==null)
        {
            throw new FaxException("File name not provided in query string.");
        }
        
        //get content
        byte[] content=null;
        ContentType contentType=request.getContentType();
        switch(contentType)
        {
            case BINARY:
                content=request.getContentAsBinary();
                break;
            case STRING:
                String contentString=request.getContentAsString();
                content=IOHelper.convertStringToBinary(contentString,null);
                break;
            default:
                throw new FaxException("Unsupported content type: "+contentType);
        }
        if((content==null)||(content.length==0))
        {
            throw new FaxException("File content not provided in request payload.");
        }
        
        //create file info
        FileInfo fileInfo=new FileInfo(name,content);
        
        return fileInfo;
    }
439263
public Object handle(Stru _cmd, HttpRequest request) throws Exception {
		try {
			Check.illegalargument.assertEquals(GET, request.getRequestLine().getMethod());
			Obj cmd = _cmd.asObj();
			@Nullable String path = cmd.getStr(CMD_PATH);
			String nameAndTx = cmd.getStrictStr(CMD_NAME);
			String ext = cmd.getStrictStr(CMD_EXT);
			int dotPos = nameAndTx.indexOf('.');
			String name = dotPos > 0 ? nameAndTx.substring(0, dotPos) : nameAndTx;
			String tx = dotPos > 0 ? nameAndTx.substring(dotPos + 1) : null;
			if (path != null) name = Uris.URIS.pathJoin(path, name);
			
			Tuple2<String, byte[]> foundImage = imageStore.get(name, ext);
			if (foundImage == null) {
				return HTTP.createBasicResponse(
					SC_NOT_FOUND,
					Obj.make("reason", statusToReason.get(SC_NOT_FOUND)).toString(),
					CT_APPLICATION_JSON_CS_UTF8);
			} else {
				ByteArrayEntity res;
				byte[] image = foundImage.get1();
				if (tx == null && fmtEquals(ext, foundImage.get0())) {
					res = new ByteArrayEntity(image);
				} else {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					Tuple2<BufferedImage, String> biAndFmt = imageSizeFilter.readImageAndFormat(new ByteArrayInputStream(image));
					BufferedImage src = biAndFmt.get0();
					imageSizeFilter.resize(src, baos, ext, getWidthAndHeight(src.getWidth(), src.getHeight(), tx));
					res = new ByteArrayEntity(baos.toByteArray());
				}
				res.setContentType(fmt2contentType(ext));
				return res;
			}
		} catch (Exception e) {
			throw new Http500Exception(e);
		}
	}
1300965
public GetStatSrcFlowResponse getStatSrcFlow(GetStatSrcFlowRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, STAT, "srcflow");
        
        if (request.getStartTime() != null) {
            internalRequest.addParameter("startTime", DateUtils.formatAlternateIso8601Date(request.getStartTime()));
        }
        
        if (request.getEndTime() != null) {
            internalRequest.addParameter("endTime", DateUtils.formatAlternateIso8601Date(request.getEndTime()));
        }
        
        if (request.getDomain() != null) {
            internalRequest.addParameter("domain", request.getDomain());
        }
        
        if (request.getPeriod() != null) {
            internalRequest.addParameter("period", String.valueOf(request.getPeriod()));
        }
        
        return this.invokeHttpClient(internalRequest, GetStatSrcFlowResponse.class);
    }
686713
private MultipartParsingResult parseRequest(HttpRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        try {
            RequestBody body = request.getBody();
            Assert.notNull(body, "The body cannot be null.");
            List<FileItem> fileItems = fileUpload.parseRequest(new BodyContext(body));
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadBase.FileSizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Failed to parse multipart servlet request.", ex);
        }
    }
1312298
@Override
    public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpMessage request,
                                 Class<?> expectedResultType) throws Exception {
        final String path = getPath(ctx);
        final Optional<Iterable<String>> jsonPaths = getJsonPaths(ctx);
        if (jsonPaths.isPresent()) {
            return Optional.of(Query.ofJsonPath(path, jsonPaths.get()));
        }

        if (isValidFilePath(path)) {
            return Optional.of(Query.of(QueryType.IDENTITY, path));
        }
        return Optional.empty();
    }
504714
public static String getError(final HttpServletRequest request) {
		StringBuilder sb = (StringBuilder) request.getAttribute(ERROR_KEY);
		if (sb == null) {
			return "";
		}
		return sb.toString();
	}
913902
public CreateBucketResponse createBucket(CreateBucketRequest request) {
        checkNotNull(request, "request should not be null.");

        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT);
        this.setZeroContentLength(internalRequest);
        BosResponse response = this.invokeHttpClient(internalRequest, BosResponse.class);
        CreateBucketResponse result = new CreateBucketResponse();
        result.setName(request.getBucketName());
        result.setLocation(response.getMetadata().getLocation());
        return result;
    }
665628
public CopyObjectResponse copyObject(CopyObjectRequest request) {
        checkNotNull(request, "request should not be null.");
        assertStringNotNullOrEmpty(request.getSourceKey(), "object key should not be null or empty");

        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT);

        String copySourceHeader = "/" + request.getSourceBucketName() + "/" + request.getSourceKey();
        copySourceHeader = HttpUtils.normalizePath(copySourceHeader);
        internalRequest.addHeader(Headers.BCE_COPY_SOURCE, copySourceHeader);
        if (request.getETag() != null) {
            internalRequest.addHeader(Headers.BCE_COPY_SOURCE_IF_MATCH,
                    "\"" + request.getETag() + "\"");
        }
        if (request.getNoneMatchETagConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_NONE_MATCH, "\"" + request.getNoneMatchETagConstraint() + "\"");
        }
        if (request.getUnmodifiedSinceConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE, request.getUnmodifiedSinceConstraint());
        }
        if (request.getModifiedSinceConstraint() != null) {
            internalRequest.addHeader(
                    Headers.BCE_COPY_SOURCE_IF_MODIFIED_SINCE, request.getModifiedSinceConstraint());
        }
        if (request.getStorageClass() != null) {
            internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass());
        }
        ObjectMetadata newObjectMetadata = request.getNewObjectMetadata();
        if (newObjectMetadata != null) {
            internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "replace");
            populateRequestMetadata(internalRequest, newObjectMetadata);
        } else {
            internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "copy");
        }

        this.setZeroContentLength(internalRequest);

        CopyObjectResponseWithExceptionInfo intermidiateRes = this.invokeHttpClient(internalRequest,
                CopyObjectResponseWithExceptionInfo.class);
        // handle exception
        if (intermidiateRes.getETag() == null 
                && intermidiateRes.getLastModified() == null) {
            if (intermidiateRes.getMessage() != null) {
                BceServiceException bse = new BceServiceException(intermidiateRes.getMessage());
                bse.setErrorCode(intermidiateRes.getCode());
                bse.setRequestId(intermidiateRes.getRequestId());
                if (bse.getErrorCode() == "InternalError") {
                    bse.setErrorType(ErrorType.Service);
                } else {
                    bse.setErrorType(ErrorType.Client);
                }
                bse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                throw bse;
            }
        }
        return (CopyObjectResponse) intermidiateRes;
    }