pref: clean unnecessary code. (#1237)

* pref: clean unnecessary code.

* chore: change org.jetbrains.annotations.NotNull to org.springframework.lang.NonNull.
pull/1241/head
Ryan Wang 2021-01-24 14:53:32 +08:00 committed by GitHub
parent 8bb416db1a
commit de5e968025
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 65 additions and 308 deletions

View File

@ -49,7 +49,7 @@ public abstract class AbstractCacheStore<K, V> implements CacheStore<K, V> {
abstract Boolean putInternalIfAbsent(@NonNull K key, @NonNull CacheWrapper<V> cacheWrapper); abstract Boolean putInternalIfAbsent(@NonNull K key, @NonNull CacheWrapper<V> cacheWrapper);
@Override @Override
public Optional<V> get(K key) { public @NonNull Optional<V> get(@NonNull K key) {
Assert.notNull(key, "Cache key must not be blank"); Assert.notNull(key, "Cache key must not be blank");
return getInternal(key).map(cacheWrapper -> { return getInternal(key).map(cacheWrapper -> {
@ -70,17 +70,17 @@ public abstract class AbstractCacheStore<K, V> implements CacheStore<K, V> {
} }
@Override @Override
public void put(K key, V value, long timeout, TimeUnit timeUnit) { public void put(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit) {
putInternal(key, buildCacheWrapper(value, timeout, timeUnit)); putInternal(key, buildCacheWrapper(value, timeout, timeUnit));
} }
@Override @Override
public Boolean putIfAbsent(K key, V value, long timeout, TimeUnit timeUnit) { public Boolean putIfAbsent(@NonNull K key, @NonNull V value, long timeout, @NonNull TimeUnit timeUnit) {
return putInternalIfAbsent(key, buildCacheWrapper(value, timeout, timeUnit)); return putInternalIfAbsent(key, buildCacheWrapper(value, timeout, timeUnit));
} }
@Override @Override
public void put(K key, V value) { public void put(@NonNull K key, @NonNull V value) {
putInternal(key, buildCacheWrapper(value, 0, null)); putInternal(key, buildCacheWrapper(value, 0, null));
} }

View File

@ -1,6 +1,7 @@
package run.halo.app.cache; package run.halo.app.cache;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
@ -43,14 +44,15 @@ public class InMemoryCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
Optional<CacheWrapper<String>> getInternal(String key) { @NonNull
Optional<CacheWrapper<String>> getInternal(@NonNull String key) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
return Optional.ofNullable(CACHE_CONTAINER.get(key)); return Optional.ofNullable(CACHE_CONTAINER.get(key));
} }
@Override @Override
void putInternal(String key, CacheWrapper<String> cacheWrapper) { void putInternal(@NonNull String key, @NonNull CacheWrapper<String> cacheWrapper) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); Assert.notNull(cacheWrapper, "Cache wrapper must not be null");
@ -61,7 +63,7 @@ public class InMemoryCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
Boolean putInternalIfAbsent(String key, CacheWrapper<String> cacheWrapper) { Boolean putInternalIfAbsent(@NonNull String key, @NonNull CacheWrapper<String> cacheWrapper) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); Assert.notNull(cacheWrapper, "Cache wrapper must not be null");
@ -87,7 +89,7 @@ public class InMemoryCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
public void delete(String key) { public void delete(@NonNull String key) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
CACHE_CONTAINER.remove(key); CACHE_CONTAINER.remove(key);

View File

@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.iq80.leveldb.*; import org.iq80.leveldb.*;
import org.iq80.leveldb.impl.Iq80DBFactory; import org.iq80.leveldb.impl.Iq80DBFactory;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import run.halo.app.config.properties.HaloProperties; import run.halo.app.config.properties.HaloProperties;
@ -69,7 +70,8 @@ public class LevelCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
Optional<CacheWrapper<String>> getInternal(String key) { @NonNull
Optional<CacheWrapper<String>> getInternal(@NonNull String key) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
byte[] bytes = LEVEL_DB.get(stringToBytes(key)); byte[] bytes = LEVEL_DB.get(stringToBytes(key));
if (bytes != null) { if (bytes != null) {
@ -80,12 +82,12 @@ public class LevelCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
void putInternal(String key, CacheWrapper<String> cacheWrapper) { void putInternal(@NonNull String key, @NonNull CacheWrapper<String> cacheWrapper) {
putInternalIfAbsent(key, cacheWrapper); putInternalIfAbsent(key, cacheWrapper);
} }
@Override @Override
Boolean putInternalIfAbsent(String key, CacheWrapper<String> cacheWrapper) { Boolean putInternalIfAbsent(@NonNull String key, @NonNull CacheWrapper<String> cacheWrapper) {
Assert.hasText(key, "Cache key must not be blank"); Assert.hasText(key, "Cache key must not be blank");
Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); Assert.notNull(cacheWrapper, "Cache wrapper must not be null");
try { try {
@ -102,7 +104,7 @@ public class LevelCacheStore extends AbstractStringCacheStore {
} }
@Override @Override
public void delete(String key) { public void delete(@NonNull String key) {
LEVEL_DB.delete(stringToBytes(key)); LEVEL_DB.delete(stringToBytes(key));
log.debug("cache remove key: [{}]", key); log.debug("cache remove key: [{}]", key);
} }

View File

@ -5,8 +5,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import run.halo.app.model.enums.Mode; import run.halo.app.model.enums.Mode;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import static run.halo.app.model.support.HaloConst.*; import static run.halo.app.model.support.HaloConst.*;
import static run.halo.app.utils.HaloUtils.ensureSuffix; import static run.halo.app.utils.HaloUtils.ensureSuffix;
@ -84,19 +82,4 @@ public class HaloProperties {
* level * level
*/ */
private String cache = "memory"; private String cache = "memory";
private List<String> cacheRedisNodes = new ArrayList<>();
private String cacheRedisPassword = "";
/**
* hazelcast cache store impl
* memory
* level
*/
private List<String> hazelcastMembers = new ArrayList<>();
private String hazelcastGroupName;
private int initialBackoffSeconds = 5;
} }

View File

@ -106,13 +106,6 @@ public class AdminController {
return adminService.getEnvironments(); return adminService.getEnvironments();
} }
@PutMapping("halo-admin")
@ApiOperation("Updates halo-admin manually")
@Deprecated
public void updateAdmin() {
adminService.updateAdminAssets();
}
@GetMapping(value = "halo/logfile") @GetMapping(value = "halo/logfile")
@ApiOperation("Gets halo log file content") @ApiOperation("Gets halo log file content")
@DisableOnCondition @DisableOnCondition

View File

@ -1,6 +1,6 @@
package run.halo.app.core; package run.halo.app.core;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.core.MethodParameter; import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -9,7 +9,6 @@ import org.springframework.http.converter.json.AbstractJackson2HttpMessageConver
import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ -24,18 +23,18 @@ import run.halo.app.model.support.BaseResponse;
public class CommonResultControllerAdvice implements ResponseBodyAdvice<Object> { public class CommonResultControllerAdvice implements ResponseBodyAdvice<Object> {
@Override @Override
public boolean supports(MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) { public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType); return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
} }
@Override @Override
@NonNull @NonNull
public final Object beforeBodyWrite(@Nullable Object body, public final Object beforeBodyWrite(@Nullable Object body,
@NotNull MethodParameter returnType, @NonNull MethodParameter returnType,
@NotNull MediaType contentType, @NonNull MediaType contentType,
@NotNull Class<? extends HttpMessageConverter<?>> converterType, @NonNull Class<? extends HttpMessageConverter<?>> converterType,
@NotNull ServerHttpRequest request, @NonNull ServerHttpRequest request,
@NotNull ServerHttpResponse response) { @NonNull ServerHttpResponse response) {
MappingJacksonValue container = getOrCreateContainer(body); MappingJacksonValue container = getOrCreateContainer(body);
// The contain body will never be null // The contain body will never be null
beforeBodyWriteInternal(container, contentType, returnType, request, response); beforeBodyWriteInternal(container, contentType, returnType, request, response);

View File

@ -1,9 +1,8 @@
package run.halo.app.factory; package run.halo.app.factory;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory; import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
@ -15,7 +14,7 @@ public class StringToEnumConverterFactory implements ConverterFactory<String, En
@Override @Override
@NonNull @NonNull
public <T extends Enum<?>> Converter<String, T> getConverter(@NotNull Class<T> targetType) { public <T extends Enum<?>> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
return new StringToEnumConverter(targetType); return new StringToEnumConverter(targetType);
} }

View File

@ -6,7 +6,7 @@ import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.PutObjectResult; import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -41,7 +41,7 @@ public class AliOssFileHandler implements FileHandler {
} }
@Override @Override
public @NotNull UploadResult upload(@NotNull MultipartFile file) { public @NonNull UploadResult upload(@NonNull MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
@ -127,7 +127,7 @@ public class AliOssFileHandler implements FileHandler {
} }
@Override @Override
public void delete(@NotNull String key) { public void delete(@NonNull String key) {
Assert.notNull(key, "File key must not be blank"); Assert.notNull(key, "File key must not be blank");
// Get config // Get config

View File

@ -4,7 +4,7 @@ import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult; import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -39,7 +39,7 @@ public class HuaweiObsFileHandler implements FileHandler {
} }
@Override @Override
public @NotNull UploadResult upload(@NotNull MultipartFile file) { public @NonNull UploadResult upload(@NonNull MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
@ -126,7 +126,7 @@ public class HuaweiObsFileHandler implements FileHandler {
} }
@Override @Override
public void delete(@NotNull String key) { public void delete(@NonNull String key) {
Assert.notNull(key, "File key must not be blank"); Assert.notNull(key, "File key must not be blank");
// Get config // Get config

View File

@ -5,7 +5,7 @@ import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs; import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -37,9 +37,9 @@ public class MinioFileHandler implements FileHandler {
this.optionService = optionService; this.optionService = optionService;
} }
@NotNull @NonNull
@Override @Override
public UploadResult upload(@NotNull MultipartFile file) { public UploadResult upload(@NonNull MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null"); Assert.notNull(file, "Multipart file must not be null");
// Get config // Get config
String endpoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString(); String endpoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString();
@ -90,7 +90,7 @@ public class MinioFileHandler implements FileHandler {
} }
@Override @Override
public void delete(@NotNull String key) { public void delete(@NonNull String key) {
Assert.notNull(key, "File key must not be blank"); Assert.notNull(key, "File key must not be blank");
String endPoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString(); String endPoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString();

View File

@ -109,16 +109,6 @@ public class HaloConst {
* YouTube * YouTube
*/ */
public static final String YOUTUBE_VIDEO_REG_PATTERN = "\\[youtube:(\\w+)\\,(\\d+)\\,(\\d+)\\]"; public static final String YOUTUBE_VIDEO_REG_PATTERN = "\\[youtube:(\\w+)\\,(\\d+)\\,(\\d+)\\]";
/**
* Github Api url for halo-admin release.
*/
public final static String HALO_ADMIN_RELEASES_LATEST = "https://api.github.com/repos/halo-dev/halo-admin/releases/latest";
/**
* Halo admin version regex.
*/
public final static String HALO_ADMIN_VERSION_REGEX = "halo-admin-\\d+\\.\\d+(\\.\\d+)?(-\\S*)?\\.zip";
public final static String HALO_ADMIN_RELATIVE_PATH = "templates/admin/";
public final static String HALO_ADMIN_RELATIVE_BACKUP_PATH = "templates/admin-backup/";
/** /**
* Content token header name. * Content token header name.
*/ */
@ -131,10 +121,6 @@ public class HaloConst {
* Admin token param name. * Admin token param name.
*/ */
public final static String ADMIN_TOKEN_QUERY_NAME = "admin_token"; public final static String ADMIN_TOKEN_QUERY_NAME = "admin_token";
/**
* Temporary token.
*/
public final static String TEMP_TOKEN = "temp_token";
/** /**
* Content api token param name * Content api token param name
*/ */
@ -155,10 +141,6 @@ public class HaloConst {
* Database product name. * Database product name.
*/ */
public static String DATABASE_PRODUCT_NAME = null; public static String DATABASE_PRODUCT_NAME = null;
/**
* user_session
*/
public static String USER_SESSION_KEY = "user_session";
static { static {
// Set version // Set version

View File

@ -90,11 +90,6 @@ public interface AdminService {
@NonNull @NonNull
AuthToken refreshToken(@NonNull String refreshToken); AuthToken refreshToken(@NonNull String refreshToken);
/**
* Updates halo admin assets.
*/
void updateAdminAssets();
/** /**
* Get halo logs content. * Get halo logs content.
* *

View File

@ -6,7 +6,6 @@ import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -35,7 +34,6 @@ import run.halo.app.security.context.SecurityContextHolder;
import run.halo.app.security.token.AuthToken; import run.halo.app.security.token.AuthToken;
import run.halo.app.security.util.SecurityUtils; import run.halo.app.security.util.SecurityUtils;
import run.halo.app.service.*; import run.halo.app.service.*;
import run.halo.app.utils.FileUtils;
import run.halo.app.utils.HaloUtils; import run.halo.app.utils.HaloUtils;
import run.halo.app.utils.TwoFactorAuthUtils; import run.halo.app.utils.TwoFactorAuthUtils;
@ -44,16 +42,12 @@ import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import static run.halo.app.model.support.HaloConst.*; import static run.halo.app.model.support.HaloConst.DATABASE_PRODUCT_NAME;
/** /**
* Admin service implementation. * Admin service implementation.
@ -340,101 +334,6 @@ public class AdminServiceImpl implements AdminService {
return buildAuthToken(user); return buildAuthToken(user);
} }
@Override
@SuppressWarnings("unchecked")
public void updateAdminAssets() {
// Request github api
ResponseEntity<Map> responseEntity = restTemplate.getForEntity(HaloConst.HALO_ADMIN_RELEASES_LATEST, Map.class);
if (responseEntity.getStatusCode().isError() || responseEntity.getBody() == null) {
log.debug("Failed to request remote url: [{}]", HALO_ADMIN_RELEASES_LATEST);
throw new ServiceException("系统无法访问到 Github 的 API").setErrorData(HALO_ADMIN_RELEASES_LATEST);
}
Object assetsObject = responseEntity.getBody().get("assets");
if (!(assetsObject instanceof List)) {
throw new ServiceException("Github API 返回内容有误").setErrorData(assetsObject);
}
try {
List<?> assets = (List<?>) assetsObject;
Map assetMap = (Map) assets.stream()
.filter(assetPredicate())
.findFirst()
.orElseThrow(() -> new ServiceException("Halo admin 最新版暂无资源文件,请稍后再试"));
Object browserDownloadUrl = assetMap.getOrDefault("browser_download_url", "");
// Download the assets
ResponseEntity<byte[]> downloadResponseEntity = restTemplate.getForEntity(browserDownloadUrl.toString(), byte[].class);
if (downloadResponseEntity.getStatusCode().isError() || downloadResponseEntity.getBody() == null) {
throw new ServiceException("Failed to request remote url: " + browserDownloadUrl.toString()).setErrorData(browserDownloadUrl.toString());
}
String adminTargetName = haloProperties.getWorkDir() + HALO_ADMIN_RELATIVE_PATH;
Path adminPath = Paths.get(adminTargetName);
Path adminBackupPath = Paths.get(haloProperties.getWorkDir(), HALO_ADMIN_RELATIVE_BACKUP_PATH);
backupAndClearAdminAssetsIfPresent(adminPath, adminBackupPath);
// Create temp folder
Path assetTempPath = FileUtils.createTempDirectory()
.resolve(assetMap.getOrDefault("name", "halo-admin-latest.zip").toString());
// Unzip
FileUtils.unzip(downloadResponseEntity.getBody(), assetTempPath);
// find root folder
Path adminRootPath = FileUtils.findRootPath(assetTempPath,
path -> StringUtils.equalsIgnoreCase("index.html", path.getFileName().toString()))
.orElseThrow(() -> new BadRequestException("无法准确定位到压缩包的根路径,请确认包含 index.html 文件。"));
// Copy it to template/admin folder
FileUtils.copyFolder(adminRootPath, adminPath);
} catch (Throwable t) {
throw new ServiceException("更新 Halo admin 失败," + t.getMessage(), t);
}
}
@NonNull
@SuppressWarnings("unchecked")
private Predicate<Object> assetPredicate() {
return asset -> {
if (!(asset instanceof Map)) {
return false;
}
Map aAssetMap = (Map) asset;
// Get content-type
String contentType = aAssetMap.getOrDefault("content_type", "").toString();
Object name = aAssetMap.getOrDefault("name", "");
return name.toString().matches(HALO_ADMIN_VERSION_REGEX) && "application/zip".equalsIgnoreCase(contentType);
};
}
private void backupAndClearAdminAssetsIfPresent(@NonNull Path sourcePath, @NonNull Path backupPath) throws IOException {
Assert.notNull(sourcePath, "Source path must not be null");
Assert.notNull(backupPath, "Backup path must not be null");
if (!FileUtils.isEmpty(sourcePath)) {
// Clone this assets
Path adminPathBackup = Paths.get(haloProperties.getWorkDir(), HALO_ADMIN_RELATIVE_BACKUP_PATH);
// Delete backup
FileUtils.deleteFolder(backupPath);
// Copy older assets into backup
FileUtils.copyFolder(sourcePath, backupPath);
// Delete older assets
FileUtils.deleteFolder(sourcePath);
} else {
FileUtils.createIfAbsent(sourcePath);
}
}
/** /**
* Builds authentication token. * Builds authentication token.
* *

View File

@ -2,7 +2,7 @@ package run.halo.app.service.impl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@ -37,7 +37,7 @@ public abstract class BaseMetaServiceImpl<META extends BaseMeta> extends Abstrac
@Override @Override
@Transactional @Transactional
public List<META> createOrUpdateByPostId(@NotNull Integer postId, Set<META> metas) { public List<META> createOrUpdateByPostId(@NonNull Integer postId, Set<META> metas) {
Assert.notNull(postId, "Post id must not be null"); Assert.notNull(postId, "Post id must not be null");
// firstly remove post metas by post id // firstly remove post metas by post id
@ -58,13 +58,13 @@ public abstract class BaseMetaServiceImpl<META extends BaseMeta> extends Abstrac
} }
@Override @Override
public List<META> removeByPostId(@NotNull Integer postId) { public List<META> removeByPostId(@NonNull Integer postId) {
Assert.notNull(postId, "Post id must not be null of removeByPostId"); Assert.notNull(postId, "Post id must not be null of removeByPostId");
return baseMetaRepository.deleteByPostId(postId); return baseMetaRepository.deleteByPostId(postId);
} }
@Override @Override
public Map<Integer, List<META>> listPostMetaAsMap(@NotNull Set<Integer> postIds) { public Map<Integer, List<META>> listPostMetaAsMap(@NonNull Set<Integer> postIds) {
Assert.notNull(postIds, "Post ids must not be null"); Assert.notNull(postIds, "Post ids must not be null");
if (CollectionUtils.isEmpty(postIds)) { if (CollectionUtils.isEmpty(postIds)) {
return Collections.emptyMap(); return Collections.emptyMap();
@ -87,13 +87,13 @@ public abstract class BaseMetaServiceImpl<META extends BaseMeta> extends Abstrac
} }
@Override @Override
public @NotNull List<META> listBy(@NotNull Integer postId) { public @NonNull List<META> listBy(@NonNull Integer postId) {
Assert.notNull(postId, "Post id must not be null"); Assert.notNull(postId, "Post id must not be null");
return baseMetaRepository.findAllByPostId(postId); return baseMetaRepository.findAllByPostId(postId);
} }
@Override @Override
public @NotNull META create(@NotNull META meta) { public @NonNull META create(@NonNull META meta) {
Assert.notNull(meta, "Domain must not be null"); Assert.notNull(meta, "Domain must not be null");
// Check post id // Check post id
@ -106,7 +106,7 @@ public abstract class BaseMetaServiceImpl<META extends BaseMeta> extends Abstrac
} }
@Override @Override
public @NotNull META createBy(@NotNull BaseMetaParam<META> metaParam) { public @NonNull META createBy(@NonNull BaseMetaParam<META> metaParam) {
Assert.notNull(metaParam, "Meta param must not be null"); Assert.notNull(metaParam, "Meta param must not be null");
return create(metaParam.convertTo()); return create(metaParam.convertTo());
} }
@ -118,14 +118,14 @@ public abstract class BaseMetaServiceImpl<META extends BaseMeta> extends Abstrac
@Override @Override
public @NotNull BaseMetaDTO convertTo(@NotNull META postMeta) { public @NonNull BaseMetaDTO convertTo(@NonNull META postMeta) {
Assert.notNull(postMeta, "Category must not be null"); Assert.notNull(postMeta, "Category must not be null");
return new BaseMetaDTO().convertFrom(postMeta); return new BaseMetaDTO().convertFrom(postMeta);
} }
@Override @Override
public @NotNull List<BaseMetaDTO> convertTo(@NotNull List<META> postMetaList) { public @NonNull List<BaseMetaDTO> convertTo(@NonNull List<META> postMetaList) {
if (CollectionUtils.isEmpty(postMetaList)) { if (CollectionUtils.isEmpty(postMetaList)) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -1,6 +1,5 @@
package run.halo.app.service.impl; package run.halo.app.service.impl;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Example; import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
@ -38,14 +37,14 @@ public class LinkServiceImpl extends AbstractCrudService<Link, Integer> implemen
} }
@Override @Override
public @NotNull List<LinkDTO> listDtos(@NotNull Sort sort) { public @NonNull List<LinkDTO> listDtos(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
return convertTo(listAll(sort)); return convertTo(listAll(sort));
} }
@Override @Override
public @NotNull List<LinkTeamVO> listTeamVos(@NotNull Sort sort) { public @NonNull List<LinkTeamVO> listTeamVos(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
// List all links // List all links
@ -74,7 +73,7 @@ public class LinkServiceImpl extends AbstractCrudService<Link, Integer> implemen
} }
@Override @Override
public @NotNull List<LinkTeamVO> listTeamVosByRandom(@NotNull Sort sort) { public @NonNull List<LinkTeamVO> listTeamVosByRandom(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
List<LinkDTO> links = listDtos(sort); List<LinkDTO> links = listDtos(sort);
Set<String> teams = ServiceUtils.fetchProperty(links, LinkDTO::getTeam); Set<String> teams = ServiceUtils.fetchProperty(links, LinkDTO::getTeam);
@ -91,7 +90,7 @@ public class LinkServiceImpl extends AbstractCrudService<Link, Integer> implemen
} }
@Override @Override
public @NotNull Link createBy(@NotNull LinkParam linkParam) { public @NonNull Link createBy(@NonNull LinkParam linkParam) {
Assert.notNull(linkParam, "Link param must not be null"); Assert.notNull(linkParam, "Link param must not be null");
// Check the name // Check the name
@ -112,7 +111,7 @@ public class LinkServiceImpl extends AbstractCrudService<Link, Integer> implemen
} }
@Override @Override
public @NotNull Link updateBy(Integer id, @NotNull LinkParam linkParam) { public @NonNull Link updateBy(Integer id, @NonNull LinkParam linkParam) {
Assert.notNull(id, "Id must not be null"); Assert.notNull(id, "Id must not be null");
Assert.notNull(linkParam, "Link param must not be null"); Assert.notNull(linkParam, "Link param must not be null");
@ -158,7 +157,7 @@ public class LinkServiceImpl extends AbstractCrudService<Link, Integer> implemen
} }
@Override @Override
public @NotNull List<Link> listAllByRandom() { public @NonNull List<Link> listAllByRandom() {
List<Link> allLink = linkRepository.findAll(); List<Link> allLink = linkRepository.findAll();
Collections.shuffle(allLink); Collections.shuffle(allLink);
return allLink; return allLink;

View File

@ -1,6 +1,5 @@
package run.halo.app.service.impl; package run.halo.app.service.impl;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -37,14 +36,14 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public @NotNull List<MenuDTO> listDtos(@NotNull Sort sort) { public @NonNull List<MenuDTO> listDtos(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
return convertTo(listAll(sort)); return convertTo(listAll(sort));
} }
@Override @Override
public @NotNull List<MenuTeamVO> listTeamVos(@NotNull Sort sort) { public @NonNull List<MenuTeamVO> listTeamVos(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
// List all menus // List all menus
@ -73,13 +72,13 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public List<MenuDTO> listByTeam(@NotNull String team, Sort sort) { public List<MenuDTO> listByTeam(@NonNull String team, Sort sort) {
List<Menu> menus = menuRepository.findByTeam(team, sort); List<Menu> menus = menuRepository.findByTeam(team, sort);
return menus.stream().map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)).collect(Collectors.toList()); return menus.stream().map(menu -> (MenuDTO) new MenuDTO().convertFrom(menu)).collect(Collectors.toList());
} }
@Override @Override
public List<MenuVO> listByTeamAsTree(@NotNull String team, Sort sort) { public List<MenuVO> listByTeamAsTree(@NonNull String team, Sort sort) {
Assert.notNull(team, "Team must not be null"); Assert.notNull(team, "Team must not be null");
List<Menu> menus = menuRepository.findByTeam(team, sort); List<Menu> menus = menuRepository.findByTeam(team, sort);
@ -96,7 +95,7 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public @NotNull Menu createBy(@NotNull MenuParam menuParam) { public @NonNull Menu createBy(@NonNull MenuParam menuParam) {
Assert.notNull(menuParam, "Menu param must not be null"); Assert.notNull(menuParam, "Menu param must not be null");
// Create an return // Create an return
@ -104,7 +103,7 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public List<MenuVO> listAsTree(@NotNull Sort sort) { public List<MenuVO> listAsTree(@NonNull Sort sort) {
Assert.notNull(sort, "Sort info must not be null"); Assert.notNull(sort, "Sort info must not be null");
// List all menu // List all menu
@ -124,7 +123,7 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public List<Menu> listByParentId(@NotNull Integer id) { public List<Menu> listByParentId(@NonNull Integer id) {
Assert.notNull(id, "Menu parent id must not be null"); Assert.notNull(id, "Menu parent id must not be null");
return menuRepository.findByParentId(id); return menuRepository.findByParentId(id);
@ -136,12 +135,12 @@ public class MenuServiceImpl extends AbstractCrudService<Menu, Integer> implemen
} }
@Override @Override
public @NotNull Menu create(@NotNull Menu menu) { public @NonNull Menu create(@NonNull Menu menu) {
return super.create(menu); return super.create(menu);
} }
@Override @Override
public @NotNull Menu update(@NotNull Menu menu) { public @NonNull Menu update(@NonNull Menu menu) {
return super.update(menu); return super.update(menu);
} }

View File

@ -1,7 +1,7 @@
package run.halo.app.service.impl; package run.halo.app.service.impl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import run.halo.app.exception.NotFoundException; import run.halo.app.exception.NotFoundException;
import run.halo.app.model.entity.PostMeta; import run.halo.app.model.entity.PostMeta;
@ -29,7 +29,7 @@ public class PostMetaServiceImpl extends BaseMetaServiceImpl<PostMeta> implement
} }
@Override @Override
public void validateTarget(@NotNull Integer postId) { public void validateTarget(@NonNull Integer postId) {
postRepository.findById(postId) postRepository.findById(postId)
.orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId)); .orElseThrow(() -> new NotFoundException("查询不到该文章的信息").setErrorData(postId));
} }

View File

@ -1,7 +1,7 @@
package run.halo.app.service.impl; package run.halo.app.service.impl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull; import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import run.halo.app.exception.NotFoundException; import run.halo.app.exception.NotFoundException;
import run.halo.app.model.entity.SheetMeta; import run.halo.app.model.entity.SheetMeta;
@ -32,7 +32,7 @@ public class SheetMetaServiceImpl extends BaseMetaServiceImpl<SheetMeta> impleme
} }
@Override @Override
public void validateTarget(@NotNull Integer sheetId) { public void validateTarget(@NonNull Integer sheetId) {
sheetRepository.findById(sheetId) sheetRepository.findById(sheetId)
.orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId)); .orElseThrow(() -> new NotFoundException("查询不到该页面的信息").setErrorData(sheetId));
} }

View File

@ -5,7 +5,6 @@ import lombok.Getter;
import lombok.ToString; import lombok.ToString;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.NonNull; import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import run.halo.app.model.support.HaloConst; import run.halo.app.model.support.HaloConst;
@ -157,7 +156,7 @@ public class Version implements Comparable<Version> {
} }
@Override @Override
public int compareTo(@NotNull Version anotherVersion) { public int compareTo(@NonNull Version anotherVersion) {
// compare major // compare major
int majorCompare = Long.compare(major, anotherVersion.major); int majorCompare = Long.compare(major, anotherVersion.major);
if (majorCompare != 0) { if (majorCompare != 0) {

View File

@ -1,94 +0,0 @@
package run.halo.app.utils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import run.halo.app.exception.BadRequestException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Github api test.
*
* @author johnniang
* @date 19-5-21
*/
@Slf4j
@Disabled("Due to time-consumption")
class GithubTest {
final static String API_URL = "https://api.github.com/repos/halo-dev/halo-admin/releases/latest";
final static String HALO_ADMIN_REGEX = "halo-admin-\\d+\\.\\d+(\\.\\d+)?(-\\S*)?\\.zip";
final Path tempPath;
final RestTemplate restTemplate;
GithubTest() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
tempPath = Files.createTempDirectory("git-test");
this.restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient(5000)));
}
@Test
@SuppressWarnings("unchecked")
void getLatestReleaseTest() throws Throwable {
ResponseEntity<Map> responseEntity = restTemplate.getForEntity(API_URL, Map.class);
log.debug("Response: " + responseEntity);
Object assetsObject = responseEntity.getBody().get("assets");
log.debug("Assets class: " + assetsObject.getClass());
log.debug("Assets: " + assetsObject);
if (assetsObject instanceof List) {
List assets = (List) assetsObject;
Map assetMap = (Map) assets.stream().filter(aAsset -> {
if (!(aAsset instanceof Map)) {
return false;
}
Map aAssetMap = (Map) aAsset;
Object name = aAssetMap.getOrDefault("name", "");
return name.toString().matches(HALO_ADMIN_REGEX);
})
.findFirst()
.orElseThrow(() -> new BadRequestException("Halo admin has no assets available"));
Object name = assetMap.getOrDefault("name", "");
Object browserDownloadUrl = assetMap.getOrDefault("browser_download_url", "");
// Download the assets
ResponseEntity<byte[]> downloadResponseEntity = restTemplate.getForEntity(browserDownloadUrl.toString(), byte[].class);
log.debug("Download response entity status: " + downloadResponseEntity.getStatusCode());
Path downloadedPath = Files.write(tempPath.resolve(name.toString()), downloadResponseEntity.getBody());
log.debug("Downloaded path: " + downloadedPath.toString());
}
}
@Test
void nameMatchTEst() {
String name = "halo-admin-1.0.0-beta.1.zip";
assertTrue(name.matches(HALO_ADMIN_REGEX));
name = "halo-admin-1.0.zip";
assertTrue(name.matches(HALO_ADMIN_REGEX));
name = "halo-admin-1.0.0.zip";
assertTrue(name.matches(HALO_ADMIN_REGEX));
name = "halo-admin-v1.0.0-beta.zip";
assertFalse(name.matches(HALO_ADMIN_REGEX));
name = "halo-admin.zip";
assertFalse(name.matches(HALO_ADMIN_REGEX));
}
}