Skip to content

Commit

Permalink
Apply checkstyle and fix format in center module (#321)
Browse files Browse the repository at this point in the history
* feat: enable checkstyle in center module

* feat: apply checkstyle in center module

* fix: fix
  • Loading branch information
TedaLIEz authored Mar 3, 2023
1 parent b49072b commit 3ab343d
Show file tree
Hide file tree
Showing 24 changed files with 58 additions and 45 deletions.
4 changes: 4 additions & 0 deletions center/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ plugins {
id 'java'
id 'org.springframework.boot'
}
apply from: "${project.rootDir}/quality/checkstyle.gradle"
group = 'com.microsoft.hydralab'
version = hydraLabVersion

sourceCompatibility = 11
targetCompatibility = 11

classes.finalizedBy checkstyleMain
bootJar.dependsOn("checkstyleMain")

repositories {
mavenCentral()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
@EnableJpaRepositories(basePackages = {"com.microsoft.hydralab.common.repository", "com.microsoft.hydralab.center.repository"})
@EntityScan(basePackages = {"com.microsoft.hydralab.common.entity.center", "com.microsoft.hydralab.common.entity.common"})
@PropertySource(value = {"classpath:version.properties"}, encoding = "utf-8")
@SuppressWarnings("HideUtilityClassConstructor")
public class RegisterCenterApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.microsoft.hydralab.common.monitor.MetricPushGateway;
import com.microsoft.hydralab.common.util.Const;
import com.microsoft.hydralab.common.file.StorageServiceClientProxy;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

package com.microsoft.hydralab.center.config;


import com.microsoft.hydralab.center.service.DeviceAgentManagementService;
import com.microsoft.hydralab.center.util.MetricUtil;
import lombok.extern.slf4j.Slf4j;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public Result<DeviceGroup> createGroup(@CurrentSecurityContext SysUser requestor
* 3) admin of the TEAM that group is in
*/
@GetMapping(value = {"/api/deviceGroup/delete"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result deleteGroup(@CurrentSecurityContext SysUser requestor,
@QueryParam(value = "groupName") String groupName) {
try {
Expand All @@ -107,6 +108,7 @@ public Result deleteGroup(@CurrentSecurityContext SysUser requestor,
* 3) admin of the TEAM that group is in
*/
@GetMapping(value = {"/api/deviceGroup/enableVerify"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result<DeviceGroup> enableGroup(@CurrentSecurityContext SysUser requestor,
@QueryParam(value = "groupName") String groupName) {
try {
Expand All @@ -132,6 +134,7 @@ public Result<DeviceGroup> enableGroup(@CurrentSecurityContext SysUser requestor
* 3) admin of the TEAM that group is in
*/
@GetMapping(value = {"/api/deviceGroup/disableVerify"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result<DeviceGroup> disableGroup(@CurrentSecurityContext SysUser requestor,
@QueryParam(value = "groupName") String groupName) {
try {
Expand Down Expand Up @@ -185,6 +188,7 @@ public Result<List<DeviceGroup>> queryGroups(@CurrentSecurityContext SysUser req
* 3) admin of the TEAM that group is in
*/
@PostMapping(value = {"/api/deviceGroup/addRelation"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result<DeviceGroupRelation> addRelation(@CurrentSecurityContext SysUser requestor,
@RequestParam(value = "groupName") String groupName,
@RequestParam(value = "deviceSerial") String deviceSerial,
Expand Down Expand Up @@ -214,6 +218,7 @@ public Result<DeviceGroupRelation> addRelation(@CurrentSecurityContext SysUser r
* 3) admin of the TEAM that group is in
*/
@PostMapping(value = {"/api/deviceGroup/deleteRelation"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result deleteRelation(@CurrentSecurityContext SysUser requestor,
@RequestParam(value = "groupName", required = true) String groupName,
@RequestParam(value = "deviceSerial", required = true) String deviceSerial) {
Expand Down Expand Up @@ -247,6 +252,7 @@ public Result deleteRelation(@CurrentSecurityContext SysUser requestor,
* 3) admin of the TEAM that group is in
*/
@GetMapping(value = "/api/deviceGroup/generate", produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result<AccessInfo> generateDeviceToken(@CurrentSecurityContext SysUser requestor,
@QueryParam(value = "deviceIdentifier") String deviceIdentifier) {
try {
Expand Down Expand Up @@ -279,6 +285,7 @@ public Result<AccessInfo> generateDeviceToken(@CurrentSecurityContext SysUser re
* 2) members of the TEAM that group is in
*/
@GetMapping(value = "/api/deviceGroup/queryDeviceList", produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result<List<DeviceInfo>> queryDevicesByGroup(@CurrentSecurityContext SysUser requestor,
@QueryParam(value = "groupName") String groupName) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ public Result<JSONObject> isAlive() {
* 3) admin of the TEAM that group is in
*/
@PostMapping(value = "/api/device/updateDeviceScope", produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("IllegalCatch")
public Result updateDeviceScope(@CurrentSecurityContext SysUser requestor,
@RequestParam(value = "deviceSerial") String deviceSerial,
@RequestParam(value = "isPrivate") Boolean isPrivate) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@
@RestController
public class PackageSetController {
private final Logger logger = LoggerFactory.getLogger(PackageSetController.class);
public SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
public int message_length = 200;
private final SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
private final int messageLength = 200;
@Resource
AttachmentService attachmentService;
@Resource
Expand All @@ -77,6 +77,7 @@ public class PackageSetController {
* 2) members of the TEAM that fileSet is in
*/
@PostMapping(value = {"/api/package/add"}, produces = MediaType.APPLICATION_JSON_VALUE)
@SuppressWarnings("ParameterNumber")
public Result add(@CurrentSecurityContext SysUser requestor,
@RequestParam(value = "teamName", required = false) String teamName,
@RequestParam(value = "commitId", required = false) String commitId,
Expand All @@ -88,10 +89,11 @@ public Result add(@CurrentSecurityContext SysUser requestor,
if (requestor == null) {
return Result.error(HttpStatus.UNAUTHORIZED.value(), "unauthorized");
}
String localTeamName = teamName;
if (StringUtils.isEmpty(teamName)) {
teamName = requestor.getDefaultTeamName();
localTeamName = requestor.getDefaultTeamName();
}
SysTeam team = sysTeamService.queryTeamByName(teamName);
SysTeam team = sysTeamService.queryTeamByName(localTeamName);
if (team == null) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "Team doesn't exist.");
}
Expand All @@ -101,27 +103,29 @@ public Result add(@CurrentSecurityContext SysUser requestor,
if (appFile.isEmpty()) {
return Result.error(HttpStatus.FORBIDDEN.value(), "apk file empty");
}
String localCommitId = commitId;
if (!LogUtils.isLegalStr(commitId, Const.RegexString.COMMON_STR, true)) {
commitId = "commitId";
localCommitId = "commitId";
}
String localBuildType = buildType;
if (!LogUtils.isLegalStr(buildType, Const.RegexString.COMMON_STR, false)) {
buildType = "debug";
localBuildType = "debug";
}
int commitCountInt = Integer.parseInt(commitCount);
commitMessage = commitMessage.replaceAll("[\\t\\n\\r]", " ");
if (commitMessage.length() > message_length) {
commitMessage = commitMessage.substring(0, message_length);
String localCommitMessage = commitMessage.replaceAll("[\\t\\n\\r]", " ");
if (localCommitMessage.length() > messageLength) {
localCommitMessage = localCommitMessage.substring(0, messageLength);
}
logger.info("commitId: {}, commitMessage: {}, buildType: {}, commitCount: {}", commitId, commitMessage, buildType,
logger.info("commitId: {}, commitMessage: {}, buildType: {}, commitCount: {}", localCommitId, localCommitMessage, localBuildType,
commitCountInt);// CodeQL [java/log-injection] False Positive: Has verified the string by regular expression

try {
String relativePath = FileUtil.getPathForToday();
//Init test file set info
TestFileSet testFileSet = new TestFileSet();
testFileSet.setBuildType(buildType);
testFileSet.setCommitId(commitId);
testFileSet.setCommitMessage(commitMessage);
testFileSet.setBuildType(localBuildType);
testFileSet.setCommitId(localCommitId);
testFileSet.setCommitMessage(localCommitMessage);
testFileSet.setCommitCount(commitCount);
testFileSet.setTeamId(team.getTeamId());
testFileSet.setTeamName(team.getTeamName());
Expand Down Expand Up @@ -263,10 +267,11 @@ public Result uploadTestJson(@CurrentSecurityContext SysUser requestor,
if (!LogUtils.isLegalStr(packageName, Const.RegexString.PACKAGE_NAME, false)) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "The packagename is illegal");
}
if (StringUtils.isEmpty(teamName)) {
teamName = requestor.getDefaultTeamName();
String localTeamName = teamName;
if (StringUtils.isEmpty(localTeamName)) {
localTeamName = requestor.getDefaultTeamName();
}
SysTeam team = sysTeamService.queryTeamByName(teamName);
SysTeam team = sysTeamService.queryTeamByName(localTeamName);
if (team == null) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "Team doesn't exist.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

package com.microsoft.hydralab.center.controller;


import com.microsoft.hydralab.center.service.RolePermissionManagementService;
import com.microsoft.hydralab.center.service.SecurityUserService;
import com.microsoft.hydralab.center.service.SysPermissionService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.microsoft.hydralab.center.service.TestDataService;
import com.microsoft.hydralab.center.service.UserTeamManagementService;
import com.microsoft.hydralab.common.entity.agent.Result;
import com.microsoft.hydralab.common.entity.center.SysUser;
import com.microsoft.hydralab.common.entity.common.AndroidTestUnit;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,8 @@ public Result<List> getTaskSuiteList(@CurrentSecurityContext SysUser requestor,

// filter all Task Suite in TEAMs that user is in
if (!sysUserService.checkUserAdmin(requestor)) {
criteriaTypes = userTeamManagementService.formTeamIdCriteria(requestor.getTeamAdminMap());
if (criteriaTypes.size() == 0) {
List<CriteriaType> criteriaTypeList = userTeamManagementService.formTeamIdCriteria(requestor.getTeamAdminMap());
if (criteriaTypeList.size() == 0) {
return Result.error(HttpStatus.UNAUTHORIZED.value(), "User belongs to no TEAM, please contact administrator for binding TEAM");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,20 +255,21 @@ public Result<SysUser> switchDefaultTeam(@CurrentSecurityContext SysUser request
return Result.error(HttpStatus.BAD_REQUEST.value(), "TEAM id is wrong.");
}
SysUser user;
if (StringUtils.isEmpty(mailAddress)) {
String localMailAddress = mailAddress;
if (StringUtils.isEmpty(localMailAddress)) {
// [All USERs] request for self default TEAM update
mailAddress = requestor.getMailAddress();
localMailAddress = requestor.getMailAddress();
user = requestor;
} else {
// [Admin only] request for others' default TEAM update
user = sysUserService.queryUserByMailAddress(mailAddress);
user = sysUserService.queryUserByMailAddress(localMailAddress);
if (user == null) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "USER id is wrong.");
}
}

if (sysUserService.checkUserAdmin(requestor) || mailAddress.equals(requestor.getMailAddress())) {
if (!userTeamManagementService.checkUserTeamRelation(mailAddress, teamId)) {
if (sysUserService.checkUserAdmin(requestor) || localMailAddress.equals(requestor.getMailAddress())) {
if (!userTeamManagementService.checkUserTeamRelation(localMailAddress, teamId)) {
return Result.error(HttpStatus.BAD_REQUEST.value(), "USER isn't under the TEAM, cannot switch the default TEAM to it.");
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
public class CorsInterceptor implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(CorsInterceptor.class);
@Value("${ENV:dev}")
private String ENV;
private String env;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import java.util.List;
import java.util.Optional;


@Repository
public interface UserTeamRelationRepository extends JpaRepository<UserTeamRelation, UserTeamRelationId> {
Optional<UserTeamRelation> findByMailAddressAndTeamId(String mailAddress, String teamId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ public File generateAgentConfigFile(String agentId, String host) {
" registry:\n" +
" # The server hostname:port of Hydra Lab Center. If nginx enabled, switch to port of nginx\n" +
" server: '" + host + "'\n" +
" # The Agent info registered in Hydra Lab Center, for instance if it's running on localhost, the URL would be: http://localhost:9886/portal/index.html#/auth\n" +
" # The Agent info registered in Hydra Lab Center, for instance if it's running on localhost," +
" the URL would be: http://localhost:9886/portal/index.html#/auth\n" +
" name: " + agentUser.getName() + "\n" +
" id: " + agentUser.getId() + "\n" +
" secret: " + agentUser.getSecret() + "\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ public class AuthTokenService {
SecurityUserService securityUserService;

public AuthToken saveAuthToken(AuthToken authToken) {
authToken = authTokenRepository.save(authToken);
return authToken;
return authTokenRepository.save(authToken);
}

public AuthToken getAuthToken(Long tokenId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ public void heartbeatAll() {
private void sendAgentMetadata(Session session, AgentUser agentUser, String signalName) {
agentUser.setBatteryStrategy(AgentUser.BatteryStrategy.valueOf(batteryStrategy));
AgentMetadata data = new AgentMetadata();

data.setStorageType(storageType);
data.setAccessToken(storageTokenManageService.generateWriteToken(agentUser.getId()));
data.setAgentUser(agentUser);
Expand Down Expand Up @@ -721,7 +720,8 @@ private JSONObject runT2CTest(TestTaskSpec testTaskSpec) {
}
Assert.notNull(testInfo, "Failed to parse the json file for test automation.");

int androidCount = 0, edgeCount = 0;
int androidCount = 0;
int edgeCount = 0;

for (DriverInfo driverInfo : testInfo.getDrivers()) {
if (driverInfo.getPlatform().equalsIgnoreCase("android")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

package com.microsoft.hydralab.center.service;


import com.microsoft.hydralab.center.repository.DeviceGroupRelationRepository;
import com.microsoft.hydralab.center.repository.DeviceGroupRepository;
import com.microsoft.hydralab.common.entity.center.DeviceGroup;
Expand Down Expand Up @@ -36,7 +35,6 @@ public class DeviceGroupService {
@Resource
UserTeamManagementService userTeamManagementService;


public DeviceGroup createGroup(String teamId, String teamName, String groupName, String owner) {
DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setTeamId(teamId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,4 @@ public void putUserSession(String mailAddress, HttpSession httpSession) {
}
}


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

package com.microsoft.hydralab.center.service;

import com.microsoft.hydralab.common.file.AccessToken;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class SysPermissionService {
//save Permission list <permissionId, SysPermission>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class SysRoleService {
//save Role list <roleId, SysRole>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import java.util.HashMap;
import java.util.Map;


@Component
public class AuthUtil {

Expand Down Expand Up @@ -135,16 +134,17 @@ public String getLoginUrl(String originUrl, String queryString) {
if (originUrl == null) {
return getLoginUrl();
}
String url = originUrl;
if (queryString != null) {
originUrl = originUrl + "?" + queryString;
url = url + "?" + queryString;
}
try {
originUrl = URLEncoder.encode(originUrl, FileUtil.UTF_8);
url = URLEncoder.encode(url, FileUtil.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
String loginUrl =
authorizationUri + "?client_id=" + clientId + "&response_type=code&redirect_uri=" + redirectUri + "&response_mode=query&scope=" + scope + "&state=" + originUrl;
authorizationUri + "?client_id=" + clientId + "&response_type=code&redirect_uri=" + redirectUri + "&response_mode=query&scope=" + scope + "&state=" + url;
return loginUrl;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

package com.microsoft.hydralab.center.util;

public class CenterConstant {
public final class CenterConstant {
public static final String CENTER_FILE_BASE_DIR = "storage/test/package/";
public static final String CENTER_TEMP_FILE_DIR = "storage/temp/";

private CenterConstant() {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public void updateAgentAliveStatus(String agentId, String status) {
agentAliveStatusMap.put(agentId, status);
}


public int getAgentAliveStatus(String agentUserId) {
String agentStatus = agentAliveStatusMap.getOrDefault(agentUserId, GlobalConstant.AgentLiveStatus.OFFLINE.getStatus());
return GlobalConstant.AgentLiveStatus.OFFLINE.getStatus().equals(agentStatus) ? 1 : 0;
Expand Down

0 comments on commit 3ab343d

Please sign in to comment.