Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Improvement] internationalization message #3927

Open
wants to merge 29 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import java.util.List;
import java.util.Locale;

/** Customize the SpringMVC configuration */
@Configuration
Expand All @@ -52,6 +55,8 @@ public class WebMvcConfig implements WebMvcConfigurer {
HttpMethod.DELETE.name()
};

public static final String LOCALE_LANGUAGE_COOKIE = "language";

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ByteArrayHttpMessageConverter());
Expand Down Expand Up @@ -95,4 +100,16 @@ public void addInterceptors(InterceptorRegistry registry) {
.addInterceptor(uploadFileTypeInterceptor)
.addPathPatterns("/flink/app/upload", "/resource/upload");
}

@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setCookieName(LOCALE_LANGUAGE_COOKIE);
// set default locale
localeResolver.setDefaultLocale(Locale.US);
// set language tag compliant
localeResolver.setLanguageTagCompliant(false);
return localeResolver;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.streampark.console.base.enums;

public enum CommonStatus implements Status {

SUCCESS(0, "success", "成功"),
UNKNOWN_ERROR(1, "unknown error: {0}", "未知错误: {0}"),

PROJECT(10, "Project", "项目"),
TEAM(11, "Team", "团队"),
VARIABLE(12, "Variable", "变量"),
APPLICATION(13, "Application", "应用程序"),
FLINK_CLUSTERS(14, "Flink Clusters", "Flink集群"),

;

private final int code;
private final String enMsg;
private final String zhMsg;

CommonStatus(int code, String enMsg, String zhMsg) {
this.code = code;
this.enMsg = enMsg;
this.zhMsg = zhMsg;
}

@Override
public int getCode() {
return this.code;
}

@Override
public String getEnMsg() {
return this.enMsg;
}

@Override
public String getZhMsg() {
return this.zhMsg;
}
ly109974 marked this conversation as resolved.
Show resolved Hide resolved
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,29 @@
* limitations under the License.
*/

package org.apache.streampark.console.base.exception;
package org.apache.streampark.console.base.enums;

/** This exception is thrown when there is an error in the file type */
public class IllegalFileTypeException extends ApiAlertException {
import org.springframework.context.i18n.LocaleContextHolder;

public IllegalFileTypeException(String message) {
super(message);
}
import java.util.Locale;

public interface Status {

/** get status code */
int getCode();

/** get english message */
String getEnMsg();

/** get chinese message */
String getZhMsg();

public IllegalFileTypeException(String message, Throwable cause) {
super(message, cause);
/** get internationalization message */
default String getMessage() {
if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(LocaleContextHolder.getLocale().getLanguage())) {
return getZhMsg();
} else {
return getEnMsg();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
package org.apache.streampark.console.base.exception;

import org.apache.streampark.console.base.domain.ResponseCode;
import org.apache.streampark.console.base.enums.Status;

import org.bouncycastle.util.Arrays;

import java.text.MessageFormat;
import java.util.Objects;

/**
*
*
* <pre>
* To notify the frontend of an exception message,
* it is usually a <strong> clear </strong> and <strong> concise </strong> message, e.g:
Expand All @@ -34,48 +36,57 @@
*/
public class ApiAlertException extends AbstractApiException {

public ApiAlertException(String message) {
protected ApiAlertException(String message) {
super(message, ResponseCode.CODE_FAIL_ALERT);
}

public ApiAlertException(Throwable cause) {
protected ApiAlertException(Throwable cause) {
super(cause, ResponseCode.CODE_FAIL_ALERT);
}

public ApiAlertException(String message, Throwable cause) {
protected ApiAlertException(String message, Throwable cause) {
super(message, cause, ResponseCode.CODE_FAIL_ALERT);
}

public static void throwIfNull(Object object, String errorMsgFmt, Object... args) {
public static void throwIfNull(Object object, Status status, Object... args) {
if (Objects.isNull(object)) {
if (args == null || args.length < 1) {
throw new ApiAlertException(errorMsgFmt);
}
throw new ApiAlertException(String.format(errorMsgFmt, args));
throwException(status, args);
}
}

public static void throwIfNotNull(Object object, String errorMsgFmt, Object... args) {
if (!Objects.isNull(object)) {
if (args == null || args.length < 1) {
throw new ApiAlertException(errorMsgFmt);
}
throw new ApiAlertException(String.format(errorMsgFmt, args));
public static void throwIfNotNull(Object object, Status status, Object... args) {
if (Objects.nonNull(object)) {
throwException(status, args);
}
}

public static void throwIfFalse(boolean expression, String errorMessage) {
if (!expression) {
throw new ApiAlertException(errorMessage);
}
public static void throwIfFalse(boolean expression, Status status, Object... args) {
throwIfTrue(!expression, status, args);
}

public static void throwIfTrue(boolean expression, String errorMsgFmt, Object... args) {
public static void throwIfTrue(boolean expression, Status status, Object... args) {
if (expression) {
if (args == null || args.length < 1) {
throw new ApiAlertException(errorMsgFmt);
throwException(status, args);
}
}

private static Object[] processArgs(Object[] args) {
if (!Arrays.isNullOrEmpty(args)) {
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (arg instanceof Status) {
args[i] = ((Status) arg).getMessage();
}
}
throw new ApiAlertException(String.format(errorMsgFmt, args));
}
return args;
}

public static <T> T throwException(Status status, Throwable cause, Object... args) {
throw new ApiAlertException(MessageFormat.format(status.getMessage(), processArgs(args)), cause);
}

public static <T> T throwException(Status status, Object... args) {
throw new ApiAlertException(MessageFormat.format(status.getMessage(), processArgs(args)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@

import org.apache.streampark.common.util.ExceptionUtils;
import org.apache.streampark.console.base.domain.ResponseCode;
import org.apache.streampark.console.base.enums.MessageStatus;

import java.text.MessageFormat;

/**
*
*
* <pre>
* An exception message that needs to be notified to front-end,
* is a detailed exception message,such as the stackTrace info,
Expand All @@ -32,16 +33,13 @@
*/
public class ApiDetailException extends AbstractApiException {

public ApiDetailException(String message) {
super(message, ResponseCode.CODE_FAIL_DETAIL);
}

public ApiDetailException(Throwable cause) {
super(ExceptionUtils.stringifyException(cause), ResponseCode.CODE_FAIL_DETAIL);
}

public ApiDetailException(String message, Throwable cause) {
super(message + ExceptionUtils.stringifyException(cause), ResponseCode.CODE_FAIL_DETAIL);
public ApiDetailException(MessageStatus status, Throwable cause, Object... args) {
super(MessageFormat.format(status.getMessage(), ExceptionUtils.stringifyException(cause), args),
ResponseCode.CODE_FAIL_DETAIL);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,12 @@

package org.apache.streampark.console.base.exception;

/** Applies to all application exceptions */
/**
* Applies to all application exceptions
*/
public class ApplicationException extends ApiAlertException {

public ApplicationException(String message) {
super(message);
}

public ApplicationException(Throwable cause) {
super(cause.getMessage());
public ApplicationException(String message, Throwable cause) {
super(message, cause);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@
import java.io.InputStream;
import java.util.Map;

/** An interceptor used to handle file uploads */
import static org.apache.streampark.console.base.enums.MessageStatus.HANDLER_UPLOAD_FILE_IS_NULL_ERROR;
import static org.apache.streampark.console.base.enums.MessageStatus.HANDLER_UPLOAD_FILE_TYPE_ILLEGAL_ERROR;

/**
* An interceptor used to handle file uploads
*/
@Component
public class UploadFileTypeInterceptor implements HandlerInterceptor {

Expand All @@ -53,13 +58,10 @@ public boolean preHandle(
Map<String, MultipartFile> files = multipartRequest.getFileMap();
for (String file : files.keySet()) {
MultipartFile multipartFile = multipartRequest.getFile(file);
ApiAlertException.throwIfNull(
multipartFile, "File to upload can't be null. Upload file failed.");
ApiAlertException.throwIfNull(multipartFile, HANDLER_UPLOAD_FILE_IS_NULL_ERROR);
InputStream input = multipartFile.getInputStream();
boolean isJarOrPyFile = FileUtils.isJarFileType(input) || isPythonFile(input);
ApiAlertException.throwIfFalse(
isJarOrPyFile,
"Illegal file type, Only support standard jar or python files. Upload file failed.");
ApiAlertException.throwIfFalse(isJarOrPyFile, HANDLER_UPLOAD_FILE_TYPE_ILLEGAL_ERROR);
}
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package org.apache.streampark.console.core.aspect;

import org.apache.streampark.console.base.domain.RestResponse;
import org.apache.streampark.console.base.enums.MessageStatus;
import org.apache.streampark.console.base.exception.ApiAlertException;
import org.apache.streampark.console.core.annotation.OpenAPI;
import org.apache.streampark.console.core.annotation.Permission;
Expand Down Expand Up @@ -52,6 +53,13 @@

import javax.servlet.http.HttpServletRequest;

import static org.apache.streampark.console.base.enums.CommonStatus.UNKNOWN_ERROR;
import static org.apache.streampark.console.base.enums.MessageStatus.API_NOT_SUPPORT;
import static org.apache.streampark.console.base.enums.MessageStatus.FLINk_APP_IS_NULL;
import static org.apache.streampark.console.base.enums.MessageStatus.SYSTEM_PERMISSION_JOB_OWNER_MISMATCH;
import static org.apache.streampark.console.base.enums.MessageStatus.SYSTEM_PERMISSION_LOGIN_USER_PERMISSION_MISMATCH;
import static org.apache.streampark.console.base.enums.MessageStatus.SYSTEM_PERMISSION_TEAM_NO_PERMISSION;

@Slf4j
@Component
@Aspect
Expand Down Expand Up @@ -84,7 +92,7 @@ public RestResponse openAPI(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String url = request.getRequestURI();
throw new ApiAlertException("openapi unsupported: " + url);
ApiAlertException.throwException(API_NOT_SUPPORT, url);
}
}
return (RestResponse) joinPoint.proceed();
Expand Down Expand Up @@ -113,7 +121,7 @@ public RestResponse permissionAction(ProceedingJoinPoint joinPoint) throws Throw
Permission permission = methodSignature.getMethod().getAnnotation(Permission.class);

User currentUser = ServiceHelper.getLoginUser();
ApiAlertException.throwIfNull(currentUser, "Permission denied, please login first.");
ApiAlertException.throwIfNull(currentUser, MessageStatus.SYSTEM_USER_NOT_LOGIN);

boolean isAdmin = currentUser.getUserType() == UserTypeEnum.ADMIN;

Expand All @@ -122,27 +130,23 @@ public RestResponse permissionAction(ProceedingJoinPoint joinPoint) throws Throw
Long userId = getId(joinPoint, methodSignature, permission.user());
ApiAlertException.throwIfTrue(
userId != null && !currentUser.getUserId().equals(userId),
"Permission denied, operations can only be performed with the permissions of the currently logged-in user.");
SYSTEM_PERMISSION_LOGIN_USER_PERMISSION_MISMATCH);

// 2) check team
Long teamId = getId(joinPoint, methodSignature, permission.team());
if (teamId != null) {
Member member = memberService.getByTeamIdUserName(teamId, currentUser.getUsername());
ApiAlertException.throwIfTrue(
member == null,
"Permission denied, only members of this team can access this permission");
ApiAlertException.throwIfTrue(member == null, SYSTEM_PERMISSION_TEAM_NO_PERMISSION);
}

// 3) check app
Long appId = getId(joinPoint, methodSignature, permission.app());
if (appId != null) {
Application app = applicationManageService.getById(appId);
ApiAlertException.throwIfTrue(app == null, "Invalid operation, application is null");
ApiAlertException.throwIfTrue(app == null, FLINk_APP_IS_NULL);
if (!currentUser.getUserId().equals(app.getUserId())) {
Member member = memberService.getByTeamIdUserName(app.getTeamId(), currentUser.getUsername());
ApiAlertException.throwIfTrue(
member == null,
"Permission denied, this job not created by the current user, And the job cannot be found in the current user's team.");
ApiAlertException.throwIfTrue(member == null, SYSTEM_PERMISSION_JOB_OWNER_MISMATCH);
}
}
}
Expand Down Expand Up @@ -171,7 +175,7 @@ private Long getId(ProceedingJoinPoint joinPoint, MethodSignature methodSignatur
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
throw new ApiAlertException(
return ApiAlertException.throwException(UNKNOWN_ERROR,
"Wrong use of annotation on method " + methodSignature.getName(), e);
}
}
Expand Down
Loading
Loading