code
stringlengths
11
173k
docstring
stringlengths
2
593k
func_name
stringlengths
2
189
language
stringclasses
1 value
repo
stringclasses
833 values
path
stringlengths
11
294
url
stringlengths
60
339
license
stringclasses
4 values
public StorageSourceConfig findByStorageIdAndName(Integer storageId, String name) { return storageSourceConfigService .selectStorageConfigByStorageId(storageId) .stream() .filter(storageSourceConfig -> StrUtil.equals(name, storageSourceConfig.getName())) .findFirst() .orElse(null); }
获取指定存储源的指定参数名称 @param storageId 存储源 id @param name 参数名 @return 参数信息
StorageSourceConfigService::findByStorageIdAndName
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceConfigService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceConfigService.java
MIT
public List<StorageSourceConfig> toStorageSourceConfigList(Integer storageId, StorageTypeEnum storageType, StorageSourceAllParamDTO storageSourceAllParam) { // 返回结果 List<StorageSourceConfig> result = new ArrayList<>(); // 获取该存储源类型需要的参数列表 List<StorageSourceParamDef> storageSourceParamList = StorageSourceContext.getStorageSourceParamListByType(storageType); // 遍历参数列表, 将参数转换成存储源参数对象 for (StorageSourceParamDef storageSourceParam : storageSourceParamList) { // 根据字段名称获取字段值 Object fieldValue = ReflectUtil.getFieldValue(storageSourceAllParam, storageSourceParam.getKey()); String fieldStrValue = Convert.toStr(fieldValue); // 校验是否必填, 如果不符合则抛出异常 boolean paramRequired = storageSourceParam.isRequired(); if (paramRequired && StrUtil.isEmpty(fieldStrValue)) { String errMsg = StrUtil.format("参数「{}」不能为空", storageSourceParam.getName()); throw new InitializeStorageSourceException(CodeMsg.STORAGE_SOURCE_INIT_STORAGE_CONFIG_FAIL, storageId, errMsg).setResponseExceptionMessage(true); } // 校验如果有默认值,则填充默认值 String paramDefaultValue = storageSourceParam.getDefaultValue(); if (StrUtil.isNotEmpty(paramDefaultValue) && StrUtil.isEmpty(fieldStrValue)) { fieldStrValue = paramDefaultValue; } // 添加到结果列表 StorageSourceConfig storageSourceConfig = new StorageSourceConfig(); storageSourceConfig.setTitle(storageSourceParam.getName()); storageSourceConfig.setName(storageSourceParam.getKey()); storageSourceConfig.setValue(fieldStrValue); storageSourceConfig.setType(storageType); storageSourceConfig.setStorageId(storageId); result.add(storageSourceConfig); } return result; }
将存储源所有参数转换成指定存储类型的参数对象列表 @param storageId 存储源 ID @param storageType 存储源类型 @param storageSourceAllParam 存储源所有参数
CacheEvict::toStorageSourceConfigList
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceConfigService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceConfigService.java
MIT
public List<StorageSource> findAllOrderByOrderNum() { return storageSourceMapper.findAllOrderByOrderNum(); }
获取所有存储源列表 @return 存储源列表
StorageSourceService::findAllOrderByOrderNum
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
public List<StorageSource> findAllEnableOrderByOrderNum() { return storageSourceMapper.findListByEnableOrderByOrderNum(); }
获取所有已启用的存储源列表,按照存储源的排序号排序 @return 已启用的存储源列表
StorageSourceService::findAllEnableOrderByOrderNum
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
public Integer findIdByKey(String storageKey) { return Optional.ofNullable(storageSourceService.findByStorageKey(storageKey)).map(StorageSource::getId).orElse(null); }
根据存储源 key 获取存储源 id @param storageKey 存储源 key @return 存储源信息
StorageSourceService::findIdByKey
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
public String findStorageKeyById(Integer id){ return Optional.ofNullable(storageSourceService.findById(id)).map(StorageSource::getKey).orElse(null); }
根据存储源 id 获取存储源 key @param id 存储源 id @return 存储源 key
StorageSourceService::findStorageKeyById
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
public StorageTypeEnum findStorageTypeById(Integer id) { return Optional.ofNullable(storageSourceService.findById(id)).map(StorageSource::getType).orElse(null); }
根据 id 获取指定存储源的类型. @param id 存储源 ID @return 存储源对应的类型.
StorageSourceService::findStorageTypeById
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
public boolean existByStorageKey(String storageKey) { return storageSourceService.findByStorageKey(storageKey) != null; }
判断存储源 key 是否已存在 (不读取缓存) @param storageKey 存储源 key @return 是否已存在
StorageSourceService::existByStorageKey
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/StorageSourceService.java
MIT
private static void checkPathSecurity(String... paths) { for (String path : paths) { // 路径中不能包含 .. 不然可能会获取到上层文件夹的内容 if (StrUtil.startWith(path, "/..") || StrUtil.containsAny(path, "../", "..\\")) { throw new IllegalArgumentException("文件路径存在安全隐患: " + path); } } }
检查路径合法性: - 只有以 . 开头的允许通过,其他的如 ./ ../ 的都是非法获取上层文件夹内容的路径. @param paths 文件路径 @throws IllegalArgumentException 文件路径包含非法字符时会抛出此异常
LocalServiceImpl::checkPathSecurity
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/LocalServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/LocalServiceImpl.java
MIT
private static void checkNameSecurity(String... names) { for (String name : names) { // 路径中不能包含 .. 不然可能会获取到上层文件夹的内容 if (StrUtil.containsAny(name, "\\", "/")) { throw new IllegalArgumentException("文件名存在安全隐患: " + name); } } }
检查路径合法性: - 不为空,且不包含 \ / 字符 @param names 文件路径 @throws IllegalArgumentException 文件名包含非法字符时会抛出此异常
LocalServiceImpl::checkNameSecurity
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/LocalServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/LocalServiceImpl.java
MIT
private String getIdByPath(String path) { String fullPath = StringUtils.concat(param.getBasePath(), path); if (StrUtil.isEmpty(fullPath) || StrUtil.equals(fullPath, StringUtils.DELIMITER_STR)) { return StrUtil.isEmpty(param.getDriveId()) ? "root" : param.getDriveId(); } List<String> pathList = StrUtil.splitTrim(fullPath, "/"); String driveId = ""; for (String subPath : pathList) { String folderIdParam = new GoogleDriveAPIParam().getDriveIdByPathParam(subPath, driveId); HttpRequest httpRequest = HttpUtil.createGet(DRIVE_FILE_URL); httpRequest.header("Authorization", "Bearer " + param.getAccessToken()); httpRequest.body(folderIdParam); HttpResponse httpResponse = httpRequest.execute(); checkHttpResponseIsError(httpResponse); String body = httpResponse.body(); JSONObject jsonRoot = JSON.parseObject(body); JSONArray files = jsonRoot.getJSONArray("files"); if (files.size() == 0) { throw ExceptionUtil.wrapRuntime(new FileNotFoundException()); } JSONObject jsonLastItem = files.getJSONObject(files.size() - 1); if (jsonLastItem.containsKey("shortcutDetails")) { driveId = jsonLastItem.getJSONObject("shortcutDetails").getString("targetId"); } else { driveId = jsonLastItem.getString("id"); } } return driveId; }
根据路径获取文件/文件夹 id @param path 路径 @return 文件/文件夹 id
GoogleDriveServiceImpl::getIdByPath
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public OAuth2TokenDTO getRefreshToken() { StorageSourceConfig refreshStorageSourceConfig = storageSourceConfigService.findByStorageIdAndName(storageId, StorageConfigConstant.REFRESH_TOKEN_KEY); String paramStr = "client_id=" + param.getClientId() + "&client_secret=" + param.getClientSecret() + "&refresh_token=" + refreshStorageSourceConfig.getValue() + "&grant_type=refresh_token" + "&access_type=offline"; log.info("存储源 {}({}) 尝试刷新令牌", storageId, this.getStorageTypeEnum().getDescription()); if (log.isDebugEnabled()) { log.debug("存储源 {}({}) 尝试刷新令牌, 参数信息为: {}", storageId, this.getStorageTypeEnum().getDescription(), param); } HttpRequest post = HttpUtil.createPost(REFRESH_TOKEN_URL); post.body(paramStr); HttpResponse response = post.execute(); String responseBody = response.body(); log.info("存储源 {}({}) 刷新令牌完成, 响应信息为: httpStatus: {}", storageId, this.getStorageTypeEnum().getDescription(), response.getStatus()); if (log.isDebugEnabled()) { log.debug("存储源 {}({}) 刷新令牌完成, 响应信息为: {}", storageId, this.getStorageTypeEnum().getDescription(), responseBody); } JSONObject jsonBody = JSONObject.parseObject(responseBody); if (response.getStatus() != HttpStatus.OK.value()) { return OAuth2TokenDTO.fail(param.getClientId(), param.getClientSecret(), param.getRedirectUri(), responseBody); } String accessToken = jsonBody.getString("access_token"); return OAuth2TokenDTO.success(param.getClientId(), param.getClientSecret(), param.getRedirectUri(), accessToken, null, responseBody); }
根据 RefreshToken 刷新 AccessToken, 返回刷新后的 Token. @return 刷新后的 Token
GoogleDriveServiceImpl::getRefreshToken
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public List<FileItemResult> jsonArrayToFileList(JSONArray jsonArray, String folderPath) { ArrayList<FileItemResult> fileList = new ArrayList<>(); for (int i = 0; i < jsonArray.size(); i++) { fileList.add(jsonObjectToFileItem(jsonArray.getJSONObject(i), folderPath)); } return fileList; }
转换 api 返回的 json array 为 zfile 文件对象列表 @param jsonArray api 返回文件 json array @param folderPath 所属文件夹路径 @return zfile 文件对象列表
GoogleDriveServiceImpl::jsonArrayToFileList
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public FileItemResult jsonObjectToFileItem(JSONObject jsonObject, String folderPath) { FileItemResult fileItemResult = new FileItemResult(); fileItemResult.setName(jsonObject.getString("name")); fileItemResult.setPath(folderPath); fileItemResult.setSize(jsonObject.getLong("size")); String mimeType = jsonObject.getString("mimeType"); if (ObjectUtil.equals(SHORTCUT_MIME_TYPE, mimeType)) { JSONObject shortcutDetails = jsonObject.getJSONObject("shortcutDetails"); mimeType = shortcutDetails.getString("targetMimeType"); } if (StrUtil.equals(mimeType, FOLDER_MIME_TYPE)) { fileItemResult.setType(FileTypeEnum.FOLDER); } else { fileItemResult.setType(FileTypeEnum.FILE); fileItemResult.setUrl(getDownloadUrl(StringUtils.concat(folderPath, fileItemResult.getName()))); } fileItemResult.setTime(jsonObject.getDate("modifiedTime")); if (fileItemResult.getSize() == null) { fileItemResult.setSize(-1L); } return fileItemResult; }
转换 api 返回的 json object 为 zfile 文件对象 @param jsonObject api 返回文件 json object @param folderPath 所属文件夹路径 @return zfile 文件对象
GoogleDriveServiceImpl::jsonObjectToFileItem
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public String getDriveIdByPathParam(String folderPath, String parentId) { GoogleDriveAPIParam googleDriveApiParam = getBasicParam(); String parentIdParam = ""; if (StrUtil.isNotEmpty(parentId)) { parentIdParam = "'" + parentId + "' in parents and "; } googleDriveApiParam.setFields("files(id,shortcutDetails)"); googleDriveApiParam.setQ(parentIdParam + " name = '" + folderPath + "' and trashed = false"); return googleDriveApiParam.toString(); }
根据路径获取 id 的 api 请求参数 @param folderPath 文件夹路径
GoogleDriveAPIParam::getDriveIdByPathParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public String getFileListParam(String folderId, String pageToken) { GoogleDriveAPIParam googleDriveAPIParam = getBasicParam(); googleDriveAPIParam.setFields("files(id,name,mimeType,shortcutDetails,size,modifiedTime),nextPageToken"); googleDriveAPIParam.setQ("'" + folderId + "' in parents and trashed = false"); googleDriveAPIParam.setPageToken(pageToken); googleDriveAPIParam.setPageSize(DEFAULT_PAGE_SIZE); return googleDriveAPIParam.toString(); }
根据路径获取 id 的 api 请求参数 @param folderId google drive 文件夹 id @param pageToken 分页 token
GoogleDriveAPIParam::getFileListParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public String getSearchParam(String folderId, String pageToken, String keyword) { GoogleDriveAPIParam googleDriveAPIParam = getBasicParam(); String parentIdParam = ""; if (StrUtil.isNotEmpty(folderId)) { parentIdParam = "'" + folderId + "' in parents and "; } googleDriveAPIParam.setFields("files(id,name,mimeType,shortcutDetails,size,modifiedTime),nextPageToken"); googleDriveAPIParam.setQ(parentIdParam + " name contains '" + keyword + "' and trashed = false"); googleDriveAPIParam.setPageToken(pageToken); googleDriveAPIParam.setPageSize(DEFAULT_PAGE_SIZE); return googleDriveAPIParam.toString(); }
根据关键字和路径搜索文件 api 请求参数 @param folderId 搜索的父文件夹 id @param pageToken 分页 token @param keyword 搜索关键字
GoogleDriveAPIParam::getSearchParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
public GoogleDriveAPIParam getBasicParam() { GoogleDriveAPIParam googleDriveAPIParam = new GoogleDriveAPIParam(); String driveId = param.getDriveId(); // 判断是否是团队盘,如果是,则需要添加团队盘的参数 boolean isTeamDrive = StrUtil.isNotEmpty(driveId); googleDriveAPIParam.setCorpora("user"); googleDriveAPIParam.setIncludeItemsFromAllDrives(true); googleDriveAPIParam.setSupportsAllDrives(true); if (isTeamDrive) { googleDriveAPIParam.setDriveId(driveId); googleDriveAPIParam.setCorpora("drive"); } return googleDriveAPIParam; }
判断是否是团队盘,填充基础参数
GoogleDriveAPIParam::getBasicParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
private void checkHttpResponseIsError(HttpResponse httpResponse) { if (HttpStatus.valueOf(httpResponse.getStatus()).isError()) { int statusCode = httpResponse.getStatus(); String responseBody = httpResponse.body(); String msg = StrUtil.format("statusCode: {}, responseBody: {}", statusCode, responseBody); throw new HttpResponseStatusErrorException(msg); } }
检查 http 响应是否为 5xx, 如果是,则抛出异常 @param httpResponse http 响应
GoogleDriveAPIParam::checkHttpResponseIsError
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
private void checkHttpResponseIsError(CloseableHttpResponse closeableHttpResponse) throws IOException { int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); if (HttpStatus.valueOf(statusCode).isError()) { HttpEntity responseEntity = closeableHttpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); String msg = StrUtil.format("statusCode: {}, responseBody: {}", statusCode, responseBody); throw new HttpResponseStatusErrorException(msg); } }
检查 http 响应是否为 5xx, 如果是,则抛出异常 (http client) @param closeableHttpResponse http 响应
GoogleDriveAPIParam::checkHttpResponseIsError
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/GoogleDriveServiceImpl.java
MIT
private String getPolicy(UploadSignParam uploadSignParam) { String bucketName = param.getBucketName(); HashMap<String, Object> params = new HashMap<>(); params.put(Params.BUCKET, bucketName); params.put(Params.SAVE_KEY, StringUtils.concat(uploadSignParam.getPath(), uploadSignParam.getName())); params.put(Params.EXPIRATION, System.currentTimeMillis() / 1000 + UPLOAD_SESSION_EXPIRATION); params.put("content-length", uploadSignParam.getSize()); params.put(Params.CONTENT_LENGTH_RANGE, "0," + uploadSignParam.getSize()); return UpYunUtils.getPolicy(params); }
获取上传 policy @param uploadSignParam 上传签名参数 @return 上传 policy
UpYunServiceImpl::getPolicy
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/impl/UpYunServiceImpl.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/impl/UpYunServiceImpl.java
MIT
public void testConnection() { try { fileList("/"); isInitialized = true; } catch (Exception e) { throw new InitializeStorageSourceException(CodeMsg.STORAGE_SOURCE_INIT_FAIL, storageId, "初始化异常, 错误信息为: " + e.getMessage(), e).setResponseExceptionMessage(true); } }
测试是否连接成功, 会尝试取调用获取根路径的文件, 如果没有抛出异常, 则认为连接成功.
AbstractBaseFileService::testConnection
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractBaseFileService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractBaseFileService.java
MIT
public OAuth2TokenDTO getTokenByCode(String code, String clientId, String clientSecret, String redirectUri) { String param = "client_id=" + clientId + "&redirect_uri=" + redirectUri + "&client_secret=" + clientSecret + "&code=" + code + "&scope=" + getScope() + "&grant_type=authorization_code"; if (log.isDebugEnabled()) { log.debug("根据授权回调 code 获取存储源类型为 [{}] 的令牌, 请求参数: [{}]", this.getStorageTypeEnum().getDescription(), param); } String fullAuthenticateUrl = AUTHENTICATE_URL.replace("{authenticateEndPoint}", getAuthenticateEndPoint()); HttpResponse response = HttpUtil.createPost(fullAuthenticateUrl) .body(param, "application/x-www-form-urlencoded") .execute(); String responseBody = response.body(); int responseStatus = response.getStatus(); log.info("根据授权回调 code 获取存储源类型为 [{}] 的令牌完成. [httpStatus: {}]", this.getStorageTypeEnum().getDescription(), responseStatus); if (responseStatus != HttpStatus.OK.value()) { return OAuth2TokenDTO.fail(clientId, clientSecret, redirectUri, responseBody); } JSONObject jsonBody = JSONObject.parseObject(responseBody); String accessToken = jsonBody.getString(ACCESS_TOKEN_FIELD_NAME); String refreshToken = jsonBody.getString(REFRESH_TOKEN_FIELD_NAME); return OAuth2TokenDTO.success(clientId, clientSecret, redirectUri, accessToken, refreshToken, responseBody); }
OAuth2 协议中, 根据 code 换取 access_token 和 refresh_token. @param code 代码 @return 获取的 Token 信息.
AbstractMicrosoftDriveService::getTokenByCode
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractMicrosoftDriveService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractMicrosoftDriveService.java
MIT
public List<FileItemResult> s3FileList(String path) { String bucketName = param.getBucketName(); path = StringUtils.trimStartSlashes(path); String fullPath = StringUtils.trimStartSlashes(StringUtils.concat(param.getBasePath(), path, ZFileConstant.PATH_SEPARATOR)); List<FileItemResult> fileItemList = new ArrayList<>(); ListObjectsRequest listObjectsRequest = new ListObjectsRequest() .withBucketName(bucketName) .withPrefix(fullPath) .withMaxKeys(1000) .withDelimiter("/"); ObjectListing objectListing = s3Client.listObjects(listObjectsRequest); boolean isFirstWhile = true; do { if (!isFirstWhile) { objectListing = s3Client.listNextBatchOfObjects(objectListing); } for (S3ObjectSummary s : objectListing.getObjectSummaries()) { FileItemResult fileItemResult = new FileItemResult(); if (s.getKey().equals(fullPath)) { continue; } fileItemResult.setName(s.getKey().substring(fullPath.length())); fileItemResult.setSize(s.getSize()); fileItemResult.setTime(s.getLastModified()); fileItemResult.setType(FileTypeEnum.FILE); fileItemResult.setPath(path); String fullPathAndName = StringUtils.concat(path, fileItemResult.getName()); fileItemResult.setUrl(getDownloadUrl(fullPathAndName)); fileItemList.add(fileItemResult); } for (String commonPrefix : objectListing.getCommonPrefixes()) { FileItemResult fileItemResult = new FileItemResult(); fileItemResult.setName(commonPrefix.substring(fullPath.length(), commonPrefix.length() - 1)); String name = fileItemResult.getName(); if (StrUtil.isEmpty(name) || StrUtil.equals(name, StringUtils.DELIMITER_STR)) { continue; } fileItemResult.setType(FileTypeEnum.FOLDER); fileItemResult.setPath(path); fileItemList.add(fileItemResult); } isFirstWhile = false; } while (objectListing.isTruncated()); return fileItemList; }
获取 S3 指定目录下的对象列表 @param path 路径 @return 指定目录下的对象列表
AbstractS3BaseFileService::s3FileList
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractS3BaseFileService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/storage/service/base/AbstractS3BaseFileService.java
MIT
public boolean containsPathMatcher(Collection<String> patternList, String value) { if (CollUtil.isEmpty(patternList)) { return false; } for (String pattern : patternList) { if (pathMatcher.match(pattern, value)) { return true; } } return false; }
校验 value 是否在 Ant 表达式列表中. @param patternList Ant 表达式列表 @param value 要校验的值 @return 如果集合为空 (null 或者空), 返回 false, 否则在表达式列表中找到匹配的返回 true, 找不到返回 false.
RefererCheckAspect::containsPathMatcher
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/link/aspect/RefererCheckAspect.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/link/aspect/RefererCheckAspect.java
MIT
private void handlerDownload(String storageKey, String filePath, String shortKey, String downloadType) throws IOException { HttpServletRequest request = RequestHolder.getRequest(); HttpServletResponse response = RequestHolder.getResponse(); // 获取存储源 Service AbstractBaseFileService<?> fileService; try { fileService = storageSourceContext.getByStorageKey(storageKey); } catch (InvalidStorageSourceException e) { throw new RuntimeException("无效的或初始化失败的存储源 [" + storageKey + "] 文件 [" + filePath + "] 下载链接异常, 无法下载.", e); } StorageSource storageSource = storageSourceService.findByStorageKey(storageKey); Boolean enable = storageSource.getEnable(); if (!enable) { throw new RuntimeException("未启用的存储源 [" + storageKey + "] 文件 [" + filePath + "] 下载链接异常, 无法下载."); } // 检查是否访问了禁止下载的目录 if (filterConfigService.checkFileIsDisableDownload(storageSource.getId(), filePath)) { // 获取 Forbidden 页面地址 String forbiddenUrl = systemConfigService.getForbiddenUrl(); RequestHolder.getResponse().sendRedirect(forbiddenUrl); return; } // 获取文件下载链接 String downloadUrl; try { downloadUrl = fileService.getDownloadUrl(filePath); } catch (StorageSourceFileOperatorException e) { throw new RuntimeException("获取存储源 [" + storageKey + "] 文件 [" + filePath + "] 下载链接异常, 无法下载.", e); } // 判断下载链接是否为空 if (StrUtil.isEmpty(downloadUrl)) { throw new RuntimeException("获取存储源 [" + storageKey + "] 文件 [" + filePath + "] 下载链接为空, 无法下载."); } // 记录下载日志. SystemConfigDTO systemConfig = systemConfigService.getSystemConfig(); Boolean recordDownloadLog = systemConfig.getRecordDownloadLog(); if (BooleanUtil.isTrue(recordDownloadLog)) { DownloadLog downloadLog = new DownloadLog(downloadType, filePath, storageKey, shortKey); downloadLogService.save(downloadLog); } // 判断下载链接是否为 m3u8 格式, 如果是则返回 m3u8 内容. if (StrUtil.equalsIgnoreCase(FileUtil.extName(filePath), "m3u8")) { String textContent = HttpUtil.getTextContent(downloadUrl); response.setContentType("application/vnd.apple.mpegurl;charset=utf-8"); OutputStream outputStream = response.getOutputStream(); byte[] textContentBytes = EncodingUtils.getBytes(textContent, CharsetUtil.CHARSET_UTF_8.displayName()); IoUtil.write(outputStream, true, textContentBytes); return; } // 禁止直链被浏览器 302 缓存. response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate, private"); response.setHeader(HttpHeaders.PRAGMA, "no-cache"); response.setHeader(HttpHeaders.EXPIRES, "0"); // 重定向到下载链接. String parameterType = request.getParameter("type"); if (StrUtil.equals(parameterType, "preview")) { downloadUrl = UrlUtils.concatQueryParam(downloadUrl, "type", "preview"); } response.sendRedirect(downloadUrl); }
处理指定存储源的下载请求 @param storageKey 存储源 key @param filePath 文件路径 @param shortKey 短链接 key @param downloadType 下载类型, 直链下载(directLink)或短链下载(shortLink) @throws IOException 可能抛出的 IO 异常
LinkDownloadService::handlerDownload
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/link/service/LinkDownloadService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/link/service/LinkDownloadService.java
MIT
public ShortLink generatorShortLink(Integer storageId, String fullPath, Long expireTime) { boolean validate = checkExpireDateIsValidate(expireTime); if (!validate) { throw new IllegalArgumentException("过期时间不合法"); } ShortLink shortLink; String randomKey; int generateCount = 0; do { // 获取短链 randomKey = RandomUtil.randomString(6); shortLink = shortLinkService.findByKey(randomKey); generateCount++; } while (shortLink != null); shortLink = new ShortLink(); shortLink.setStorageId(storageId); shortLink.setUrl(fullPath); shortLink.setCreateDate(new Date()); shortLink.setShortKey(randomKey); if (expireTime == -1) { shortLink.setExpireDate(DateUtil.parseDate("9999-12-31")); } else { shortLink.setExpireDate(new Date(System.currentTimeMillis() + expireTime * 1000L)); } if (log.isDebugEnabled()) { log.debug("生成直/短链: 存储源 ID: {}, 文件路径: {}, 短链 key {}, 随机生成直链冲突次数: {}", shortLink.getStorageId(), shortLink.getUrl(), shortLink.getShortKey(), generateCount); } shortLinkMapper.insert(shortLink); return shortLink; }
为存储源指定路径生成短链接, 保证生成的短连接 key 是不同的 @param storageId 存储源 id @param fullPath 存储源路径 @return 生成后的短链接信息
ShortLinkService::generatorShortLink
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/link/service/ShortLinkService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/link/service/ShortLinkService.java
MIT
public ReadmeConfig findReadmeByPath(Integer storageId, String path) { List<ReadmeConfig> readmeConfigList = readmeConfigService.findByStorageId(storageId); return getReadmeByTestPattern(storageId, readmeConfigList, path); }
根据存储源指定路径下的 readme 配置 @param storageId 存储源ID @param path 文件夹路径 @return 存储源 readme 配置列表
public::findReadmeByPath
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
MIT
public ReadmeConfig getByStorageAndPath(Integer storageId, String path, Boolean compatibilityReadme) { ReadmeConfig readmeByPath = new ReadmeConfig(); readmeByPath.setStorageId(storageId); readmeByPath.setDisplayMode(ReadmeDisplayModeEnum.BOTTOM); if (BooleanUtil.isTrue(compatibilityReadme)) { try { log.info("存储源 {} 兼容获取目录 {} 下的 readme.md", storageId, path); AbstractBaseFileService<IStorageParam> abstractBaseFileService = storageSourceContext.getByStorageId(storageId); String pathAndName = StringUtils.concat(path, "readme.md"); FileItemResult fileItem = abstractBaseFileService.getFileItem(pathAndName); if (fileItem != null) { String url = fileItem.getUrl(); String readmeText = HttpUtil.getTextContent(url); readmeByPath.setReadmeText(readmeText); } } catch (Exception e) { log.error("存储源 {} 兼容获取目录 {} 下的 readme.md 文件失败", storageId, path, e); } } else { // 获取指定目录 readme 文件 ReadmeConfig dbReadmeConfig = readmeConfigService.findReadmeByPath(storageId, path); if (dbReadmeConfig != null) { readmeByPath = dbReadmeConfig; } log.info("存储源 {} 规则模式获取目录 {} 下文档信息", storageId, path); } return readmeByPath; }
根据存储源指定路径下的 readme 配置,如果指定为兼容模式,则会读取指定目录下的 readme.md 文件. @param storageId 存储源 ID @param path 存储源路径 @param compatibilityReadme 是否兼容为读取 readme.md 文件 @return 目录下存储源 readme 配置
public::getByStorageAndPath
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
MIT
private ReadmeConfig getReadmeByTestPattern(Integer storageId, List<ReadmeConfig> patternList, String test) { // 如果目录文档规则为空, 则可直接返回空. if (CollUtil.isEmpty(patternList)) { if (log.isDebugEnabled()) { log.debug("目录文档规则列表为空, 存储源 ID: {}, 测试字符串: {}", storageId, test); } return null; } for (ReadmeConfig filterConfig : patternList) { String expression = filterConfig.getExpression(); if (StrUtil.isEmpty(expression)) { if (log.isDebugEnabled()) { log.debug("存储源 {} 目录文档规则表达式为空: {}, 测试字符串: {}, 表达式为空,跳过该规则比对", storageId, expression, test); } continue; } try { boolean match = PatternMatcherUtils.testCompatibilityGlobPattern(expression, test); if (log.isDebugEnabled()) { log.debug("存储源 {} 目录文档规则表达式: {}, 测试字符串: {}, 匹配结果: {}", storageId, expression, test, match); } if (match) { return filterConfig; } } catch (Exception e) { log.error("存储源 {} 目录文档规则表达式: {}, 测试字符串: {}, 匹配异常,跳过该规则.", storageId, expression, test, e); } } return null; }
根据规则表达式和测试字符串进行匹配,如测试字符串和其中一个规则匹配上,则返回 true,反之返回 false。 @param patternList 规则列表 @param test 测试字符串 @return 是否显示
public::getReadmeByTestPattern
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/readme/service/ReadmeConfigService.java
MIT
public LoginVerifyImgResult generatorCaptcha() { CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 45, 4, 7); String code = captcha.getCode(); String imageBase64 = captcha.getImageBase64Data(); String uuid = UUID.fastUUID().toString(); verifyCodeCache.put(uuid, code); LoginVerifyImgResult loginVerifyImgResult = new LoginVerifyImgResult(); loginVerifyImgResult.setImgBase64(imageBase64); loginVerifyImgResult.setUuid(uuid); return loginVerifyImgResult; }
生成验证码,并写入缓存中. @return 验证码生成结果
ImgVerifyCodeService::generatorCaptcha
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
MIT
public boolean verifyCaptcha(String uuid, String code) { String expectedCode = verifyCodeCache.get(uuid); return Objects.equals(expectedCode, code); }
对验证码进行验证. @param uuid 验证码 uuid @param code 验证码 @return 是否验证成功
ImgVerifyCodeService::verifyCaptcha
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
MIT
public void checkCaptcha(String uuid, String code) { boolean flag = verifyCaptcha(uuid, code); if (!flag) { throw new LoginVerifyException("验证码错误或已失效."); } }
对验证码进行验证, 如验证失败则抛出异常 @param uuid 验证码 uuid @param code 验证码
ImgVerifyCodeService::checkCaptcha
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/ImgVerifyCodeService.java
MIT
public LoginTwoFactorAuthenticatorResult setupDevice() throws QrGenerationException { // 生成 2FA 密钥 String secret = secretGenerator.generate(); QrData data = qrDataFactory.newBuilder().secret(secret).issuer("ZFile").build(); // 将生成的 2FA 密钥转换为 Base64 图像字符串 String qrCodeImage = getDataUriForImage( qrGenerator.generate(data), qrGenerator.getImageMimeType()); return new LoginTwoFactorAuthenticatorResult(qrCodeImage, secret); }
生成 2FA 双因素认证二维码和密钥 @return 2FA 双因素认证二维码和密钥 @throws QrGenerationException 二维码生成异常
TwoFactorAuthenticatorVerifyService::setupDevice
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
MIT
public void deviceVerify(VerifyLoginTwoFactorAuthenticatorRequest verifyLoginTwoFactorAuthenticatorRequest) { String secret = verifyLoginTwoFactorAuthenticatorRequest.getSecret(); String code = verifyLoginTwoFactorAuthenticatorRequest.getCode(); if (verifier.isValidCode(secret, code)) { SystemConfigDTO systemConfig = systemConfigService.getSystemConfig(); systemConfig.setLoginVerifyMode(LoginVerifyModeEnum.TWO_FACTOR_AUTHENTICATION_MODE); systemConfig.setLoginVerifySecret(secret); systemConfigService.updateSystemConfig(systemConfig); } else { throw new LoginVerifyException("验证码不正确"); } }
验证 2FA 双因素认证是否正确,正确则进行绑定. @param verifyLoginTwoFactorAuthenticatorRequest 2FA 双因素认证请求参数
TwoFactorAuthenticatorVerifyService::deviceVerify
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
MIT
public void checkCode(String loginVerifySecret, String verifyCode) { if (!verifier.isValidCode(loginVerifySecret, verifyCode)) { throw new LoginVerifyException("验证码错误或已失效"); } }
验证 2FA 双因素认证. @param loginVerifySecret 2FA 双因素认证密钥 @param verifyCode 2FA 双因素认证验证码
TwoFactorAuthenticatorVerifyService::checkCode
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/module/login/service/TwoFactorAuthenticatorVerifyService.java
MIT
private List<RequestParameter> generateRequestParameters(){ RequestParameterBuilder token = new RequestParameterBuilder(); List<RequestParameter> parameters = new ArrayList<>(); token.name("zfile-token").description("token").in(In.HEADER.toValue()).required(true).build(); parameters.add(token.build()); return parameters; }
获取通用的全局参数 @return 全局参数列表
Knife4jConfiguration::generateRequestParameters
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/config/Knife4jConfiguration.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/config/Knife4jConfiguration.java
MIT
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("ZFILE 文档") .description("# 这是 ZFILE Restful 接口文档展示页面") .termsOfServiceUrl("https://www.zfile.vip") .contact(new Contact("zhaojun", "https://zfile.vip", "[email protected]")) .version("1.0") .build(); }
api 基本信息描述 @return ApiInfo
Knife4jConfiguration::apiInfo
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/config/Knife4jConfiguration.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/config/Knife4jConfiguration.java
MIT
public String getResultMessage() { return responseExceptionMessage ? super.getMessage() : super.getCodeMsg().getMsg(); }
根据 responseExceptionMessage 判断使用异常消息进行接口返回,如果是则取异常的 message, 否则取 CodeMsg 中的 message @return 异常消息
StorageSourceException::getResultMessage
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/exception/StorageSourceException.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/exception/StorageSourceException.java
MIT
public StorageSourceException setResponseExceptionMessage(boolean responseExceptionMessage) { this.responseExceptionMessage = responseExceptionMessage; return this; }
设置值是否使用异常消息进行接口返回 @param responseExceptionMessage 是否使用异常消息进行接口返回 @return 当前对象
StorageSourceException::setResponseExceptionMessage
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/exception/StorageSourceException.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/exception/StorageSourceException.java
MIT
public static String getTextContent(String url) { long maxFileSize = 1024 * ZFileConstant.TEXT_MAX_FILE_SIZE_KB; if (getRemoteFileSize(url) > maxFileSize) { throw new PreviewException("预览文件超出大小, 最大支持 " + FileUtil.readableFileSize(maxFileSize)); } String result; try { result = cn.hutool.http.HttpUtil.get(url); } catch (Exception e) { throw new TextParseException(StrUtil.format("获取文件内容失败, URL: {}", url), e); } return result == null ? "" : result; }
获取 URL 对应的文件内容 @param url 文件 URL @return 文件内容
HttpUtil::getTextContent
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/HttpUtil.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/HttpUtil.java
MIT
public static Long getRemoteFileSize(String url) { long size = 0; URL urlObject; try { urlObject = new URL(url); URLConnection conn = urlObject.openConnection(); size = conn.getContentLength(); } catch (IOException e) { e.printStackTrace(); } return size; }
获取远程文件大小 @param url 文件 URL @return 文件大小
HttpUtil::getRemoteFileSize
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/HttpUtil.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/HttpUtil.java
MIT
public static String resolvePlaceholdersBySpringProperties(String formatStr) { String placeholderName = getFirstPlaceholderName(formatStr); if (StrUtil.isEmpty(placeholderName)) { return formatStr; } String propertyValue = SpringUtil.getProperty(placeholderName); Map<String, String> map = new HashMap<>(); map.put(placeholderName, propertyValue); return resolvePlaceholders(formatStr, map); }
解析占位符, 将指定的占位符替换为指定的值. 变量值从 Spring 环境中获取, 如没取到, 则默认为空. 必须在 Spring 环境下使用, 否则会抛出异常. @param formatStr 模板字符串 @return 替换后的字符串
PlaceholderUtils::resolvePlaceholdersBySpringProperties
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
MIT
public static String resolvePlaceholders(String formatStr, Map<String, String> parameter) { if (parameter == null || parameter.isEmpty()) { return formatStr; } StringBuffer buf = new StringBuffer(formatStr); int startIndex = buf.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length()); if (endIndex != -1) { String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length(); try { String propVal = parameter.get(placeholder); if (propVal != null) { buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal); nextIndex = startIndex + propVal.length(); } else { log.warn("Could not resolve placeholder '{}' in [{}] ", placeholder, formatStr); } } catch (Exception ex) { log.error("Could not resolve placeholder '{}' in [{}]: ", placeholder, formatStr, ex); } startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex); } else { startIndex = -1; } } return buf.toString(); }
解析占位符, 将指定的占位符替换为指定的值. @param formatStr 模板字符串 @param parameter 参数列表 @return 替换后的字符串
PlaceholderUtils::resolvePlaceholders
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
MIT
public static String getFirstPlaceholderName(String formatStr) { List<String> list = getPlaceholderNames(formatStr); if (CollUtil.isNotEmpty(list)) { return list.get(0); } return null; }
获取模板字符串第一个占位符的名称, 如 "我的名字是: ${name}, 我的年龄是: ${age}", 返回 "name". @param formatStr 模板字符串 @return 占位符名称
PlaceholderUtils::getFirstPlaceholderName
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
MIT
public static List<String> getPlaceholderNames(String formatStr) { if (StrUtil.isEmpty(formatStr)) { return Collections.emptyList(); } List<String> placeholderNameList = new ArrayList<>(); StringBuffer buf = new StringBuffer(formatStr); int startIndex = buf.indexOf(PLACEHOLDER_PREFIX); while (startIndex != -1) { int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length()); if (endIndex != -1) { String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex); int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length(); startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex); placeholderNameList.add(placeholder); } else { startIndex = -1; } } return placeholderNameList; }
获取模板字符串第一个占位符的名称, 如 "我的名字是: ${name}, 我的年龄是: ${age}", 返回 ["name", "age]. @param formatStr 模板字符串 @return 占位符名称
PlaceholderUtils::getPlaceholderNames
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PlaceholderUtils.java
MIT
public AjaxJson<T> setMsg(String msg) { this.msg = msg; return this; }
给 msg 赋值,连缀风格
AjaxJson::setMsg
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/AjaxJson.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/AjaxJson.java
MIT
public static Class<?> getClassFirstGenericsParam(Class<?> clazz) { Type genericSuperclass = clazz.getGenericSuperclass(); Type actualTypeArgument = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0]; return (Class<?>) actualTypeArgument; }
获取指定类的泛型类型, 只获取第一个泛型类型 @param clazz 泛型类 @return 泛型类型
ClassUtils::getClassFirstGenericsParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/ClassUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/ClassUtils.java
MIT
public static ResponseEntity<Resource> exportSingleThread(File file, String fileName) { if (!file.exists()) { ByteArrayResource byteArrayResource = new ByteArrayResource("文件不存在或异常,请联系管理员.".getBytes(StandardCharsets.UTF_8)); return ResponseEntity.status(HttpStatus.NOT_FOUND) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .body(byteArrayResource); } MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; HttpHeaders headers = new HttpHeaders(); if (StrUtil.isEmpty(fileName)) { fileName = file.getName(); } headers.setContentDispositionFormData("attachment", StringUtils.encodeAllIgnoreSlashes(fileName)); return ResponseEntity .ok() .headers(headers) .contentLength(file.length()) .contentType(mediaType) .body(new InputStreamResource(FileUtil.getInputStream(file))); }
文件下载,单线程,不支持断点续传 @param file 文件对象 @param fileName 要保存为的文件名 @return 文件下载对象
FileResponseUtil::exportSingleThread
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/FileResponseUtil.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/FileResponseUtil.java
MIT
public static String concatQueryParam(String url, String name, String value) { if (StrUtil.contains(url, "?")) { return url + "&" + name + "=" + value; } else { return url + "?" + name + "=" + value; } }
给 url 拼接参数 @param url 原始 URL @param name 参数名称 @param value 参数值 @return 拼接后的 URL
UrlUtils::concatQueryParam
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/UrlUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/UrlUtils.java
MIT
public static String bytesToSize(long bytes) { if (bytes == 0) { return "0"; } double k = 1024; String[] sizes = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; double i = Math.floor(Math.log(bytes) / Math.log(k)); return NumberUtil.round(bytes / Math.pow(k, i), 3) + " " + sizes[(int) i]; }
将文件大小转换为可读单位 @param bytes 字节数 @return 文件大小可读单位
SizeToStrUtils::bytesToSize
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java
MIT
public static String bpsToSize(long bps) { if (bps == 0) { return "0"; } double k = 1000; String[] sizes = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; double i = Math.floor(Math.log(bps) / Math.log(k)); return NumberUtil.round(bps / Math.pow(k, i), 3) + " " + sizes[(int) i]; }
将带宽大小转换为可读单位 @param bps 字节数 @return 带宽大小可读单位
SizeToStrUtils::bpsToSize
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java
MIT
public static Enum<?> convertStrToEnum(Class<?> clazz, Object value) { if (!ClassUtil.isEnum(clazz)) { return null; } Field[] fields = ReflectUtil.getFields(clazz); for (Field field : fields) { boolean jsonValuePresent = field.isAnnotationPresent(JsonValue.class); boolean enumValuePresent = field.isAnnotationPresent(EnumValue.class); if (jsonValuePresent || enumValuePresent) { Object[] enumConstants = clazz.getEnumConstants(); for (Object enumObj : enumConstants) { if (ObjectUtil.equal(value, ReflectUtil.getFieldValue(enumObj, field))) { return (Enum<?>) enumObj; } } } } return null; }
根据枚举 class 和值获取对应的枚举对象 @param clazz 枚举类 Class @param value 枚举值 @return 枚举对象
EnumConvertUtils::convertStrToEnum
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/EnumConvertUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/EnumConvertUtils.java
MIT
public static boolean testCompatibilityGlobPattern(String pattern, String test) { // 如果规则表达式最开始没有 /, 则兼容在最前方加上 /. if (!StrUtil.startWith(pattern, ZFileConstant.PATH_SEPARATOR)) { pattern = ZFileConstant.PATH_SEPARATOR + pattern; } // 兼容性处理. test = StringUtils.concat(test, ZFileConstant.PATH_SEPARATOR); if (StrUtil.endWith(pattern, "/**")) { test += "xxx"; } return testGlobPattern(pattern, test); }
兼容模式的 glob 表达式匹配. 默认的 glob 表达式是不支持以下情况的:<br> <ul> <li>pattern: /a/**</li> <li>test1: /a</li> <li>test2: /a/</li> <ul> <p>test1 和 test 2 均无法匹配这种情况, 此方法兼容了这种情况, 即对 test 内容后拼接 "/xx", 使其可以匹配上 pattern. <p><strong>注意:</strong>但此方法对包含文件名的情况无效, 仅支持 test 为 路径的情况. @param pattern glob 规则表达式 @param test 匹配内容 @return 是否匹配.
PatternMatcherUtils::testCompatibilityGlobPattern
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java
MIT
private static boolean testGlobPattern(String pattern, String test) { // 从缓存取出 PathMatcher, 防止重复初始化 PathMatcher pathMatcher = PATH_MATCHER_MAP.getOrDefault(pattern, FileSystems.getDefault().getPathMatcher("glob:" + pattern)); PATH_MATCHER_MAP.put(pattern, pathMatcher); return pathMatcher.matches(Paths.get(test)) || StrUtil.equals(pattern, test); }
测试密码规则表达式和文件路径是否匹配 @param pattern glob 规则表达式 @param test 测试字符串
PatternMatcherUtils::testGlobPattern
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java
MIT
public static HttpServletRequest getRequest(){ return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); }
获取 HttpServletRequest @return HttpServletRequest
RequestHolder::getRequest
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
MIT
public static HttpServletResponse getResponse(){ return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(); }
获取 HttpServletResponse @return HttpServletResponse
RequestHolder::getResponse
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
MIT
public static void writeFile(Function<String, InputStream> function, String path){ try (InputStream inputStream = function.apply(path)) { HttpServletResponse response = RequestHolder.getResponse(); String fileName = FileUtil.getName(path); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + StringUtils.encodeAllIgnoreSlashes(fileName)); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); OutputStream outputStream = response.getOutputStream(); IoUtil.copy(inputStream, outputStream); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } }
向 response 写入文件流. @param function 文件输入流获取函数 @param path 文件路径
RequestHolder::writeFile
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java
MIT
public static String trimSlashes(String path) { path = trimStartSlashes(path); path = trimEndSlashes(path); return path; }
移除 URL 中的前后的所有 '/' @param path 路径 @return 如 path = '/folder1/file1/', 返回 'folder1/file1' 如 path = '///folder1/file1//', 返回 'folder1/file1'
StringUtils::trimSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String trimStartSlashes(String path) { if (StrUtil.isEmpty(path)) { return path; } while (path.startsWith(DELIMITER_STR)) { path = path.substring(1); } return path; }
移除 URL 中的第一个 '/' @param path 路径 @return 如 path = '/folder1/file1', 返回 'folder1/file1' 如 path = '/folder1/file1', 返回 'folder1/file1'
StringUtils::trimStartSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String trimEndSlashes(String path) { if (StrUtil.isEmpty(path)) { return path; } while (path.endsWith(DELIMITER_STR)) { path = path.substring(0, path.length() - 1); } return path; }
移除 URL 中的最后一个 '/' @param path 路径 @return 如 path = '/folder1/file1/', 返回 '/folder1/file1' 如 path = '/folder1/file1///', 返回 '/folder1/file1'
StringUtils::trimEndSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String removeDuplicateSlashes(String path) { if (StrUtil.isEmpty(path)) { return path; } StringBuilder sb = new StringBuilder(); // 是否包含 http 或 https 协议信息 boolean containProtocol = StrUtil.containsAnyIgnoreCase(path, HTTP_PROTOCOL, HTTPS_PROTOCOL); if (containProtocol) { path = trimStartSlashes(path); } // 是否包含 http 协议信息 boolean startWithHttpProtocol = StrUtil.startWithIgnoreCase(path, HTTP_PROTOCOL); // 是否包含 https 协议信息 boolean startWithHttpsProtocol = StrUtil.startWithIgnoreCase(path, HTTPS_PROTOCOL); if (startWithHttpProtocol) { sb.append(HTTP_PROTOCOL); } else if (startWithHttpsProtocol) { sb.append(HTTPS_PROTOCOL); } for (int i = sb.length(); i < path.length() - 1; i++) { char current = path.charAt(i); char next = path.charAt(i + 1); if (!(current == DELIMITER && next == DELIMITER)) { sb.append(current); } } sb.append(path.charAt(path.length() - 1)); return sb.toString(); }
去除路径中所有重复的 '/' @param path 路径 @return 如 path = '/folder1//file1/', 返回 '/folder1/file1/' 如 path = '/folder1////file1///', 返回 '/folder1/file1/'
StringUtils::removeDuplicateSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String removeDuplicateSlashesAndTrimStart(String path) { path = removeDuplicateSlashes(path); path = trimStartSlashes(path); return path; }
去除路径中所有重复的 '/', 并且去除开头的 '/' @param path 路径 @return 如 path = '/folder1//file1/', 返回 'folder1/file1/' 如 path = '///folder1////file1///', 返回 'folder1/file1/'
StringUtils::removeDuplicateSlashesAndTrimStart
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String removeDuplicateSlashesAndTrimEnd(String path) { path = removeDuplicateSlashes(path); path = trimEndSlashes(path); return path; }
去除路径中所有重复的 '/', 并且去除结尾的 '/' @param path 路径 @return 如 path = '/folder1//file1/', 返回 '/folder1/file1' 如 path = '///folder1////file1///', 返回 '/folder1/file1'
StringUtils::removeDuplicateSlashesAndTrimEnd
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String concatTrimStartSlashes(String... strs) { return trimStartSlashes(concat(strs)); }
拼接 URL,并去除重复的分隔符 '/',并去除开头的 '/', 但不会影响 http:// 和 https:// 这种头部. @param strs 拼接的字符数组 @return 拼接结果
StringUtils::concatTrimStartSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String concatTrimEndSlashes(String... strs) { return trimEndSlashes(concat(strs)); }
拼接 URL,并去除重复的分隔符 '/',并去除结尾的 '/', 但不会影响 http:// 和 https:// 这种头部. @param strs 拼接的字符数组 @return 拼接结果
StringUtils::concatTrimEndSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String concatTrimSlashes(String... strs) { return trimSlashes(concat(strs)); }
拼接 URL,并去除重复的分隔符 '/',并去除开头和结尾的 '/', 但不会影响 http:// 和 https:// 这种头部. @param strs 拼接的字符数组 @return 拼接结果
StringUtils::concatTrimSlashes
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String concat(String... strs) { StringBuilder sb = new StringBuilder(DELIMITER_STR); for (int i = 0; i < strs.length; i++) { String str = strs[i]; if (StrUtil.isEmpty(str)) { continue; } sb.append(str); if (i != strs.length - 1) { sb.append(DELIMITER); } } return removeDuplicateSlashes(sb.toString()); }
拼接 URL,并去除重复的分隔符 '/',但不会影响 http:// 和 https:// 这种头部. @param strs 拼接的字符数组 @return 拼接结果
StringUtils::concat
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String concat(boolean encodeAllIgnoreSlashes, String... strs) { StringBuilder sb = new StringBuilder(DELIMITER_STR); for (int i = 0; i < strs.length; i++) { String str = strs[i]; if (StrUtil.isEmpty(str)) { continue; } sb.append(str); if (i != strs.length - 1) { sb.append(DELIMITER); } } if (encodeAllIgnoreSlashes) { return encodeAllIgnoreSlashes(removeDuplicateSlashes(sb.toString())); } else { return removeDuplicateSlashes(sb.toString()); } }
拼接 URL,并去除重复的分隔符 '/',但不会影响 http:// 和 https:// 这种头部. @param encodeAllIgnoreSlashes 是否 encode 编码 (忽略 /) @param strs 拼接的字符数组 @return 拼接结果
StringUtils::concat
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public static String generatorPathLink(String storageKey, String fullPath) { SystemConfigService systemConfigService = SpringUtil.getBean(SystemConfigService.class); SystemConfigDTO systemConfig = systemConfigService.getSystemConfig(); String domain = systemConfig.getDomain(); String directLinkPrefix = systemConfig.getDirectLinkPrefix(); return concat(domain, directLinkPrefix, storageKey, encodeAllIgnoreSlashes(fullPath)); }
拼接文件直链生成 URL @param storageKey 存储源 ID @param fullPath 文件全路径 @return 生成结果
StringUtils::generatorPathLink
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java
MIT
public HttpLoggingInterceptor setLevel(Level level) { if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead."); this.level = level; return this; }
Logs request and response lines and their respective headers and bodies (if present). <p>Example: <pre>{@code --> POST /greeting http/1.1 Host: example.com Content-Type: plain/text Content-Length: 3 Hi? --> END POST <-- 200 OK (22ms) Content-Type: plain/text Content-Length: 6 Hello! <-- END HTTP }</pre> BODY } public interface Logger { void log(String message); /** A {@link Logger} defaults output appropriate for the current platform. Logger DEFAULT = message -> Platform.get().log(message, INFO, null); Logger DEBUG = log::debug; Logger TRACE = log::trace; } public HttpLoggingInterceptor() { this(Logger.DEFAULT); } public HttpLoggingInterceptor(Logger logger) { this.logger = logger; } private final Logger logger; private volatile Set<String> headersToRedact = Collections.emptySet(); public void redactHeader(String name) { Set<String> newHeadersToRedact = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); newHeadersToRedact.addAll(headersToRedact); newHeadersToRedact.add(name); headersToRedact = newHeadersToRedact; } private volatile Level level = Level.NONE; /** Change the level at which this interceptor logs.
HttpLoggingInterceptor::setLevel
java
zfile-dev/zfile
src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java
https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java
MIT
default Review createReview(Review body){return null;}
Create a new review for a product. @param body review to be created. @return just created review.
createReview
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java
MIT
default void deleteReviews(int productId){}
Delete all product reviews. @param productId to delete its reviews.
deleteReviews
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java
MIT
default Product createProduct(Product body) { return null; }
Add product to the repository. @param body product to save. @since v0.1
createProduct
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java
MIT
default void deleteProduct(int id) {}
Delete the product from repository. @implNote This method should be idempotent and always return 200 OK status. @param id to be deleted. @since v0.1
deleteProduct
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java
MIT
default Recommendation createRecommendation(Recommendation body) { return null; }
Create a new recommendation for a product. @param body the recommendation to add. @return currently created recommendation. @since v0.1
createRecommendation
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java
MIT
default void deleteRecommendations(int productId) {}
Delete all product recommendations. @param productId to delete recommendations for. @since v0.1
deleteRecommendations
java
mohamed-taman/Springy-Store-Microservices
store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java
https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java
MIT
public String packageName() { return packageName; }
Returns the package name, like {@code "java.util"} for {@code Map.Entry}. Returns the empty string for the default package.
ClassName::packageName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public ClassName enclosingClassName() { return enclosingClassName; }
Returns the enclosing class, like {@link Map} for {@code Map.Entry}. Returns null if this class is not nested in another class.
ClassName::enclosingClassName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public ClassName topLevelClassName() { return enclosingClassName != null ? enclosingClassName.topLevelClassName() : this; }
Returns the top class in this nesting group. Equivalent to chained calls to {@link #enclosingClassName()} until the result's enclosing class is null.
ClassName::topLevelClassName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public String reflectionName() { return enclosingClassName != null ? (enclosingClassName.reflectionName() + '$' + simpleName) : (packageName.isEmpty() ? simpleName : packageName + '.' + simpleName); }
Returns the top class in this nesting group. Equivalent to chained calls to {@link #enclosingClassName()} until the result's enclosing class is null. public ClassName topLevelClassName() { return enclosingClassName != null ? enclosingClassName.topLevelClassName() : this; } /** Return the binary name of a class.
ClassName::reflectionName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public ClassName peerClass(String name) { return new ClassName(packageName, enclosingClassName, name); }
Returns a class that shares the same enclosing package or class. If this class is enclosed by another class, this is equivalent to {@code enclosingClassName().nestedClass(name)}. Otherwise it is equivalent to {@code get(packageName(), name)}.
ClassName::peerClass
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public ClassName nestedClass(String name) { return new ClassName(packageName, this, name); }
Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this class.
ClassName::nestedClass
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public String simpleName() { return simpleName; }
Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this class. public ClassName nestedClass(String name) { return new ClassName(packageName, this, name); } /** Returns the simple name of this class, like {@code "Entry"} for {@link Map.Entry}.
ClassName::simpleName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public String canonicalName() { return canonicalName; }
Returns the full class name of this class. Like {@code "java.util.Map.Entry"} for {@link Map.Entry}. *
ClassName::canonicalName
java
square/javapoet
src/main/java/com/squareup/javapoet/ClassName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java
Apache-2.0
public boolean isPrimitive() { return keyword != null && this != VOID; }
Returns true if this is a primitive type like {@code int}. Returns false for all other types types including boxed primitives and {@code void}.
TypeName::isPrimitive
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
public boolean isBoxedPrimitive() { TypeName thisWithoutAnnotations = withoutAnnotations(); return thisWithoutAnnotations.equals(BOXED_BOOLEAN) || thisWithoutAnnotations.equals(BOXED_BYTE) || thisWithoutAnnotations.equals(BOXED_SHORT) || thisWithoutAnnotations.equals(BOXED_INT) || thisWithoutAnnotations.equals(BOXED_LONG) || thisWithoutAnnotations.equals(BOXED_CHAR) || thisWithoutAnnotations.equals(BOXED_FLOAT) || thisWithoutAnnotations.equals(BOXED_DOUBLE); }
Returns true if this is a boxed primitive type like {@code Integer}. Returns false for all other types types including unboxed primitives and {@code java.lang.Void}.
TypeName::isBoxedPrimitive
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
public TypeName box() { if (keyword == null) return this; // Doesn't need boxing. TypeName boxed = null; if (keyword.equals(VOID.keyword)) boxed = BOXED_VOID; else if (keyword.equals(BOOLEAN.keyword)) boxed = BOXED_BOOLEAN; else if (keyword.equals(BYTE.keyword)) boxed = BOXED_BYTE; else if (keyword.equals(SHORT.keyword)) boxed = BOXED_SHORT; else if (keyword.equals(INT.keyword)) boxed = BOXED_INT; else if (keyword.equals(LONG.keyword)) boxed = BOXED_LONG; else if (keyword.equals(CHAR.keyword)) boxed = BOXED_CHAR; else if (keyword.equals(FLOAT.keyword)) boxed = BOXED_FLOAT; else if (keyword.equals(DOUBLE.keyword)) boxed = BOXED_DOUBLE; else throw new AssertionError(keyword); return annotations.isEmpty() ? boxed : boxed.annotated(annotations); }
Returns a boxed type if this is a primitive type (like {@code Integer} for {@code int}) or {@code void}. Returns this type if boxing doesn't apply.
TypeName::box
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
public TypeName unbox() { if (keyword != null) return this; // Already unboxed. TypeName thisWithoutAnnotations = withoutAnnotations(); TypeName unboxed = null; if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID; else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN; else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE; else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT; else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT; else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG; else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR; else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT; else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE; else throw new UnsupportedOperationException("cannot unbox " + this); return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations); }
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code Integer}) or {@code Void}. Returns this type if it is already unboxed. @throws UnsupportedOperationException if this type isn't eligible for unboxing.
TypeName::unbox
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
public static TypeName get(TypeMirror mirror) { return get(mirror, new LinkedHashMap<>()); }
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code Integer}) or {@code Void}. Returns this type if it is already unboxed. @throws UnsupportedOperationException if this type isn't eligible for unboxing. public TypeName unbox() { if (keyword != null) return this; // Already unboxed. TypeName thisWithoutAnnotations = withoutAnnotations(); TypeName unboxed = null; if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID; else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN; else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE; else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT; else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT; else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG; else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR; else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT; else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE; else throw new UnsupportedOperationException("cannot unbox " + this); return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations); } @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return toString().equals(o.toString()); } @Override public final int hashCode() { return toString().hashCode(); } @Override public final String toString() { String result = cachedString; if (result == null) { try { StringBuilder resultBuilder = new StringBuilder(); CodeWriter codeWriter = new CodeWriter(resultBuilder); emit(codeWriter); result = resultBuilder.toString(); cachedString = result; } catch (IOException e) { throw new AssertionError(); } } return result; } CodeWriter emit(CodeWriter out) throws IOException { if (keyword == null) throw new AssertionError(); if (isAnnotated()) { out.emit(""); emitAnnotations(out); } return out.emitAndIndent(keyword); } CodeWriter emitAnnotations(CodeWriter out) throws IOException { for (AnnotationSpec annotation : annotations) { annotation.emit(out, true); out.emit(" "); } return out; } /** Returns a type name equivalent to {@code mirror}.
TypeName::get
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
public static TypeName get(Type type) { return get(type, new LinkedHashMap<>()); }
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code Integer}) or {@code Void}. Returns this type if it is already unboxed. @throws UnsupportedOperationException if this type isn't eligible for unboxing. public TypeName unbox() { if (keyword != null) return this; // Already unboxed. TypeName thisWithoutAnnotations = withoutAnnotations(); TypeName unboxed = null; if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID; else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN; else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE; else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT; else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT; else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG; else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR; else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT; else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE; else throw new UnsupportedOperationException("cannot unbox " + this); return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations); } @Override public final boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return toString().equals(o.toString()); } @Override public final int hashCode() { return toString().hashCode(); } @Override public final String toString() { String result = cachedString; if (result == null) { try { StringBuilder resultBuilder = new StringBuilder(); CodeWriter codeWriter = new CodeWriter(resultBuilder); emit(codeWriter); result = resultBuilder.toString(); cachedString = result; } catch (IOException e) { throw new AssertionError(); } } return result; } CodeWriter emit(CodeWriter out) throws IOException { if (keyword == null) throw new AssertionError(); if (isAnnotated()) { out.emit(""); emitAnnotations(out); } return out.emitAndIndent(keyword); } CodeWriter emitAnnotations(CodeWriter out) throws IOException { for (AnnotationSpec annotation : annotations) { annotation.emit(out, true); out.emit(" "); } return out; } /** Returns a type name equivalent to {@code mirror}. public static TypeName get(TypeMirror mirror) { return get(mirror, new LinkedHashMap<>()); } static TypeName get(TypeMirror mirror, final Map<TypeParameterElement, TypeVariableName> typeVariables) { return mirror.accept(new SimpleTypeVisitor8<TypeName, Void>() { @Override public TypeName visitPrimitive(PrimitiveType t, Void p) { switch (t.getKind()) { case BOOLEAN: return TypeName.BOOLEAN; case BYTE: return TypeName.BYTE; case SHORT: return TypeName.SHORT; case INT: return TypeName.INT; case LONG: return TypeName.LONG; case CHAR: return TypeName.CHAR; case FLOAT: return TypeName.FLOAT; case DOUBLE: return TypeName.DOUBLE; default: throw new AssertionError(); } } @Override public TypeName visitDeclared(DeclaredType t, Void p) { ClassName rawType = ClassName.get((TypeElement) t.asElement()); TypeMirror enclosingType = t.getEnclosingType(); TypeName enclosing = (enclosingType.getKind() != TypeKind.NONE) && !t.asElement().getModifiers().contains(Modifier.STATIC) ? enclosingType.accept(this, null) : null; if (t.getTypeArguments().isEmpty() && !(enclosing instanceof ParameterizedTypeName)) { return rawType; } List<TypeName> typeArgumentNames = new ArrayList<>(); for (TypeMirror mirror : t.getTypeArguments()) { typeArgumentNames.add(get(mirror, typeVariables)); } return enclosing instanceof ParameterizedTypeName ? ((ParameterizedTypeName) enclosing).nestedClass( rawType.simpleName(), typeArgumentNames) : new ParameterizedTypeName(null, rawType, typeArgumentNames); } @Override public TypeName visitError(ErrorType t, Void p) { return visitDeclared(t, p); } @Override public ArrayTypeName visitArray(ArrayType t, Void p) { return ArrayTypeName.get(t, typeVariables); } @Override public TypeName visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) { return TypeVariableName.get(t, typeVariables); } @Override public TypeName visitWildcard(javax.lang.model.type.WildcardType t, Void p) { return WildcardTypeName.get(t, typeVariables); } @Override public TypeName visitNoType(NoType t, Void p) { if (t.getKind() == TypeKind.VOID) return TypeName.VOID; return super.visitUnknown(t, p); } @Override protected TypeName defaultAction(TypeMirror e, Void p) { throw new IllegalArgumentException("Unexpected type mirror: " + e); } }, null); } /** Returns a type name equivalent to {@code type}.
TypeName::get
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeName.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java
Apache-2.0
private TypeSpec(TypeSpec type) { assert type.anonymousTypeArguments == null; this.kind = type.kind; this.name = type.name; this.anonymousTypeArguments = null; this.javadoc = type.javadoc; this.annotations = Collections.emptyList(); this.modifiers = Collections.emptySet(); this.typeVariables = Collections.emptyList(); this.superclass = null; this.superinterfaces = Collections.emptyList(); this.enumConstants = Collections.emptyMap(); this.fieldSpecs = Collections.emptyList(); this.staticBlock = type.staticBlock; this.initializerBlock = type.initializerBlock; this.methodSpecs = Collections.emptyList(); this.typeSpecs = Collections.emptyList(); this.originatingElements = Collections.emptyList(); this.nestedTypesSimpleNames = Collections.emptySet(); this.alwaysQualifiedNames = Collections.emptySet(); }
Creates a dummy type spec for type-resolution only (in CodeWriter) while emitting the type declaration but before entering the type body.
TypeSpec::TypeSpec
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeSpec.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeSpec.java
Apache-2.0
public Builder avoidClashesWithNestedClasses(TypeElement typeElement) { checkArgument(typeElement != null, "typeElement == null"); for (TypeElement nestedType : ElementFilter.typesIn(typeElement.getEnclosedElements())) { alwaysQualify(nestedType.getSimpleName().toString()); } TypeMirror superclass = typeElement.getSuperclass(); if (!(superclass instanceof NoType) && superclass instanceof DeclaredType) { TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement(); avoidClashesWithNestedClasses(superclassElement); } for (TypeMirror superinterface : typeElement.getInterfaces()) { if (superinterface instanceof DeclaredType) { TypeElement superinterfaceElement = (TypeElement) ((DeclaredType) superinterface).asElement(); avoidClashesWithNestedClasses(superinterfaceElement); } } return this; }
Call this to always fully qualify any types that would conflict with possibly nested types of this {@code typeElement}. For example - if the following type was passed in as the typeElement: <pre><code> class Foo { class NestedTypeA { } class NestedTypeB { } } </code></pre> <p> Then this would add {@code "NestedTypeA"} and {@code "NestedTypeB"} as names that should always be qualified via {@link #alwaysQualify(String...)}. This way they would avoid possible import conflicts when this JavaFile is written. @param typeElement the {@link TypeElement} with nested types to avoid clashes with. @return this builder instance.
Builder::avoidClashesWithNestedClasses
java
square/javapoet
src/main/java/com/squareup/javapoet/TypeSpec.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeSpec.java
Apache-2.0
public void emitModifiers(Set<Modifier> modifiers, Set<Modifier> implicitModifiers) throws IOException { if (modifiers.isEmpty()) return; for (Modifier modifier : EnumSet.copyOf(modifiers)) { if (implicitModifiers.contains(modifier)) continue; emitAndIndent(modifier.name().toLowerCase(Locale.US)); emitAndIndent(" "); } }
Emits {@code modifiers} in the standard order. Modifiers in {@code implicitModifiers} will not be emitted.
CodeWriter::emitModifiers
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
public void emitTypeVariables(List<TypeVariableName> typeVariables) throws IOException { if (typeVariables.isEmpty()) return; typeVariables.forEach(typeVariable -> currentTypeVariables.add(typeVariable.name)); emit("<"); boolean firstTypeVariable = true; for (TypeVariableName typeVariable : typeVariables) { if (!firstTypeVariable) emit(", "); emitAnnotations(typeVariable.annotations, true); emit("$L", typeVariable.name); boolean firstBound = true; for (TypeName bound : typeVariable.bounds) { emit(firstBound ? " extends $T" : " & $T", bound); firstBound = false; } firstTypeVariable = false; } emit(">"); }
Emit type variables with their bounds. This should only be used when declaring type variables; everywhere else bounds are omitted.
CodeWriter::emitTypeVariables
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
String lookupName(ClassName className) { // If the top level simple name is masked by a current type variable, use the canonical name. String topLevelSimpleName = className.topLevelClassName().simpleName(); if (currentTypeVariables.contains(topLevelSimpleName)) { return className.canonicalName; } // Find the shortest suffix of className that resolves to className. This uses both local type // names (so `Entry` in `Map` refers to `Map.Entry`). Also uses imports. boolean nameResolved = false; for (ClassName c = className; c != null; c = c.enclosingClassName()) { ClassName resolved = resolve(c.simpleName()); nameResolved = resolved != null; if (resolved != null && Objects.equals(resolved.canonicalName, c.canonicalName)) { int suffixOffset = c.simpleNames().size() - 1; return join(".", className.simpleNames().subList( suffixOffset, className.simpleNames().size())); } } // If the name resolved but wasn't a match, we're stuck with the fully qualified name. if (nameResolved) { return className.canonicalName; } // If the class is in the same package, we're done. if (Objects.equals(packageName, className.packageName())) { referencedNames.add(topLevelSimpleName); return join(".", className.simpleNames()); } // We'll have to use the fully-qualified name. Mark the type as importable for a future pass. if (!javadoc) { importableType(className); } return className.canonicalName; }
Returns the best name to identify {@code className} with in the current context. This uses the available imports and the current scope to find the shortest name available. It does not honor names visible due to inheritance.
CodeWriter::lookupName
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
private ClassName stackClassName(int stackDepth, String simpleName) { ClassName className = ClassName.get(packageName, typeSpecStack.get(0).name); for (int i = 1; i <= stackDepth; i++) { className = className.nestedClass(typeSpecStack.get(i).name); } return className.nestedClass(simpleName); }
Returns the class referenced by {@code simpleName}, using the current nesting context and imports. // TODO(jwilson): also honor superclass members when resolving names. private ClassName resolve(String simpleName) { // Match a child of the current (potentially nested) class. for (int i = typeSpecStack.size() - 1; i >= 0; i--) { TypeSpec typeSpec = typeSpecStack.get(i); if (typeSpec.nestedTypesSimpleNames.contains(simpleName)) { return stackClassName(i, simpleName); } } // Match the top-level class. if (typeSpecStack.size() > 0 && Objects.equals(typeSpecStack.get(0).name, simpleName)) { return ClassName.get(packageName, simpleName); } // Match an imported type. ClassName importedType = importedTypes.get(simpleName); if (importedType != null) return importedType; // No match. return null; } /** Returns the class named {@code simpleName} when nested in the class at {@code stackDepth}.
CodeWriter::stackClassName
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
CodeWriter emitAndIndent(String s) throws IOException { boolean first = true; for (String line : LINE_BREAKING_PATTERN.split(s, -1)) { // Emit a newline character. Make sure blank lines in Javadoc & comments look good. if (!first) { if ((javadoc || comment) && trailingNewline) { emitIndentation(); out.append(javadoc ? " *" : "//"); } out.append("\n"); trailingNewline = true; if (statementLine != -1) { if (statementLine == 0) { indent(2); // Begin multiple-line statement. Increase the indentation level. } statementLine++; } } first = false; if (line.isEmpty()) continue; // Don't indent empty lines. // Emit indentation and comment prefix if necessary. if (trailingNewline) { emitIndentation(); if (javadoc) { out.append(" * "); } else if (comment) { out.append("// "); } } out.append(line); trailingNewline = false; } return this; }
Emits {@code s} with indentation as required. It's important that all code that writes to {@link #out} does it through here, since we emit indentation lazily in order to avoid unnecessary trailing whitespace.
CodeWriter::emitAndIndent
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
Map<String, ClassName> suggestedImports() { Map<String, ClassName> result = new LinkedHashMap<>(importableTypes); result.keySet().removeAll(referencedNames); return result; }
Returns the types that should have been imported for this code. If there were any simple name collisions, that type's first use is imported.
CodeWriter::suggestedImports
java
square/javapoet
src/main/java/com/squareup/javapoet/CodeWriter.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java
Apache-2.0
public String newName(String suggestion) { return newName(suggestion, UUID.randomUUID().toString()); }
Return a new name using {@code suggestion} that will not be a Java identifier or clash with other names.
NameAllocator::newName
java
square/javapoet
src/main/java/com/squareup/javapoet/NameAllocator.java
https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java
Apache-2.0