file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
FileMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/FileMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.T2File;
@Mapper
public interface FileMapper {
public int insertFile(T2File file);
public T2File getFileInfo(T2File file);
public T2File getFileKey(T2File file);
public String getFileId();
public List<T2File> getFileInfoList(String fileId);
public int updateFileDelYn(String[] fileSeqs);
public int updateFileDelYnById(String fileId);
public List<T2File> getFileInfoListKessan(T2File param);
public int updateFileDelYnKessan(T2File deleteFile);
public int updateFileDelYnByFilePathNm(T2File deleteFile);
public T2File selectFileInfo(String fileSeq);
public T2File selectFileInfoById(String fileId);
public void copyFileInfo(T2File fileInfo);
public T2File selectFileInfoByName(T2File bean);
public void upateOrgFileName(T2File packageFileInfo);
public List<T2File> selectPackagingFileInfo(String prjId);
public List<T2File> getReusePackagingInfo();
public T2File selectReuseFileInfo(@Param("prjId") String prjId
, @Param("logiPath") String logiPath);
public int updateReuseChkFileDelYnByFilePathNm(T2File deleteFile);
public int updateBatFile(T2File deleteFile);
public T2File selectReuseFileByFilePathNm(T2File deleteFile);
public List<T2File> getPackgingReuseCntToList(String prjId);
public int getPackgingReuseCnt(String logiNm);
public int setReusePackagingFileHidden(@Param("prjId") String prjId
, @Param("logiPath") String logiPath
, @Param("logiNm") String logiNm);
public List<T2File> getBinAndroidFileList(@Param("prjId") String prjId, @Param("ossReportId") String ossReportId);
public T2File getFileInfo2(T2File file);
public void insertCopyPhysicalFileInfo(T2File fileInfo);
public T2File selectPackagingVulDOCFileInfo(String prjId);
} | 2,091 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
StatisticsMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/StatisticsMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.Statistics;
@Mapper
public interface StatisticsMapper {
List<Statistics> getChartTitle(Statistics statistics);
List<String> getNoneUser();
List<Statistics> getDivisionalProjectChartData(Statistics statistics);
List<Statistics> getMostUsedOssChartData(Statistics statistics);
List<Statistics> getMostUsedLicenseChartData(Statistics statistics);
List<Statistics> getUpdatedOssChartData(Statistics statistics);
List<Statistics> getUpdatedLicenseChartData(Statistics statistics);
List<Statistics> getTrdPartyRelatedChartData(Statistics statistics);
List<Statistics> getUserRelatedChartData(Statistics statistics);
List<Statistics> getMostUsedChartData(Statistics statistics);
} | 960 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/VulnerabilityMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Vulnerability;
@Mapper
public interface VulnerabilityMapper {
int selectVulnerabilityTotalCount(Vulnerability vulnerability);
List<Vulnerability> selectVulnerabilityList(Vulnerability vulnerability);
int checkVulnDataCnt(Vulnerability vulnerability);
List<String> selectVulnerabilityOSSNameAutoComplete();
List<String> selectVulnerabilityOSSVersionAutoComplete(String name);
List<String> selectVulnerabilityCveIdAutoComplete();
int getVulnListByOssNameCnt(OssMaster bean);
List<Vulnerability> getVulnListByOssName(OssMaster bean);
int updateOssRecheckVulnFlag();
int selectNvdTotalCount();
List<Map<String, Object>> selectVendorProductInfo(OssMaster ossBean);
List<Map<String, Object>> selectNvdInfo(OssMaster ossBean);
List<Map<String, Object>> selectNvdInfo2(OssMaster ossBean);
void insertNvdOssHis(OssMaster ossBean);
void updateOssVulnInfoNew(OssMaster newNVD);
List<String> selectUsedVulnerabilityOssProject(OssMaster ossBean);
Map<String, Object> selectNvdInfoWithOutVer(OssMaster ossBean);
void deleteOssVulnInfo(String ossId);
List<Vulnerability> selectVulnerabilityExportList(Vulnerability vulnerability);
Map<String, Object> getCveInfo(String cveId);
List<Map<String, Object>> selectMaxScoreNvdInfo(Map<String, Object> paramMap);
List<String> getPatchLinkForNvdData(@Param("cveId") String cveId);
List<Vulnerability> getSecurityVulnListByOssName(OssMaster bean);
List<Map<String, Object>> getCpeInfoAndRange(@Param("cveId") String cveId, @Param("ossName") String ossName);
List<Map<String, Object>> selectDiffVendorForProduct(OssMaster ossBean);
List<Map<String, Object>> selectDiffVendorForVendorProduct(OssMaster ossBean);
int checkDiscoveredSndMailCnt(OssMaster ossBean);
void insertOssDiscoveredSndEmail(Map<String, Object> paramMap);
void updateOssDiscoveredSndEmail();
List<Map<String, Object>> selectDiscoveredSndMailList(OssMaster ossBean);
int selectDiscoveredNotSndMailList(OssMaster ossBean);
Vulnerability selectNotFixedCveInfo(OssMaster ossBean);
List<Map<String, Object>> selectVendorProductSndMailList(OssMaster ossBean);
List<Map<String, Object>> selectNvdInfoSndMailList(OssMaster ossBean);
List<Map<String, Object>> selectVendorProductInfoWithOurVer(OssMaster ossBean);
int getCpeMatchForCpeInfoCnt(Map<String, Object> paramMap);
} | 2,765 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ProcessGuideMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/ProcessGuideMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.ProcessGuide;
@Mapper
public interface ProcessGuideMapper {
public List<ProcessGuide> selectProcessGuideList(ProcessGuide vo) throws Exception;
public int selectProcessGuideTotalCount(ProcessGuide vo) throws Exception;
public void updateProcessGuide(ProcessGuide vo) throws Exception;
public ProcessGuide selectProcessGuide(ProcessGuide vo) throws Exception;
public int selectProcessGuideCount(ProcessGuide vo) throws Exception;
}
| 697 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ProjectMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/ProjectMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssComponentsLicense;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
@Mapper
public interface ProjectMapper {
int selectProjectTotalCount(Project project);
List<Project> selectProjectList(Project project);
void updateReviewer(Project project);
void updateReject(Project project);
List<String> selectCategoryCode(String code);
Project selectProjectMaster(Project project);
List<Project> selectModelList(String prjId);
List<Project> selectWatchersList(Project project);
void insertProjectMaster(Project project);
void insertProjectWatcher(Project project);
void insertProjectModel(Project project);
void deleteProjectMaster(Project project);
void deleteProjectModel(Project project);
void deleteProjectWatcher(Project project);
List<ProjectIdentification> getOssNames(ProjectIdentification identification);
List<ProjectIdentification> getOssVersions(String ossName);
ProjectIdentification getOssId(ProjectIdentification identification);
List<ProjectIdentification> getOssFindByNameAndVersion(ProjectIdentification identification);
List<ProjectIdentification> getOssFindByVersionAndDownloadLocation(ProjectIdentification identification);
List<ProjectIdentification> getOssFindByDownloadLocation(ProjectIdentification identification);
List<ProjectIdentification> getLicenses(ProjectIdentification identification);
String getDivision(Project project);
OssComponents selectOssComponents(String componentId);
int registComponents(OssComponents param);
String selectLastComponent();
int selectExistLicense(OssComponentsLicense ossComponentsLicense);
int registComponentLicense(OssComponentsLicense ossComponentsLicense);
List<Project> getProjectNameList(Project project);
List<Project> getProjectIdList(Project project);
List<Project> getProjectModelNameList();
List<OssComponents> selectComponentId(ProjectIdentification prj);
void deleteOssComponentsLicense(OssComponents ossComponents);
void deleteOssComponents(ProjectIdentification prj);
OssMaster selectOssNickName(ProjectIdentification projectIdentification);
void updateFileId(Project project);
List<T2File> selectCsvFile(@Param("csvFileId") String csvFileId);
void deleteFileBySeq(T2File file);
List<T2File> selectAndroidCsvFile(Project project);
List<T2File> selectAndroidNoticeFile(Project project);
String selectLicenseComb(ProjectIdentification projectIdentification);
void updateComment(Project result);
void deleteComment(CommentsHistory commentsHistory);
List<ProjectIdentification> selectBomList(ProjectIdentification projectIdentification);
List<OssComponents> selectOssRefPrjList1(OssMaster ossMaster);
List<Project> selectUnlimitedOssComponentBomList(Project project);
List<OssComponentsLicense> selectBomLicense(ProjectIdentification projectIdentification);
List<OssComponentsLicense> selectBomLicenseGrp(ProjectIdentification projectIdentification);
int selectDuplicatedProject(Project project); //프로젝트 리스트중 Name + Version이 중복될 경우 0 이상의 값 리턴
List<Project> selectProjectListExcel(Project project);
String selectLastPrjId();
List<ProjectIdentification> selectOssComponentsList(Project project);
List<OssComponentsLicense> selectOssComponentsLicenseList(ProjectIdentification projectIdentification);
void insertOssComponents(ProjectIdentification projectIdentification);
void insertOssComponentsLicense(OssComponentsLicense ossComponentsLicense);
Project selectProjectMaster2(Project project);
void updateProjectMaster(Project project);
void updateReadmeContent(Project project);
void updateVerifyContents(Project project);
List<ProjectIdentification> identificationSubGrid(ProjectIdentification identification);
String getLicensesId(String licenseName);
List<ProjectIdentification> selectIdentificationGridList(ProjectIdentification identification);
ProjectIdentification selectOssComponentInfo(Map<String, String> paramMap);
List<OssComponents> getPartnerOssList(OssComponents ossComponents);
List<ProjectIdentification> getPartnerOssListValidation(OssComponents ossComponents);
List<ProjectIdentification> getIdentificationProjectSearch(ProjectIdentification projectIdentification);
void insertOssComponentsThirdParty(OssComponents ossComponents);
void insertOssComponentsThirdProject(OssComponents ossComponents);
List<OssComponentsLicense> selectThirdComponent(String prjId);
Collection<? extends OssComponentsLicense> selectThirdComponent2(String string);
void insertOssComponentsLicenseThird(OssComponentsLicense ossComponentsLicense);
void updateExcludeYn(OssComponentsLicense ossComponentsLicense);
List<Project> getProjectCreator();
List<Project> getProjectReviwer();
Project selectProjectDetailExcel(String parameter);
List<ProjectIdentification> getProjectReportExcelList(ProjectIdentification identification);
List<Project> getProjectVersionList(Project project);
void registPackageFileId(Project project);
void updatePartnerOssList(OssComponents bean);
void deleteOssComponentsLicenseWithIds(OssComponents bean);
void deleteOssComponentsWithIds(OssComponents bean);
void deleteOssComponentsWithIds2(OssComponents bean);
void insertOssComponentsCopy(OssComponents bean);
void insertOssComponentsLicenseCopy(OssComponents bean);
void updateSrcOssList(ProjectIdentification projectIdentification);
void insertSrcOssList(ProjectIdentification projectIdentification);
void updateBom(OssComponents component);
void updateProjectSubStatus(Project param);
LicenseMaster selectLicenseMaster(LicenseMaster license);
void updateComponentsOssId(Project project);
void updateComponentsLicenseId(Project project);
List<String> checkChangedIdentification(String prjId);
void updateIdentificationConfirm(Project project);
List<T2File> selectAndroidResultFile(Project project);
List<Map<String, String>> getProjectDownloadExpandInfo(Project param);
void registBomComponents(ProjectIdentification bean);
void updateComponentsLicenseInfo(Project project);
void deleteOssNotice(String prjId);
void makeOssNotice(OssNotice noticeParam);
Map<String, Object> getNoticeType(String prjId);
void updateProjectStatusWithComplete(Project bean);
List<ProjectIdentification> getOssInfoByName(ProjectIdentification projectIdentification);
List<OssMaster> checkOssNickName(OssMaster bean);
void updateFileBySeq(T2File file);
List<OssComponents> selectOssComponentsListByComponentIds(OssComponents param);
void updateAndroidNoticeFileInfoWithLoadFromProject(Project project);
List<OssComponentsLicense> getComponentListForLicenseCheck(Project _ossidUpdateParam);
void updateOssIdToNull(OssComponents _updateParam);
List<T2File> selectFileInfoById(String fileId);
void updateComponentsOssInfo(Project project);
void updateComponentsCopyrightInfo(ProjectIdentification projectIdentification);
void updateWithoutVerifyYn(OssNotice ossNotice);
List<Project> selectWatchersCheck(Project project);
List<Project> getWatcherListByEmail(String email);
List<OssComponents> findBinAutoIdentificationWithBinaryText(String prjId);
List<OssComponentsLicense> getOssComponentsLicenseListByComponentId(String componentId);
List<OssComponents> findBinAutoIdentificationWithResultText(String prjId);
void updateIdentifcationProgress(Project bean);
int existsWatcherByEmail(Project project);
void insertWatcher(Project project);
int existsWatcherByUser(Project project);
void removeWatcher(Project project);
List<Project> copyWatcher(Project project);
List<Project> selectDeleteModelList(String prjId);
void updateModelSyncInfo(Project bean);
void updateReleaseDateProjectModel(Project bean);
void resetReleaseDateProjectModelFlag(String prjId);
void deleteProjectModelWithModelName(Project project);
void updateFilePath(OssComponents newBean);
void updateDistributeTarget(Project project);
String selectViewOnlyFlag(Project project);
void updatePublicYn(Project project);
List<String> getModelCategoryTemplateArray();
List<String> getModelCategoryTemplateArraySKS();
int existsWatcher(Project project);
public List<Project> selectAddList(Project project);
void insertAddList(Project project);
void deleteAddList(Project project);
int existsAddList(Project project);
List<String> findIdentificationMaxNvdInfo(@Param("prjId")String prjId, @Param("commponentDiv")String commponentDiv);
List<String> findIdentificationMaxNvdInfoForVendorProduct(@Param("prjId")String prjId, @Param("commponentDiv")String commponentDiv);
int selectOssComponentMaxIdx(Project project);
Project getProjectBasicInfo(Project project);
List<Project> selectModelInfoList(Project project);
void updateProjectAllowDownloadBitFlag(Project project);
void updateProjectDistributionStatus(@Param("prjId") String prjId, @Param("destributionStatus") String destributionStatus);
List<String> getDeleteOssComponentsLicenseIds(OssComponents bean);
int selectReuseProjectTotalCount(Project project);
List<Project> selectReuseProject(Project project);
List<T2File> selectReusePackagingFileList(@Param("prjId") String prjId);
int getOssAnalysisDataCnt(Project project);
Project getOssAnalysisData(Project project);
String getReviewerEmail(@Param("prjId") String prjId, @Param("loginUser") String loginUser);
int selectProjectCount(Project project);
void insertStatisticsMostUsedOssInfo(Project project);
void insertStatisticsMostUsedLicenseInfo(Project project);
void deleteStatisticsMostUsedInfo(Project project);
int selectAdminCheckCnt(ProjectIdentification projectIdentification);
List<Project> selectPartnerRefPrjList(PartnerMaster partner);
void updateFileId2(Project project);
void updateCopyConfirmStatusProjectStatus(Project project);
void updateConfirmCopyVerificationDestributionStatus(Project project);
void updateProjectDivision(Project project);
void deleteProjectDistributeHis(Project project);
List<OssComponentsLicense> selectBomLicenseList(ProjectIdentification identification);
void deleteSecurityData(OssComponents ossComponents);
void insertSecurityData(OssComponents ossComponents);
List<OssComponents> getSecurityDataList(ProjectIdentification identification);
int existsWatcherByUserDivistion(Project project);
void updateWatcherDivision(Project project);
void updateCveInfoForNotFixedOssInfo(OssMaster ossMaster);
List<String> selectVulnInfoForIdentification(@Param("vendorProduct")String vendorProduct, @Param("version")String version);
int getSecurityDataCntByProject(Project project);
public List<OssComponents> selectOssComponentsSbomList(ProjectIdentification identification);
public List<OssComponents> selectOssComponentsListClassAppend(ProjectIdentification identification);
int selectVulnerabilityResolutionSecurityListCnt(Project project);
int copySecurityDataForProjectCnt(Project project);
void copySecurityDataForProject(Project project);
List<OssComponents> checkSelectDownloadFile(Project project);
List<ProjectIdentification> checkSelectDownloadFileForBOM(Project project);
List<OssComponents> getDependenciesDataList(Project project);
int checkProjectDistributeHis(Project project);
}
| 11,933 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
NvdMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/NvdMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.OssMaster;
@Mapper
public interface NvdMapper {
// 사용중인 메타 데이터 조회
public List<HashMap<String, Object>> selectUseMetaData(HashMap<String, Object> param);
// 메타 데이터 신규 등록
public void insertNewMetaData(HashMap<String, Object> param);
// 메타 데이터 사용유무 변경
public void updateUseYN(HashMap<String, Object> param);
// 메타 데이터 Wait Job 데이터 조회
public List<HashMap<String, Object>> selectWaitJobData(HashMap<String, Object> param);
// 메타 데이터 Delete Job 데이터 조회
public List<HashMap<String, Object>> selectDeleteJobData(HashMap<String, Object> param);
// 메타 데이터 Job 상태 변경
public void updateJobStatus(HashMap<String, Object> param);
// CVE 데이터 삭제
public void deleteCveData(HashMap<String, Object> param);
// SW 취약점 리스트 데이터 삭제
public void deleteVulnSwData(HashMap<String, Object> param);
// CPE 데이터 조회
public HashMap<String, Object> selectOneCpeDicData(HashMap<String, Object> param);
// CPE 데이터 등록
public void insertCpeDicData(HashMap<String, Object> param);
// CPE Dictionary 데이터 삭제
public void deleteCpeDicData();
// SW 취약점 개수 조회
public int selectVulnSwCnt(HashMap<String, Object> param);
// CVE 정보 조회
public HashMap<String, Object> selectOneCveInfo(HashMap<String, Object> param);
// SW 취약점 정보 조회
public HashMap<String, Object> selectOneVulnSwInfo(HashMap<String, Object> param);
// CVE 정보 등록
public void insertCveInfo(HashMap<String, Object> param);
// SW 취약점 정보 등록
public void insertVulnSwInfo(HashMap<String, Object> param);
// OSS 배치 타겟 초기화
public void updateOssBatTarget();
// OSS 배치 타겟 조회
public List<Map<String, Object>> selectOssBatTarget();
// OSS 취약점 정보 설정
public void updateOssVulnInfo(Map<String, Object> param);
// OSS 취약점 유무 설정
public void updateOssVulnYn(HashMap<String, Object> param);
// 메타 데이터 Job Run Timeout
public void updateJobRunTimeout(HashMap<String, Object> param);
// Local에 저장된 입력 데이터 조회 - 첫 NVD 데이터 입력 시 사용
public List<HashMap<String, Object>> selectLocalJobData(HashMap<String, Object> param);
public List<String> selectUsedVulnerabilityOssProject(OssMaster ossBean);
public void deleteNvdDataTemp();
public void deleteNvdData();
public int insertNvdDataTemp();
public int copyNvdDataFromTemp();
public void deleteNvdDataScore();
public int insertNvdDataScore();
public List<Map<String, Object>> selectOssBatTargetWithOutVersion();
public int updateOssRecheckVulnFlag();
public HashMap<String, Object> selectOneCveInfoV3(Map<String, Object> cveInfo);
public void insertCveInfoV3(Map<String, Object> cveInfo);
public void deleteCveDataV3(Map<String, Object> cveInfo);
public void deleteNvdDataV3(Map<String, Object> cveInfo);
public void insertNvdDataV3(Map<String, String> ossInfo);
public void deleteNvdDataTempV3();
public int insertNvdDataTempV3();
public void deleteNvdDataScoreV3();
public void insertNvdDataScoreV3();
public List<Map<String, Object>> selectOssBatTargetV3();
public List<Map<String, Object>> selectOssBatTargetWithOutVersionV3();
public Map<String, Object> selectNvdInfo(OssMaster ossBean);
public Map<String, Object> selectNvdInfoWithOutVer(OssMaster ossBean);
public void updateOssVulnInfoNew(OssMaster ossBean);
public void insertNvdOssHis(OssMaster ossBean);
public List<Map<String, Object>> selectOssBatTargetV3test();
public List<Map<String, Object>> selectOssBatTargetWithOutVersionV3test();
public int selectNvdTotalCount();
public int deleteOssVulnInfo(String ossId);
public int selectNickNameMgrtNvdDataScoreV3();
public int insertNickNameMgrtNvdDataScoreV3();
public int selectMaxCvssScoreNvdDataScoreV3();
public int insertMaxCvssScoreNvdDataScoreV3();
public int ossNameNickNameCvssScoreDiffCnt();
public int ossNameToNickNameMgrtCvssScore();
public int nickNameToOssNameMgrtCvssScore();
public void truncateCpeMatchNames();
public void truncateCpeMatch();
public void insertCpeMatchData(Map<String, Object> matchInfo);
public void insertCpeMatchNameData(Map<String, Object> matchInfo);
public List<String> selectNvdMatchList(Map<String, String> _matchNameParams);
public void insertBulkCpeMatchData(List<Map<String, Object>> insertDataList);
public void insertBulkCpeMatchNameData(List<Map<String, Object>> insertDataList);
public void insertBulkNvdDataV3(Object object);
public void nvdBulkDataCleanCVE();
public void nvdBulkDataCleanData();
}
| 5,209 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiVulnerabilityMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/ApiVulnerabilityMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ApiVulnerabilityMapper {
List<Map<String, Object>> selectNvdList(Map<String, Object> paramMap);
List<Map<String, Object>> selectMaxScoreNvdInfo(Map<String, Object> paramMap);
}
| 426 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiOssMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/ApiOssMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ApiOssMapper {
List<Map<String, Object>> getOssInfo(Map<String, Object> paramMap);
String getOssName(String ossName);
List<Map<String, Object>> getOssInfoByDownloadLocation(String downloadLocation);
List<Map<String, Object>> getLicenseInfo(String licenseName);
List<String> selectOssNicknameList(String ossName);
List<HashMap<String, Object>> getOssInfoAll();
List<HashMap<String, Object>> getOssInfoAllWithNick();
List<HashMap<String, Object>> getOssAllNickNameList();
List<String> getDownloadLocationListByOssName(String ossName);
List<String> getHomepageListByOssName(String ossName);
}
| 885 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CodeMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/CodeMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.T2Code;
import oss.fosslight.domain.T2CodeDtl;
@Mapper
public interface CodeMapper {
public List<T2Code> selectCodeList(T2Code vo) throws Exception;
public ArrayList<T2CodeDtl> selectCodeDetailList(T2CodeDtl vo) throws Exception;
public void insertCode(T2Code vo) throws Exception;
public void updateCode(T2Code vo) throws Exception;
public void deleteCode(T2Code vo) throws Exception;
public void deleteCodeDetailAll(T2Code vo) throws Exception;
public void insertCodeDetail(T2CodeDtl vo) throws Exception;
public void updateCodeDetail(T2CodeDtl vo) throws Exception;
public void deleteCodeDetail(T2CodeDtl vo) throws Exception;
public int selectCodeTotalCount(T2Code vo);
public List<T2Code> getCodeList(T2Code t2Code);
public List<T2Code> getCodeNmList(T2Code t2Code);
public String selectExtType(String string);
public List<String> getCategoryList(String categoryCd);
public void saveConfiguration(T2Code code);
/**
* Get the Detail Code.
*
* @param cdNo the cd no
* @param cdDtlNo the cd dtl no
* @return the code dtl T2CodeDtl object
*/
public T2CodeDtl getCodeDetail(@Param("cdNo") String cdNo, @Param("cdDtlNo") String cdDtlNo);
/**
* Gets the Detail Code Name.
*
* @param cdNo the cd no
* @param cdDtlNo the cd dtl no
* @return the code dtl nm
*/
public String getCodeDtlNm(@Param("cdNo") String cdNo, @Param("cdDtlNo") String cdDtlNo);
/**
* Update Detail Code Name.
*
* @param cdNo the cd no
* @param cdDtlNo the cd dtl no
* @param cdDtlNm the cd dtl nm
* @return update result int
*/
public int updateCodeDtlNm(@Param("cdNo") String cdNo, @Param("cdDtlNo") String cdDtlNo, @Param("cdDtlNm") String cdDtlNm);
public void updateStatisticsMostUsed(T2CodeDtl codeDtl);
}
| 2,149 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityHistoryMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/VulnerabilityHistoryMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.VulnerabilityHistory;
@Mapper
public interface VulnerabilityHistoryMapper {
int selectVulnerabilityHistoryTotalCount(VulnerabilityHistory vulnerabilityHistory);
List<VulnerabilityHistory> selectVulnerabilityHistoryList(VulnerabilityHistory vulnerabilityHistory);
}
| 518 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
OssMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/OssMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.OssAnalysis;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssComponentsLicense;
import oss.fosslight.domain.OssLicense;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.Vulnerability;
@Mapper
public interface OssMapper {
int selectOssMasterTotalCount(OssMaster ossMaster);
List<OssMaster> selectOssList(OssMaster ossMaster);
List<OssMaster> selectOssSubList(OssMaster ossMaster);
List<OssLicense> selectOssLicenseList(OssMaster ossMaster);
List<OssMaster> selectOssNameList();
List<OssMaster> selectOssNicknameList(OssMaster ossMaster);
List<Vulnerability> getOssVulnerabilityList(Vulnerability vulnParam);
OssMaster selectOssOne(OssMaster ossMaster);
List<OssMaster> selectOssNicknameListWithoutOwn(OssMaster ossMaster);
List<OssMaster> selectOssDownloadLocationList(OssMaster ossMaster);
List<OssMaster> selectOssDetectedLicenseList(OssMaster ossMaster);
int selectOssPopupTotalCount(OssMaster ossMaster);
List<OssMaster> selectOssPopupList(OssMaster ossMaster);
List<OssMaster> getBasicOssInfoListById(OssMaster ossMaster);
int checkExistOssConfProject(OssMaster ossMaster);
int checkExistOssConfPartner(OssMaster ossMaster);
void insertOssMaster(OssMaster ossMaster);
int insertOssNickname(OssMaster ossMaster);
int mergeOssNickname(OssMaster ossMaster);
int insertOssLicenseDeclared(OssMaster ossMaster);
int insertOssLicenseDetected(OssMaster ossMaster);
int updateOssForProject(OssMaster ossMaster);
int mergeOssName(OssMaster ossMaster);
List<OssMaster> selectOssList2(OssMaster ossMaster);
int deleteOssMaster(OssMaster ossMaster);
int deleteOssNickname(OssMaster ossMaster);
int deleteOssLicense(OssMaster ossMaster);
List<OssMaster> selectOssListExcel(OssMaster ossMaster);
List<OssMaster> getBasicOssInfoList(OssMaster ossMaster);
Map<String, Object> selectOssNameMap(OssMaster ossMaster);
OssMaster checkExistsOss(OssMaster param);
OssMaster licenseChecker(OssMaster ossMaster);
OssMaster checkExistsOssNickname(OssMaster param);
OssMaster checkExistsOssname(OssMaster param);
List<Project> getOssChangeForUserList(OssMaster param);
void deleteComponentLicenseByChangeOss(String componentId);
void insertComponentLicenseByChangeOss(OssComponentsLicense bean);
void deleteComponentLicenseIgnoreFirstByChangeOss(OssComponentsLicense deleteParam);
void updateComponentLicenseByOssChange(OssComponentsLicense updateParam);
List<OssMaster> getOssListByName(OssMaster bean);
int checkExistsOssByname(OssMaster bean);
void deleteOssLicenseFlag(String ossId);
void updateOssLicenseFlag(OssMaster updateParam);
void updateOssLicenseVDiffFlag(OssMaster updateParam);
List<OssMaster> apiSelectOssIdList();
OssMaster getLastModifiedOssInfoByName(OssMaster bean);
List<OssMaster> apiGetOssCopyTargetList(OssMaster param);
void apiCopyOssMaster(OssMaster bean);
void apiCopyOssLicense(OssMaster bean);
void apiCopyOssLicenseFlag(OssMaster bean);
int checkHasAnotherVersion(OssMaster ossMaster);
OssMaster getOssBasicInfoForMailContents(String ossId);
List<String> checkNickNameRegOss(String ossName);
void updateLicenseTypeAndObligation(OssMaster ossBean);
OssMaster checkExistsOssNickname2(OssMaster param);
List<OssMaster> getOssInfoAll();
List<OssMaster> getOssInfoAllWithNick();
OssMaster getNvdDataByOssName(OssMaster nvdParam);
void updateNvdData(OssMaster ossMaster);
void changeOssNameByDelete(OssMaster bean);
void mergeOssNickname2(OssMaster nickMergeParam);
int getOssVersionCountByName(String ossName);
String checkExistOssConfByName(String ossName);
List<OssMaster> getBasicOssListByName(String ossName);
List<OssMaster> checkExistsOssDownloadLocation(OssMaster ossMaster);
List<OssMaster> checkExistsOssHomepage(OssMaster ossMaster);
List<OssMaster> getOssAllNickNameList();
List<OssMaster> checkExistsOssDownloadLocationWithOssName(OssMaster param);
List<OssMaster> checkExistsOssHomepageWithOssName(OssMaster param);
OssMaster getNvdDataByOssNameWithoutVer(OssMaster nvdParam);
int existsOssDownloadLocation(OssMaster ossMaster);
void deleteOssDownloadLocation(OssMaster ossMaster);
void insertOssDownloadLocation(OssMaster ossMaster);
String checkOssName(ProjectIdentification bean);
List<OssMaster> checkOssNameUrl(ProjectIdentification bean);
List<OssMaster> checkOssNameUrl2(ProjectIdentification bean);
int updateOssCheckNameBySelfCheck(ProjectIdentification bean);
int updateOssCheckLicenseBySelfCheck(ProjectIdentification bean);
int updateOssCheckNameByPartner(ProjectIdentification bean);
int updateOssCheckLicenseByPartner(ProjectIdentification bean);
int updateOssCheckName(ProjectIdentification bean);
int updateOssCheckLicense(ProjectIdentification bean);
int checkOssNameCnt(ProjectIdentification bean);
int checkOssNameUrlCnt(ProjectIdentification bean);
int checkOssNameUrl2Cnt(ProjectIdentification bean);
int ossAnalysisListCnt(@Param("prjId") String prjId, @Param("startAnalysisFlag") String startAnalysisFlag, @Param("csvComponentIdList") int[] csvComponentIdList);
void deleteOssAnalysisList(@Param("prjId") String prjId);
void deleteOssAnalysis(@Param("prjId") String prjId);
int insertOssAnalysisList(OssMaster bean);
int updateOssAnalysisList(OssMaster bean);
List<OssAnalysis> selectOssAnalysisList(OssMaster bean);
void setOssAnalysisStatus(OssMaster bean);
String getOssAnalysisStatus(@Param("prjId") String prjId);
OssAnalysis getNewestOssInfo(OssAnalysis bean);
OssAnalysis getNewestOssInfo2(OssAnalysis bean);
List<OssMaster> getNewestOssInfoByOssMaster(OssMaster bean);
int updateAnalysisComplete(OssAnalysis bean);
int getAnalysisListPage(@Param("rows") int rows, @Param("prjId") String prjId);
OssAnalysis getAutoAnalysisSuccessOssInfo(@Param("referenceOssId") String referenceOssId);
void setDeactivateFlag(OssMaster ossMaster);
List<PartnerMaster> getOssNameMergePartnerList(OssMaster ossMaster);
List<Project> getOssNameMergeProjectList(OssMaster ossMaster);
void updateOssMasterSync(OssMaster ossMaster);
void deleteOssLicenseDeclaredSync(OssMaster ossMaster);
void deleteOssLicenseDetectedSync(OssMaster ossMaster);
int updateOssComponents(OssMaster ossMaster);
OssMaster getSaveSesstionOssInfoByName(OssMaster ossMaster);
List<OssComponents> getConfirmOssComponentsList(OssMaster ossMaster);
List<Vulnerability> getOssVulnerabilityList2(OssMaster ossMaster);
List<String> selectMultiOssList(OssMaster ossMaster);
List<String> getDeactivateOssList();
List<OssMaster> checkOssNameTotal(ProjectIdentification bean);
Map<String, Object> getRecentlyModifiedOss(OssMaster ossMaster);
List<String> selectVulnInfoForOss(OssMaster ossMaster);
List<String> checkExistsVendorProductMatchOss(OssMaster ossMaster);
int checkOssVersionDiff(String ossName);
}
| 7,434 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiCodeMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/ApiCodeMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ApiCodeMapper {
List<Map<String, Object>> selectCodeList(@Param("cdNo") String cdNo, @Param("detailValue") String detailValue);
}
| 420 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
NvdDataMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/NvdDataMapper.java | package oss.fosslight.repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.context.annotation.Configuration;
@Configuration("NvdDataMapper")
@Mapper
public interface NvdDataMapper {
String getCodeString(@Param(value = "cdNo") String cdNo, @Param(value = "cdDtlNo") String cdDtlNo);
String getCodeExp(@Param(value = "cdNo") String cdNo, @Param(value = "cdDtlNo") String cdDtlNo);
List<HashMap<String, Object>> selectUseMetaData(HashMap<String, Object> params);
int insertNewMetaData(HashMap<String, Object> params);
int insertErrorMetaData(HashMap<String, Object> params);
int updateUseYN(HashMap<String, Object> params);
int updateJobStatus(HashMap<String, Object> params);
List<HashMap<String, Object>> selectWaitJobData(HashMap<String, Object> params);
void truncateCpeMatchNames();
void truncateCpeMatch();
void insertBulkCpeMatchData(List<Map<String, Object>> params);
void insertBulkCpeMatchNameData(List<Map<String, Object>> params);
Map<String, Object> selectOneCveInfoV3(Map<String, Object> params);
List<String> selectNvdMatchList(Map<String, String> params);
void insertCveInfoV3(Map<String, Object> params);
void insertBulkNvdDataV3(List<Map<String, String>> params);
void deleteCveDataV3(Map<String, Object> params);
void deleteNvdDataV3(Map<String, Object> params);
void deleteNvdDataTempV3();
int getProducVerCnt();
List<Map<String, Object>> getProducVerList(@Param(value = "pageIdx")int pageIdx, @Param(value = "pageCnt")int pageCnt);
public Map<String, Object> getMaxScoreProductVer(@Param(value = "ossName")String ossName, @Param(value = "ossVersion")String ossVersion, @Param(value = "vendor")String vendor);
void insertNvdDataListTempV3(List<Map<String, Object>> params);
void deleteNvdDataScoreV3();
void insertNvdDataScoreV3();
int selectNickNameMgrtNvdDataScoreV3();
void insertNickNameMgrtNvdDataScoreV3();
int selectMaxCvssScoreNvdDataScoreV3();
void insertMaxCvssScoreNvdDataScoreV3();
int ossNameNickNameCvssScoreDiffCnt();
int ossNameToNickMgrtCvssScoreDiffCnt();
void ossNameToNickNameMgrtCvssScore();
void nickNameToOssNameMgrtCvssScore();
void insertCpeMatchData(Map<String, Object> params);
void insertCpeMatchNameData(Map<String, Object> params);
void resetCveDataV3();
void resetNvdDataV3();
void createTableCpeMatchTemp();
void createTableCpeMatchNameTemp();
void truncateCpeMatchTemp();
void truncateCpeMatchNameTemp();
void copyNvdDataMatchFromTemp();
void copyNvdDataMatchNameFromTemp();
int selectVendorProductNvdDataV3Cnt();
void updateVendorProductNvdDataV3();
int selectVendorProductNvdDataScoreV3Cnt();
void updateVendorProductNvdDataScoreV3();
void insertNewMetaDataUrlConnection(HashMap<String, Object> param);
List<Map<String, Object>> selectUseMetaDataUrlConnection(HashMap<String, Object> param);
void insertNvdDataPatchLink(Map<String, Object> param);
void deleteNvdDataPatchLink(@Param(value = "cveId") String cveId);
int selectNvdCpeMatch(@Param(value = "matchCriteriaId") String matchCriteriaId);
void deleteNvdCpeMatch(@Param(value = "matchCriteriaId") String matchCriteriaId);
void deleteNvdCpeMatchNames(@Param(value = "matchCriteriaId") String matchCriteriaId);
void insertNvdDataConfigurationsTemp(Map<String, String> param);
void truncateNvdDataConfigurations();
void copyNvdDataConfigurationsFromTemp();
void truncateNvdDataConfigurationsTemp();
void deleteNvdDataConfigurations(Map<String, String> param);
}
| 3,582 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2AuthoritiesMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/T2AuthoritiesMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.T2Authorities;
import oss.fosslight.domain.T2Users;
@Mapper
public interface T2AuthoritiesMapper {
public int insertAuthorities(T2Authorities t2Authorities);
public List<T2Authorities> selectAuthoritiesByUser(T2Users veticaMember);
public int deleteAuthoritiesByUserId(T2Users veticaMember);
} | 548 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2SecuredResourcesMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/T2SecuredResourcesMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.T2SecuredResources;
@Mapper
public interface T2SecuredResourcesMapper {
public List<T2SecuredResources> getAllSecuredResources();
public List<T2SecuredResources> getAllSecuredResourcesAndSecuredResourcesRoles();
public T2SecuredResources getSecuredResources(T2SecuredResources securedResources);
public T2SecuredResources getSecuredResourcesAndSecuredResourcesRoles(T2SecuredResources securedResources);
public int updateSecuredResources(T2SecuredResources securedResource);
public int insertSecuredResource(T2SecuredResources securedResource);
public int deleteSecuredResourceByResourceId(String resourceId);
} | 885 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VerificationMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/VerificationMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import oss.fosslight.domain.File;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.T2File;
@Mapper
public interface VerificationMapper {
OssNotice selectOssNoticeOne(Project project);
List<OssComponents> selectVerifyOssList(Project project);
void updateComment(CommentsHistory commentHistory);
void deleteComment(CommentsHistory commentHistory);
int insertOssNotice(OssNotice ossNotice);
List<OssComponents> selectVerificationNotice(OssNotice ossNotice);
File selectVerificationFile(String packageFileId);
File selectVerificationVulDocFile(String packageVulDocFileId);
T2File selectPackageFileName(@Param("prjId") String prjId, @Param("fileIdx") String fileIdx);
void updateVerificationStatusProgress(OssNotice ossNotice);
void insertPackagingComponents(OssComponents component);
void deletePackagingComponents(OssNotice ossNotice);
void updateNoticeFileInfo(Project projectParam);
void updateReviewReportFileInfo(Project projectParam);
List<OssComponents> selectVerificationNoticeClassAppend(OssNotice ossNotice);
void updateVerifyFilePath(OssComponents bean);
void updatePackageFile(Project prjParam);
void updateNoticeFileInfoEtc(Project project);
int existsOssNotice(String prjId);
void updateVerifyFileCount(OssComponents bean);
int updateOssNotice(OssNotice ossNotice);
int checkPackagingFileId(@Param("prjId") String prjId, @Param("packageFileId") String packageFileId
, @Param("packageFileId2") String packageFileId2, @Param("packageFileId3") String packageFileId3);
int setPackagingReuseMap(@Param("prjId") String prjId, @Param("fileSeq") String fileSeq
, @Param("refPrjId") String refPrjId, @Param("refFileSeq") String refFileSeq);
int updatePackagingReuseMap(Project project);
OssComponents checkOssNickName2(OssComponents bean);
void updatePackageVulDocFile(Project project);
}
| 2,338 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CommonMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/CommonMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import oss.fosslight.domain.CodeInfo;
@Mapper
public interface CommonMapper {
List<CodeInfo> getCodeList(String codeGrpId);
}
| 326 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SelfCheckMapper.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/repository/SelfCheckMapper.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.repository;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssComponentsLicense;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.Vulnerability;
@Mapper
public interface SelfCheckMapper {
int selectProjectTotalCount(Project project);
List<Project> selectProjectList(Project project);
void updateReviewer(Project project);
void updateReject(Project project);
List<String> selectCategoryCode(String code);
Project selectProjectMaster(Project project);
List<Project> selectModelList(String prjId);
List<Project> selectWatchersList(Project project);
void insertProjectMaster(Project project);
void insertProjectWatcher(Project project);
void insertProjectModel(Project project);
void deleteProjectMaster(Project project);
void deleteProjectModel(Project project);
void deleteProjectWatcher(Project project);
List<ProjectIdentification> getOssNames(ProjectIdentification identification);
List<ProjectIdentification> getOssVersions(String ossName);
ProjectIdentification getOssId(ProjectIdentification identification);
List<ProjectIdentification> getLicenses(ProjectIdentification identification);
String getDivision(Project project);
OssComponents selectOssComponents(String componentId);
int registComponents(OssComponents param);
String selectLastComponent();
int selectExistLicense(OssComponentsLicense ossComponentsLicense);
int registComponentLicense(OssComponentsLicense ossComponentsLicense);
List<Project> getProjectNameList(Project project);
List<Project> getProjectModelNameList();
List<OssComponents> selectComponentId(ProjectIdentification prj);
void deleteOssComponentsLicense(OssComponents ossComponents);
void deleteOssComponents(ProjectIdentification prj);
void updateFileId(Project project);
List<T2File> selectCsvFile(Project project);
void deleteFileBySeq(T2File file);
List<T2File> selectAndroidCsvFile(Project project);
List<T2File> selectAndroidNoticeFile(Project project);
String selectLicenseComb(ProjectIdentification projectIdentification);
void updateComment(CommentsHistory result);
void deleteComment(CommentsHistory commentsHistory);
List<OssComponents> selectOssRefPrjList(OssMaster ossMaster);
List<Project> selectUnlimitedOssComponentBomList(Project project);
List<OssComponentsLicense> selectBomLicense(ProjectIdentification projectIdentification);
List<OssComponentsLicense> selectBomLicenseGrp(ProjectIdentification projectIdentification);
int selectDuplicatedProject(Project project); //프로젝트 리스트중 Name + Version이 중복될 경우 0 이상의 값 리턴
List<Project> selectProjectListExcel(Project project);
String selectLastPrjId();
List<ProjectIdentification> selectOssComponentsList(Project project);
List<OssComponentsLicense> selectOssComponentsLicenseList(ProjectIdentification projectIdentification);
void insertOssComponents(ProjectIdentification projectIdentification);
void insertOssComponentsLicense(OssComponentsLicense ossComponentsLicense);
Project selectProjectMaster2(Project project);
void updateProjectMaster(Project project);
void updateReadmeContent(Project project);
void updateVerifyContents(Project project);
List<ProjectIdentification> identificationSubGrid(ProjectIdentification identification);
String getLicensesId(String licenseName);
List<ProjectIdentification> selectIdentificationGridList(ProjectIdentification identification);
ProjectIdentification selectOssComponentInfo(Map<String, String> paramMap);
List<ProjectIdentification> getIdentificationProjectSearch(ProjectIdentification projectIdentification);
void insertOssComponentsThirdParty(OssComponents ossComponents);
void insertOssComponentsThirdProject(OssComponents ossComponents);
List<OssComponentsLicense> selectThirdComponent(String prjId);
Collection<? extends OssComponentsLicense> selectThirdComponent2(String string);
void insertOssComponentsLicenseThird(OssComponentsLicense ossComponentsLicense);
void updateExcludeYn(OssComponentsLicense ossComponentsLicense);
List<Project> getProjectCreator();
List<Project> getProjectReviwer();
Project selectProjectDetailExcel(String parameter);
List<ProjectIdentification> getProjectReportExcelList(ProjectIdentification identification);
List<Project> getProjectVersionList(Project project);
void registPackageFileId(Project project);
void updatePartnerOssList(OssComponents bean);
void deleteOssComponentsLicenseWithIds(OssComponents bean);
void deleteOssComponentsWithIds(OssComponents bean);
void insertOssComponentsCopy(OssComponents bean);
void insertOssComponentsLicenseCopy(OssComponents bean);
void updateSrcOssList(ProjectIdentification projectIdentification);
void insertSrcOssList(ProjectIdentification projectIdentification);
void updateBom(OssComponents component);
void updateProjectSubStatus(Project param);
LicenseMaster selectLicenseMaster(LicenseMaster license);
void updateComponentsOssId(Project project);
void updateComponentsLicenseId(Project project);
void updateIdentificationConfirm(Project project);
List<T2File> selectAndroidResultFile(Project project);
List<Map<String, String>> getProjectDownloadExpandInfo(Project param);
void registBomComponents(ProjectIdentification bean);
void makeOssNotice(OssNotice noticeParam);
String getNoticeType(String prjId);
void updateProjectStatusWithComplete(Project bean);
void deleteOssComponentsLicenseWithReferenceDiv(ProjectIdentification delParam);
List<ProjectIdentification> getOssInfoByName(ProjectIdentification projectIdentification);
List<OssMaster> checkOssNickName(OssMaster bean);
void updateFileBySeq(T2File file);
List<OssComponents> selectOssComponentsListByComponentIds(OssComponents param);
void updateAndroidNoticeFileInfoWithLoadFromProject(Project project);
List<OssComponentsLicense> getComponentListForLicenseCheck(Project _ossidUpdateParam);
void updateOssIdToNull(OssComponents _updateParam);
List<T2File> selectFileInfoById(String fileId);
void updateComponentsOssInfo(Project project);
void updateWithoutVerifyYn(OssNotice ossNotice);
List<Project> selectWatchersCheck(Project project);
List<Project> getWatcherListByEmail(String email);
String selectComponentIdx(ProjectIdentification prj);
List<Vulnerability> getAllVulnListWithProject(Project project);
List<Vulnerability> getAllVulnListWithProjectByNickName(Project project);
int existsWatcherByEmail(Project project);
void insertWatcher(Project project);
int existsWatcherByUser(Project project);
void removeWatcher(Project project);
List<Project> copyWatcher(Project project);
Project getMaxVulnByOssName(Project vnlnUpdBean);
List<Vulnerability> getAllVulnListWithProjectEmptyVersion(Project param);
List<Vulnerability> getAllVulnListWithProjectByNickNameEmptyVersion(Project param);
int existsWatcher(Project project);
List<Project> getSelfCheckList(Project project);
List<String> getAllVulnList(Project project);
OssNotice selectOssNoticeOne(Project project);
List<OssComponents> selectVerifyOssList(Project project);
Map<String, Object> getNoticeTypeReturnMap(String prjId);
void updateNoticeFileInfo(Project projectParam);
List<OssComponents> selectVerificationNotice(OssNotice ossNotice);
List<OssComponents> selectVerificationNoticeClassAppend(OssNotice ossNotice);
Project getProjectBasicInfo(Project project);
void updateNoticeFileInfoEtc(Project project);
int insertOssNotice(OssNotice ossNotice);
int updateOssNotice(OssNotice ossNotice);
List<Vulnerability> getAllVulnListWithProject2(Project param);
List<Vulnerability> getAllVulnListWithProjectByNickName2(Project project);
List<Vulnerability> getAllVulnListWithProject3(Project param);
List<Vulnerability> getAllVulnListWithProjectByNickName3(Project project);
List<String> findIdentificationMaxNvdInfo(@Param("prjId")String prjId);
List<String> findIdentificationMaxNvdInfoForVendorProduct(@Param("prjId")String prjId);
List<OssComponents> checkSelectDownloadFile(Project project);
}
| 8,962 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityHistoryController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/VulnerabilityHistoryController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.VULNERABILITY_HISTORY;
import oss.fosslight.domain.VulnerabilityHistory;
import oss.fosslight.service.VulnerabilityHistoryService;
@Controller
public class VulnerabilityHistoryController extends CoTopComponent {
@Autowired VulnerabilityHistoryService vulnerabilityHistoryService;
@GetMapping(value=VULNERABILITY_HISTORY.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return VULNERABILITY_HISTORY.PAGE_JSP;
}
@GetMapping(value=VULNERABILITY_HISTORY.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> codeList(
@ModelAttribute VulnerabilityHistory vulnerabilityHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
vulnerabilityHistory.setCurPage(page);
vulnerabilityHistory.setPageListSize(rows);
vulnerabilityHistory.setSortField(sidx);
vulnerabilityHistory.setSortOrder(sord);
return makeJsonResponseHeader(vulnerabilityHistoryService.getVulnerabilityHistoryList(vulnerabilityHistory));
}
}
| 1,975 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ExternalController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ExternalController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.EXTERNAL;
@Controller
public class ExternalController extends CoTopComponent {
@GetMapping(value=EXTERNAL.PAGE, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res){
return EXTERNAL.PAGE_JSP;
}
}
| 686 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CodeController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/CodeController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.Url.CODE;
import oss.fosslight.domain.T2Code;
import oss.fosslight.domain.T2CodeDtl;
import oss.fosslight.service.CodeService;
import oss.fosslight.validation.T2CoValidationResult;
@Controller
public class CodeController extends CoTopComponent {
@Autowired CodeService CodeService;
@GetMapping(value=CODE.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return CODE.PAGE_JSP;
}
@GetMapping(value=CODE.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> codeList(
@ModelAttribute T2Code vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
vo.setCurPage(page);
vo.setPageListSize(rows);
vo.setSortField(sidx);
vo.setSortOrder(sord);
Map<String, Object> map = CodeService.getCodeList(vo);
return makeJsonResponseHeader(map);
}
@PostMapping(value=CODE.DETAIL_LIST_AJAX)
public @ResponseBody ResponseEntity<Object> codeDetailList(
@ModelAttribute T2CodeDtl vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
HashMap<String, Object> map = new HashMap<String, Object>();
ArrayList<T2CodeDtl> codeDetailList = CodeService.getCodeDetailList(vo);
map.put("codeDetailList", codeDetailList);
return makeJsonResponseHeader(map);
}
@PostMapping(value=CODE.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> codeSave(
@ModelAttribute T2Code vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
T2CoValidationResult vResult = validateWithAppendix(req, "PROC_MODE", "ADD");
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
CodeService.setCode(vo);
CoCodeManager.getInstance().refreshCodes();
return makeJsonResponseHeader();
}
@PostMapping(value=CODE.DETAIL_SAVE_AJAX, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public @ResponseBody ResponseEntity<Object> codeDetailSave(
@RequestBody T2Code vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
T2CoValidationResult vResult = validate(vo.getT2codeDtl());
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
CodeService.setCodeDetails(vo.getT2codeDtl(), vo.getCdNo());
CoCodeManager.getInstance().refreshCodes();
return makeJsonResponseHeader();
}
@GetMapping(value=CODE.AUTOCOMPLETE_NO_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteNoAjax(
T2Code t2Code
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<T2Code> list = CodeService.getcodeList(t2Code);
return makeJsonResponseHeader(list);
}
@GetMapping(value=CODE.AUTOCOMPLETE_NM_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteNmAjax(
T2Code t2Code
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<T2Code> list = CodeService.getcodeNmList(t2Code);
return makeJsonResponseHeader(list);
}
} | 4,463 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CycloneDXDownloadController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/CycloneDXDownloadController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.File;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.CYCLONEDXDOWNLOAD;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.T2File;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.util.ExcelDownLoadUtil;
@Controller
@Slf4j
public class CycloneDXDownloadController extends CoTopComponent {
@Resource private Environment env;
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
@Autowired ProjectService projectService;
@Autowired FileService fileService;
@Autowired CommentService commentService;
@PostMapping(value =CYCLONEDXDOWNLOAD.CYCLONEDX_POST)
public @ResponseBody ResponseEntity<Object> getCycloneDXPost(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String downloadId = null;
String rtnMsg = "";
try {
String type = (String)map.get("type");
String prjId = (String)map.get("prjId");
String dataStr = "";
if (map.containsKey("dataStr")) {
dataStr = (String)map.get("dataStr");;
}
Project prjBean = null;
boolean partnerIdCheckFlag = prjId.startsWith("3rd_") ? true : false;
if (!partnerIdCheckFlag) {
prjBean = projectService.getProjectBasicInfo(prjId);
}
if ("cycloneDXJson".equals(type)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getCdxJsonFileId()))) {
downloadId = prjBean.getCdxJsonFileId();
} else {
String fileId = ExcelDownLoadUtil.getExcelDownloadId(type, prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX, !isEmpty(dataStr) ? "verify" : "bom");
T2File jsonFile = fileService.selectFileInfo(fileId);
String jsonFullPath = jsonFile.getLogiPath();
if (!jsonFullPath.endsWith("/")) {
jsonFullPath += "/";
}
jsonFullPath += jsonFile.getLogiNm();
try {
File cycloneDXJsonFile = new File(jsonFullPath);
if (cycloneDXJsonFile.exists() && cycloneDXJsonFile.length() > 0) {
downloadId = fileId;
} else {
rtnMsg = getMessage("cyclonedx.json.failure");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("cycloneDXXml".equals(type)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getCdxXmlFileId()))) {
downloadId = prjBean.getCdxXmlFileId();
} else {
String fileId = ExcelDownLoadUtil.getExcelDownloadId(type, prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX, !isEmpty(dataStr) ? "verify" : "bom");
T2File xmlFile = fileService.selectFileInfo(fileId);
String xmlFullPath = xmlFile.getLogiPath();
if (!xmlFullPath.endsWith("/")) {
xmlFullPath += "/";
}
xmlFullPath += xmlFile.getLogiNm();
try {
File cycloneDXXmlFile = new File(xmlFullPath);
if (cycloneDXXmlFile.exists() && cycloneDXXmlFile.length() > 0) {
downloadId = fileId;
} else {
rtnMsg = getMessage("cyclonedx.xml.failure");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else {
log.error("not match type...");
return makeJsonResponseHeader(false, "not match type...");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
if (downloadId != null) {
return makeJsonResponseHeader(downloadId);
} else {
return makeJsonResponseHeader(false, rtnMsg);
}
}
@ResponseBody
@GetMapping(value = CYCLONEDXDOWNLOAD.FILE)
public ResponseEntity<FileSystemResource> getFile (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
T2File fileInfo = fileService.selectFileInfo(req.getParameter("id"));
String filePath = fileInfo.getLogiPath();
if (!filePath.endsWith("/")) {
filePath += "/";
}
filePath += fileInfo.getLogiNm();
return excelToResponseEntity(filePath, fileInfo.getOrigNm());
}
}
| 5,302 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SessionController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SessionController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.SESSION;
@Controller
public class SessionController extends CoTopComponent{
@GetMapping(value = SESSION.LOGIN, produces = "text/html; charset=utf-8")
public String user(HttpServletRequest req, HttpServletResponse res) throws IOException {
if (isLogin()) {
res.sendRedirect(req.getContextPath() + "/index");
}
/*
TODO - 추후 특정 이슈가 발생하여 server를 일정기간 Server를 내릴때 해당 기능 사용
try {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.KOREA);
Date d1 = f.parse("2019-06-11 18:00:00");
Date d2 = f.parse("2019-06-12 09:00:00");
long d1_timestamp = d1.getTime() / 1000;
long d2_timestamp = d2.getTime() / 1000;
long today_timestamp = System.currentTimeMillis() / 1000;
if (d1_timestamp < today_timestamp && d2_timestamp > today_timestamp){
res.sendRedirect(req.getContextPath() + AppConstBean.ERROR_PAGES_DEFAULT);
}
} catch (ParseException e) {
e.printStackTrace();
}
*/
return SESSION.LOGIN_JSP;
}
@GetMapping(value = SESSION.LOGIN_EXPIRED, produces = "text/html; charset=utf-8")
public void loginExpired(HttpServletRequest req, HttpServletResponse res) throws IOException {
res.sendRedirect(req.getContextPath() + "/index");
}
@GetMapping(value=SESSION.SESSION_SAVE_KEY_VAL, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> sessionKeyValSave(HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String sesKey){
final String path = req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
final String bestMatchingPattern = req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
String sesVal = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);
putSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + sesKey, sesVal);
return makeJsonResponseHeader();
}
}
| 2,771 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SelfCheckController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SelfCheckController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.util.MimeTypeUtils;
import org.springframework.core.io.FileSystemResource;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.SELF_CHECK;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.T2Users;
import oss.fosslight.repository.CodeMapper;
import oss.fosslight.repository.ProjectMapper;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.MailService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SearchService;
import oss.fosslight.service.SelfCheckService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.StringUtil;
import oss.fosslight.util.YamlUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
import oss.fosslight.service.VerificationService;
import oss.fosslight.repository.VerificationMapper;
import oss.fosslight.domain.OssNotice;
@Slf4j
@Controller
public class SelfCheckController extends CoTopComponent {
/* service Area */
@Autowired ProjectService projectService;
@Autowired FileService fileService;
@Autowired CommentService commentService;
@Autowired HistoryService historyService;
@Autowired MailService mailService;
@Autowired T2UserService userService;
@Autowired SelfCheckService selfCheckService;
@Autowired VerificationService verificationService;
/* mapper Area */
@Autowired VerificationMapper verificationMapper;
@Autowired ProjectMapper projectMapper;
@Autowired CodeMapper codeMapper;
@Autowired SearchService searchService;
private final String SESSION_KEY_SEARCH = "SESSION_KEY_SELFCHECK_LIST";
/**
* [화면] self-check 목록 조회
*/
@GetMapping(value = SELF_CHECK.LIST, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model) {
T2Users param = new T2Users();
param.setSortField("userName");
param.setSortOrder("asc");
model.addAttribute("creator", userService.getAllUsers(param));
model.addAttribute("reviewer", userService.getReviwer());
Project searchBean = null;
if (!CoConstDef.FLAG_YES.equals(req.getParameter("gnbF"))) {
deleteSession(SESSION_KEY_SEARCH);
searchBean = searchService.getSelfCheckSearchFilter(loginUserName());
if (searchBean == null) {
searchBean = new Project();
}
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
searchBean = (Project) getSessionObject(SESSION_KEY_SEARCH);
}
model.addAttribute("searchBean", searchBean);
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
return SELF_CHECK.LIST_JSP;
}
/**
* [화면] 프로젝트 상세
*/
@GetMapping(value = SELF_CHECK.EDIT, produces = "text/html; charset=utf-8")
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) {
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
return SELF_CHECK.EDIT_JSP;
}
/**
* [API] 프로젝트 상세 조회 Edit Page
*/
@RequestMapping(value = SELF_CHECK.EDIT_ID, method = { RequestMethod.GET,
RequestMethod.POST }, produces = "text/html; charset=utf-8")
public String edit(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(prjId);
project = selfCheckService.getProjectDetail(project);
T2Users user = userService.getLoginUserInfo();
project.setPrjEmail(user.getEmail());
model.addAttribute("project", project);
model.addAttribute("detail", toJson(project));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
boolean permissionFlag = false;
// Admin인 경우 Creator 를 변경할 수 있도록 사용자 정보를 반환한다.
if (CommonFunction.isAdmin()) {
List<T2Users> userList = userService.selectAllUsers();
if (userList != null) {
model.addAttribute("userWithDivisionList", userList);
}
} else {
if (selfCheckService.checkUserPermissions(project, loginUserName())) {
permissionFlag = true;
}
if (!permissionFlag) model.addAttribute("projectPermission", CoConstDef.FLAG_NO);
}
return SELF_CHECK.EDIT_JSP;
}
/**
* [API] 프로젝트 상세 조회 View Page
*/
@RequestMapping(value = SELF_CHECK.VIEW_ID, method = { RequestMethod.GET,
RequestMethod.POST }, produces = "text/html; charset=utf-8")
public String view(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(prjId);
try {
project = selfCheckService.getProjectDetail(project);
if (CoConstDef.FLAG_YES.equals(project.getUseYn())) {
model.addAttribute("project", project);
model.addAttribute("detail", toJson(project));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
// Admin인 경우 Creator 를 변경할 수 있도록 사용자 정보를 반환한다.
if (CommonFunction.isAdmin()) {
List<T2Users> userList = userService.selectAllUsers();
if (userList != null) {
model.addAttribute("userWithDivisionList", userList);
}
}
} else {
model.addAttribute("message", "Reqeusted URL is for a deleted Self-Check Project. Please contact the creator or watcher of the Self-Check Project.");
}
} catch (Exception e) {
model.addAttribute("message", "Reqeusted URL contains Self-Check Project ID that doesn't exist. Please check the Self-Check Project ID again.");
}
return SELF_CHECK.VIEW_JSP;
}
/**
* [API] 프로젝트 목록 조회
*/
@GetMapping(value = SELF_CHECK.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
if ("search".equals(req.getParameter("act"))){
// 검색 조건 저장
putSessionObject(SESSION_KEY_SEARCH, project);
}else if (getSessionObject(SESSION_KEY_SEARCH) != null){
project = (Project) getSessionObject(SESSION_KEY_SEARCH);
}
Map<String, Object> map = selfCheckService.getProjectList(project);
return makeJsonResponseHeader(map);
}
/**
* [API] Identification 공통 메인 조회
*/
@GetMapping(value = SELF_CHECK.OSSGRID_ID_CD)
public @ResponseBody ResponseEntity<Object> srcMainGridAjax(@ModelAttribute ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId, @PathVariable String code) {
// 요청한 reference의 이전 정보도 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), identification.getReferenceDiv(),
identification.getReferenceId()));
Map<String, Object> result = getOssComponentDataInfo(identification, code);
if (result != null) {
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), code, prjId), result);
}
return makeJsonResponseHeader(result);
}
@SuppressWarnings("unchecked")
private Map<String, Object> getOssComponentDataInfo(ProjectIdentification identification, String code) {
if (isEmpty(identification.getReferenceDiv())) {
identification.setReferenceDiv(code);
}
if (!isEmpty(identification.getMainData())) {
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {}.getType();
identification.setMainDataGridList((List<ProjectIdentification>) fromJson(identification.getMainData(), collectionType2));
}
if (!isEmpty(identification.getSubData())) {
Type collectionType3 = new TypeToken<List<List<ProjectIdentification>>>() {}.getType();
identification.setSubDataGridList((List<List<ProjectIdentification>>) fromJson(identification.getSubData(), collectionType3));
}
Map<String, Object> map = selfCheckService.getIdentificationGridList(identification);
T2CoProjectValidator pv = new T2CoProjectValidator();
if (map != null) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
// set self check obligation message
List<ProjectIdentification> mainDataList = CommonFunction.identificationUnclearObligationCheck((List<ProjectIdentification>) map.get("mainData"), vr.getErrorCodeMap(), vr.getWarningCodeMap());
if (!vr.isValid()) {
Map<String, String> validMap = vr.getValidMessageMap();
map.put("validData", validMap);
map.replace("mainData", CommonFunction
.identificationSortByValidInfo(mainDataList, validMap, vr.getDiffMessageMap(), vr.getInfoMessageMap(), true, true));
} else {
map.replace("mainData", CommonFunction
.identificationSortByValidInfo(mainDataList, null, null, null, true, true));
}
if (!vr.isDiff()){
Map<String, String> diffMap = vr.getDiffMessageMap();
map.put("diffData", diffMap);
}
}
return map;
}
@GetMapping(value=SELF_CHECK.VIEW_AJAX, produces = "text/html; charset=utf-8")
public String ossDetailView(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Project bean, Model model){
Project project = selfCheckService.getProjectDetail(bean);
if (project != null) {
model.addAttribute("project", project);
} else {
model.addAttribute("project", new Project());
}
return SELF_CHECK.VIEW_AJAX_JSP;
}
@GetMapping(value=SELF_CHECK.LICENSE_POPUP, produces = "text/html; charset=utf-8")
public String viewLicensePopup(HttpServletRequest req, HttpServletResponse res, @ModelAttribute LicenseMaster bean, Model model){
model.addAttribute("licenseInfo", bean);
List<LicenseMaster> resultList = new ArrayList<LicenseMaster>();
if (!isEmpty(bean.getLicenseName())) {
for (String s : bean.getLicenseName().split(",")) {
if (isEmpty(s)) {
continue;
}
s = s.toUpperCase().trim();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(s)) {
resultList.add(CoCodeManager.LICENSE_INFO_UPPER.get(s));
}
}
}
model.addAttribute("isValid", !resultList.isEmpty());
return SELF_CHECK.LICENSE_POPUP_JSP;
}
@PostMapping(value=SELF_CHECK.SEND_COMMENT)
public @ResponseBody ResponseEntity<Object> sendComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
commentsHistory.setMailType(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS.equals(commentsHistory.getReferenceDiv())
? CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_ADDED_COMMENT
: CoConstDef.CD_MAIL_TYPE_PROJECT_IDENTIFICATION_ADDED_COMMENT);
commentService.registComment(commentsHistory);
return makeJsonResponseHeader();
}
@SuppressWarnings("unchecked")
@PostMapping(value = SELF_CHECK.SAVE_SRC)
public @ResponseBody ResponseEntity<Object> saveSrc(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String prjId = (String) map.get("prjId");
String csvFileId = (String) map.get("csvFileId");
String delFileString = (String) map.get("csvDelFileIds");
String FileSeqs = (String) map.get("csvFileSeqs");
String identificationSubStatusSrc = (String) map.get("identificationSubStatusSrc");
String mainDataString = (String) map.get("mainData");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>();
delFile = (List<T2File>) fromJson(delFileString, collectionType);
List<T2File> addFile = new ArrayList<T2File>();
addFile = (List<T2File>) fromJson(FileSeqs, collectionType);
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
ossComponents = CommonFunction.removeDuplicateLicense(ossComponents);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
if (CoConstDef.FLAG_NO.equals(identificationSubStatusSrc)) {
Project project = new Project();
project.setIdentificationSubStatusSrc(identificationSubStatusSrc);
project.setPrjId(prjId);
} else {
/*
* 중간저장 대응을 위해 save시에는 validation check 를 수행하지 않는다. 문제가 생길경우, 꼭 필요한
* 체크를 별도의 type으로 추가해야함 // grid validation only customValidation
* check!! // 모든 체크 파라미터를 customValidation에 코딩 해야한다.
* T2CoProjectValidator pv = new T2CoProjectValidator();
* pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE); // main grid
* pv.setAppendix("mainList", ossComponents); // sub grid
* pv.setAppendix("subList", ossComponentsLicense);
*
* // basic validator는 무시, validate를 호출하여 custom validator를 수행한다.
* T2CoValidationResult vr = pv.validate(new HashMap<>());
*
* // return validator result if (!vr.isValid()) { return
* makeJsonResponseHeader(vr.getValidMessageMap()); }
*/
// save 시 가장 기본적인 유효성 체크만 진행 (길이, 형식 체크)
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return makeJsonResponseHeader(vr.getValidMessageMap());
}
Project project = new Project();
project.setPrjId(prjId);
project.setSrcCsvFileId(csvFileId);
project.setCsvFile(delFile);
project.setCsvFileSeq(addFile);
project.setIdentificationSubStatusSrc(identificationSubStatusSrc);
Map<String, Object> remakeComponentsMap = CommonFunction.remakeMutiLicenseComponents(ossComponents, ossComponentsLicense);
ossComponents = (List<ProjectIdentification>) remakeComponentsMap.get("mainList");
ossComponentsLicense = (List<List<ProjectIdentification>>) remakeComponentsMap.get("subList");
selfCheckService.registSrcOss(ossComponents, ossComponentsLicense, project);
}
// 정상처리된 경우 세션 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_SELF_COMPONENT_ID, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_SELFT_PROJECT, prjId));
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
/**
* [API] 프로젝트 저장
*/
@PostMapping(value = SELF_CHECK.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(@ModelAttribute Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
project.setWatchers(req.getParameterValues("watchers"));
List<Project> list = new ArrayList<Project>();
Boolean isNew = StringUtil.isEmpty(project.getPrjId());
String copy = req.getParameter("copy");
String creatorIdByName = null;
if (CommonFunction.isAdmin() && !isNew && !"true".equals(copy)) {
if (!isEmpty(project.getCreatorNm())) {
List<T2Users> userList = userService.getUserListByName(project.getCreatorNm());
if (userList != null) {
for (T2Users _bean : userList) {
if (_bean.getUserId().equals(project.getCreator())) {
creatorIdByName = _bean.getUserId();
if (!creatorIdByName.equals(project.getCreator())) {
project.setCreator(_bean.getUserId());
}
break;
}
}
}
}
}
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_SELFCHECK);
Map<String, String> reqMap = new HashMap<>();
pv.saveRequest(req, reqMap);
if (!isEmpty(creatorIdByName)) {
reqMap.put("CREATOR_NM", creatorIdByName);
}
T2CoValidationResult vr = pv.validateObject(reqMap, list);
if (!vr.isValid()) {
return makeJsonResponseHeader(vr.getValidMessageMap());
}
project.setCopy(copy);
selfCheckService.registProject(project);
Map<String, String> lastResult = new HashMap<>();
lastResult.put("prjId", project.getPrjId());
return makeJsonResponseHeader(true, null, lastResult);
}
/**
* [API] 프로젝트 삭제
*/
@PostMapping(value = SELF_CHECK.DEL_AJAX)
public @ResponseBody ResponseEntity<Object> delAjax(@ModelAttribute Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
selfCheckService.deleteProject(project);
HashMap<String, Object> resMap = new HashMap<>();
resMap.put("resCd", "10");
return makeJsonResponseHeader(resMap);
}
@GetMapping(value=SELF_CHECK.LICENSE_USERGUIDE_HTML_NM, produces = "text/html; charset=utf-8")
public @ResponseBody String getLicenseUserGuideHtml(@PathVariable String licenseName, HttpServletRequest req, HttpServletResponse res, Model model){
LicenseMaster license = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(licenseName).toUpperCase());
if (license != null) {
return CommonFunction.makeHtmlLinkTagWithText(license.getDescription());
}
return "";
}
@PostMapping(value = SELF_CHECK.ADD_WATCHER)
public @ResponseBody ResponseEntity<Object> addWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
if (!isEmpty(project.getPrjUserId()) || !isEmpty(project.getPrjEmail())) {
selfCheckService.addWatcher(project);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
@PostMapping(value = SELF_CHECK.REMOVE_WATCHER)
public @ResponseBody ResponseEntity<Object> removeWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
if (!isEmpty(project.getPrjUserId()) || !isEmpty(project.getPrjEmail())) {
selfCheckService.removeWatcher(project);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* Copys the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = SELF_CHECK.COPY_WATCHER)
public @ResponseBody ResponseEntity<Object> copyWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
HashMap<String, Object> resMap = new HashMap<>();
try {
if (!isEmpty(project.getListKind()) && !isEmpty(project.getListId()) ) {
List<Project> result = selfCheckService.copyWatcher(project);
if (result != null) {
for (Project bean : result) {
if (!StringUtils.isEmpty(bean.getPrjDivision())) {
bean.setPrjDivisionName(CoCodeManager.getCodeString(CoConstDef.CD_USER_DIVISION, bean.getPrjDivision()));
}
}
if (!isEmpty(project.getPrjId())) {
boolean existSelfCheckWatcher = selfCheckService.existsWatcher(project);
for (Project pm : result) {
pm.setPrjId(project.getPrjId());
if (existSelfCheckWatcher) {
selfCheckService.addWatcher(pm);
}
}
}
}
resMap.put("copyWatcher", result);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resMap);
}
@GetMapping(value=SELF_CHECK.LICENSE_DATA)
public @ResponseBody ResponseEntity<Object> getLicenseData(HttpServletRequest req
, HttpServletResponse res, @ModelAttribute LicenseMaster bean, Model model){
Map<String, List<LicenseMaster>> resultMap = new HashMap<>();
List<LicenseMaster> resultList = new ArrayList<LicenseMaster>();
if (!isEmpty(bean.getLicenseName())) {
for (String s : bean.getLicenseName().split(",")) {
if (isEmpty(s)) {
continue;
}
s = s.toUpperCase().trim();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(s)) {
resultList.add(CoCodeManager.LICENSE_INFO_UPPER.get(s));
}
}
}
resultMap.put("licenseList", resultList);
return makeJsonResponseHeader(resultMap);
}
@PostMapping(value=SELF_CHECK.MAKE_YAML)
public @ResponseBody ResponseEntity<Object> makeYaml(
@RequestBody Project project
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String yamlFileId = "";
try {
yamlFileId = YamlUtil.makeYaml("", toJson(project));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(yamlFileId);
}
@PostMapping(value = SELF_CHECK.NOTICE_AJAX)
public @ResponseBody ResponseEntity<Object> getNoticeHtml(HttpServletRequest req,HttpServletResponse res, Model model, //
@RequestParam(value="confirm", defaultValue="")String confirm, //
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
@RequestParam(value="allowDownloadNoticeHTMLYn", defaultValue="")String allowDownloadNoticeHTMLYn, //
@RequestParam(value="allowDownloadNoticeTextYn", defaultValue="")String allowDownloadNoticeTextYn, //
@RequestParam(value="allowDownloadSimpleHTMLYn", defaultValue="")String allowDownloadSimpleHTMLYn, //
@RequestParam(value="allowDownloadSimpleTextYn", defaultValue="")String allowDownloadSimpleTextYn, //
@RequestParam(value="allowDownloadSPDXSheetYn", defaultValue="")String allowDownloadSPDXSheetYn, //
@RequestParam(value="allowDownloadSPDXRdfYn", defaultValue="")String allowDownloadSPDXRdfYn, //
@RequestParam(value="allowDownloadSPDXTagYn", defaultValue="")String allowDownloadSPDXTagYn, //
@RequestParam(value="allowDownloadSPDXJsonYn", defaultValue="")String allowDownloadSPDXJsonYn, //
@RequestParam(value="allowDownloadSPDXYamlYn", defaultValue="")String allowDownloadSPDXYamlYn, //
OssNotice ossNotice //
) throws IOException {
String resultHtml = "";
try {
selfCheckService.registOssNotice(ossNotice);
ossNotice.setDomain(CommonFunction.getDomain(req)); // domain Setting
resultHtml = selfCheckService.getNoticeHtml(ossNotice);
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(true, null, resultHtml);
}
@PostMapping(value = SELF_CHECK.MAKE_NOTICE_PREVIEW)
public @ResponseBody ResponseEntity<Object> makeNoticePreview(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
String downloadId = null;
ossNotice.setFileType("html");
try {
selfCheckService.registOssNotice(ossNotice);
downloadId = selfCheckService.getNoticeHtmlFileForPreview(ossNotice);
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@ResponseBody
@GetMapping(value = SELF_CHECK.DOWNLOAD_NOTICE_PREVIEW, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> downloadNoticePreview (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
T2File fileInfo = fileService.selectFileInfo(req.getParameter("id"));
return noticeToResponseEntity(fileInfo.getLogiPath() + "/" + fileInfo.getLogiNm(), fileInfo.getOrigNm());
}
@PostMapping(value = SELF_CHECK.MAKE_NOTICE_TEXT)
public @ResponseBody ResponseEntity<Object> makeNoticeText(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
String downloadId = null;
ossNotice.setFileType("text");
try {
selfCheckService.registOssNotice(ossNotice);
downloadId = selfCheckService.getNoticeTextFileForPreview(ossNotice);
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value = SELF_CHECK.MAKE_NOTICE_SIMPLE)
public @ResponseBody ResponseEntity<Object> makeNoticeSimple(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
String downloadId = null;
ossNotice.setFileType("html");
ossNotice.setSimpleNoticeFlag(CoConstDef.FLAG_YES); // simple templete
ossNotice.setDomain(CommonFunction.getDomain(req)); // domain Setting
try {
selfCheckService.registOssNotice(ossNotice);
downloadId = selfCheckService.getNoticeTextFileForPreview(ossNotice);
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value = SELF_CHECK.MAKE_NOTICE_TEXT_SIMPLE)
public @ResponseBody ResponseEntity<Object> makeNoticeTextSimple(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
String downloadId = null;
ossNotice.setFileType("text");
ossNotice.setSimpleNoticeFlag(CoConstDef.FLAG_YES); // simple templete
try {
selfCheckService.registOssNotice(ossNotice);
downloadId = selfCheckService.getNoticeTextFileForPreview(ossNotice);
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value=SELF_CHECK.CHECK_SELECT_DOWNLOAD_FILE)
public @ResponseBody ResponseEntity<Object> checkSelectDownloadFile(@RequestBody Project project, HttpServletRequest req, HttpServletResponse res, Model model){
Map<String, Object> resMap = new HashMap<>();
try {
resMap = selfCheckService.checkSelectDownloadFile(project);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(resMap);
}
}
| 30,618 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
PartnerController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/PartnerController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.PARTNER;
import oss.fosslight.domain.CoMail;
import oss.fosslight.domain.CoMailManager;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.History;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.T2Users;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.repository.FileMapper;
import oss.fosslight.repository.PartnerMapper;
import oss.fosslight.repository.ProjectMapper;
import oss.fosslight.service.BinaryDataService;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.PartnerService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SearchService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.YamlUtil;
import oss.fosslight.validation.T2CoValidationConfig;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Controller
@Slf4j
public class PartnerController extends CoTopComponent{
@Autowired PartnerService partnerService;
@Autowired T2UserService userService;
@Autowired CommentService commentService;
@Autowired HistoryService historyService;
@Autowired ProjectService projectService;
@Autowired FileService fileService;
@Autowired PartnerMapper partnerMapper;
@Autowired FileMapper fileMapper;
@Autowired ProjectMapper projectMapper;
@Autowired SearchService searchService;
@Autowired private BinaryDataService binaryDataService;
/** The session key search. */
private final String SESSION_KEY_SEARCH = "SESSION_KEY_PARTNER_LIST";
/** The env. */
@Resource private Environment env;
/** The resource public upload excel path prefix. */
private String RESOURCE_PUBLIC_UPLOAD_EXCEL_PATH_PREFIX;
/** The resource public excel template path prefix. */
private String RESOURCE_PUBLIC_EXCEL_TEMPLATE_PATH_PREFIX;
/**
* Sets the resource path prefix.
*/
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_UPLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("upload.path", "/upload");
RESOURCE_PUBLIC_EXCEL_TEMPLATE_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
@GetMapping(value=PARTNER.LIST, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model){
T2Users param = new T2Users();
param.setSortField("userName");
param.setSortOrder("asc");
model.addAttribute("creator", userService.getAllUsers(param));
model.addAttribute("reviewer",userService.getReviwer());
PartnerMaster searchBean = null;
Object _param = getSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + "OSSLISTMORE", true);
if (_param != null) {
String defaultSearchOssId = (String) _param;
searchBean = new PartnerMaster();
if (!isEmpty(defaultSearchOssId)) {
deleteSession(SESSION_KEY_SEARCH);
OssMaster ossBean = CoCodeManager.OSS_INFO_BY_ID.get(defaultSearchOssId);
if (ossBean != null) {
searchBean.setOssName(ossBean.getOssName());
searchBean.setOssVersion(ossBean.getOssVersion());
}
}
} else {
if (!CoConstDef.FLAG_YES.equals(req.getParameter("gnbF"))) {
deleteSession(SESSION_KEY_SEARCH);
searchBean = searchService.getPartnerSearchFilter(loginUserName());
if (searchBean == null) {
searchBean = new PartnerMaster();
}
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
searchBean = (PartnerMaster) getSessionObject(SESSION_KEY_SEARCH);
}
}
model.addAttribute("searchBean", searchBean);
return PARTNER.LIST_JSP;
}
@GetMapping(value=PARTNER.EDIT, produces = "text/html; charset=utf-8")
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("autoAnalysisFlag", CommonFunction.propertyFlagCheck("autoanalysis.use.flag", CoConstDef.FLAG_YES));
return PARTNER.EDIT_JSP;
}
@GetMapping(value=PARTNER.EDIT_ID, produces = "text/html; charset=utf-8")
public String edit(@PathVariable String partnerId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
PartnerMaster partnerMaster = new PartnerMaster();
partnerMaster.setPartnerId(partnerId);
partnerMaster = partnerService.getPartnerMasterOne(partnerMaster);
T2File confirmationFile = new T2File();
confirmationFile.setFileSeq(partnerMaster.getConfirmationFileId());
confirmationFile = fileMapper.getFileInfo(confirmationFile);
partnerMaster.setViewOnlyFlag(partnerService.checkViewOnly(partnerId));
T2File ossFile = new T2File();
ossFile.setFileSeq(partnerMaster.getOssFileId());
ossFile = fileMapper.getFileInfo(ossFile);
String binaryFileId = partnerMaster.getBinaryFileId();
T2File binaryFile = new T2File();
if (!isEmpty(binaryFileId)){
binaryFile.setFileSeq(binaryFileId);
binaryFile = fileMapper.getFileInfo(binaryFile);
model.addAttribute("binaryFile", binaryFile);
}
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PARTNER_USER);
comHisBean.setReferenceId(partnerMaster.getPartnerId());
partnerMaster.setUserComment(commentService.getUserComment(comHisBean));
partnerMaster.setDocumentsFile(partnerMapper.selectDocumentsFile(partnerMaster.getDocumentsFileId()));
partnerMaster.setDocumentsFileCnt(partnerMapper.selectDocumentsFileCnt(partnerMaster.getDocumentsFileId()));
List<Project> prjList = projectMapper.selectPartnerRefPrjList(partnerMaster);
if (prjList.size() > 0) {
model.addAttribute("prjList", toJson(prjList));
}
model.addAttribute("detail", partnerMaster);
model.addAttribute("detailJson", toJson(partnerMaster));
model.addAttribute("confirmationFile", confirmationFile);
model.addAttribute("ossFile", ossFile);
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("checkFlag", CommonFunction.propertyFlagCheck("checkFlag", CoConstDef.FLAG_YES));
model.addAttribute("autoAnalysisFlag", CommonFunction.propertyFlagCheck("autoanalysis.use.flag", CoConstDef.FLAG_YES));
return PARTNER.EDIT_JSP;
}
@GetMapping(value=PARTNER.VIEW_ID, produces = "text/html; charset=utf-8")
public String view(@PathVariable String partnerId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
PartnerMaster partnerMaster = new PartnerMaster();
partnerMaster.setPartnerId(partnerId);
try {
partnerMaster = partnerService.getPartnerMasterOne(partnerMaster);
if (CoConstDef.FLAG_YES.equals(partnerMaster.getUseYn())) {
T2File confirmationFile = new T2File();
confirmationFile.setFileSeq(partnerMaster.getConfirmationFileId());
confirmationFile = fileMapper.getFileInfo(confirmationFile);
partnerMaster.setViewOnlyFlag(partnerService.checkViewOnly(partnerId));
T2File ossFile = new T2File();
ossFile.setFileSeq(partnerMaster.getOssFileId());
ossFile = fileMapper.getFileInfo(ossFile);
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PARTNER_USER);
comHisBean.setReferenceId(partnerMaster.getPartnerId());
partnerMaster.setUserComment(commentService.getUserComment(comHisBean));
partnerMaster.setDocumentsFile(partnerMapper.selectDocumentsFile(partnerMaster.getDocumentsFileId()));
partnerMaster.setDocumentsFileCnt(partnerMapper.selectDocumentsFileCnt(partnerMaster.getDocumentsFileId()));
model.addAttribute("detail", partnerMaster);
model.addAttribute("detailJson", toJson(partnerMaster));
model.addAttribute("confirmationFile", confirmationFile);
model.addAttribute("ossFile", ossFile);
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("checkFlag", CommonFunction.propertyFlagCheck("checkFlag", CoConstDef.FLAG_YES));
model.addAttribute("autoAnalysisFlag", CommonFunction.propertyFlagCheck("autoanalysis.use.flag", CoConstDef.FLAG_YES));
} else {
model.addAttribute("message", "Reqeusted URL is for a deleted 3rd Party Software. Please contact the creator or watcher of the 3rd Party Software.");
}
} catch (Exception e) {
model.addAttribute("message", "Reqeusted URL contains 3rd Party Software ID that doesn't exist. Please check the 3rd Party Software ID again.");
}
return PARTNER.VIEW_JSP;
}
@GetMapping(value=PARTNER.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
partnerMaster.setCurPage(page);
partnerMaster.setPageListSize(rows);
partnerMaster.setSortField(sidx);
partnerMaster.setSortOrder(sord);
if (partnerMaster.getStatus() != null) {
String statuses = partnerMaster.getStatus();
if (!isEmpty(statuses)) {
String[] arrStatuses = statuses.split(",");
partnerMaster.setArrStatuses(arrStatuses);
}
}
if ("search".equals(req.getParameter("act"))){
// 검색 조건 저장
// save search condition
putSessionObject(SESSION_KEY_SEARCH, partnerMaster);
}else if (getSessionObject(SESSION_KEY_SEARCH) != null){
partnerMaster = (PartnerMaster) getSessionObject(SESSION_KEY_SEARCH);
}
Map<String, Object> map = null;
try{
map = partnerService.getPartnerMasterList(partnerMaster);
}catch(Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_CONF_ID_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteConfIdAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
partnerMaster.setStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
return makeJsonResponseHeader(partnerService.getPartnerIdList(partnerMaster));
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_CONF_NM_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteConfAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
partnerMaster.setStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
return makeJsonResponseHeader(partnerService.getPartnerNameList(partnerMaster));
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_NM_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
return makeJsonResponseHeader(partnerService.getPartnerNameList(partnerMaster));
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_CONF_SW_NM_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteConfSwNmAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
partnerMaster.setStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
return makeJsonResponseHeader(partnerService.getPartnerSwNmList(partnerMaster));
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_SW_NM_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteSwNmAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
return makeJsonResponseHeader(partnerService.getPartnerSwNmList(partnerMaster));
}
@GetMapping(value=PARTNER.USER_LIST)
public @ResponseBody ResponseEntity<Object> getUserList(
T2Users t2Users
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<T2Users> result = null;
try{
result = partnerService.getUserList(t2Users);
}catch(Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(result);
}
@PostMapping(value = PARTNER.UPDATE_REVIEWER)
public @ResponseBody ResponseEntity<Object> partnerMod(
@RequestBody PartnerMaster vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
PartnerMaster orgPartnerMaster = null;
boolean reviewerEmptyFlag = false;
if (!isEmpty(vo.getReviewer())) {
orgPartnerMaster = partnerService.getPartnerMasterOne(vo);
if (isEmpty(orgPartnerMaster.getReviewer())) reviewerEmptyFlag = true;
}
int result = partnerService.updateReviewer(vo);
try {
History h = partnerService.work(vo);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (orgPartnerMaster != null) {
if (orgPartnerMaster != null && !vo.getReviewer().equals(orgPartnerMaster.getReviewer())) {
CoMail mailBean = reviewerEmptyFlag ? new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_REVIEWER_CHANGED) : new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_REVIEWER_TO_CHANGED);
mailBean.setParamPartnerId(vo.getPartnerId());
if (reviewerEmptyFlag) {
mailBean.setToIds(new String[]{vo.getReviewer()});
} else {
mailBean.setToIds(new String[]{orgPartnerMaster.getReviewer(), vo.getReviewer()});
}
CoMailManager.getInstance().sendMail(mailBean);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(result);
}
@SuppressWarnings("unchecked")
@PostMapping(value=PARTNER.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@RequestBody PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
//3rd party name, software name, software version Duplication Check
List<PartnerMaster> result = null;
result = partnerService.getPartnerDuplication(partnerMaster);
Map<String, String> dupMap = new HashMap<String, String>();
Map<String, Object> retMap = new HashMap<String, Object>();
Map<String, Object> ruleMap = T2CoValidationConfig.getInstance().getRuleAllMap();
String msg = "";
if (result.size() > 0){
if (!isEmpty(partnerMaster.getPartnerName()) && partnerMaster.getPartnerName().equals(result.get(0).getPartnerName())){
msg = (String) ruleMap.get("PARTNER_NAME.DUPLICATED.MSG");
dupMap.put("partnerName", msg);
}
retMap.put("isValid", "false");
retMap.put("resCd", "99"); // overlap flag
retMap.put("dupData", dupMap);
return makeJsonResponseHeader(retMap);
}
String mainGrid = partnerMaster.getOssComponentsStr();
Type collectionType = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
// ossVersion N/A => "" 치환 / 3rd Party > e2fsprogs를 Row에 추가 시 Save 불가
// ossVersion N/A => "" replace / 3rd Party > cannot save when adding e2fsprogs to row
ossComponents = CommonFunction.replaceOssVersionNA((List<ProjectIdentification>) fromJson(mainGrid, collectionType));
ossComponents = CommonFunction.removeDuplicateLicense(ossComponents);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
ossComponentsLicense = CommonFunction.mergeGridAndSession(
CommonFunction.makeSessionKey(loginUserName(),CoConstDef.CD_DTL_COMPONENT_PARTNER, partnerMaster.getPartnerId()), ossComponents, ossComponentsLicense,
CommonFunction.makeSessionReportKey(loginUserName(),CoConstDef.CD_DTL_COMPONENT_PARTNER, partnerMaster.getPartnerId()));
T2CoProjectValidator pv = new T2CoProjectValidator(); // validation proceeded with t2coProject
pv.setIgnore("OSS_NAME");
pv.setIgnore("OSS_VERSION");
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_PARTNER);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
// main grid
pv.setAppendix("mainList", ossComponents);
T2CoValidationResult vr = pv.validateObject(partnerMaster);
// return validator result
if (!vr.isValid()) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
Boolean isNew = isEmpty(partnerMaster.getPartnerId());
Map<String, Object> remakeComponentsMap = CommonFunction.remakeMutiLicenseComponents(ossComponents, ossComponentsLicense);
ossComponents = (List<ProjectIdentification>) remakeComponentsMap.get("mainList");
ossComponentsLicense = (List<List<ProjectIdentification>>) remakeComponentsMap.get("subList");
try{
// binary.txt 파일이 변경된 경우 최초 한번만 수행
PartnerMaster beforePartnerInfo = new PartnerMaster();
if(!isEmpty(partnerMaster.getPartnerId())) {
beforePartnerInfo.setPartnerId(partnerMaster.getPartnerId());
beforePartnerInfo = partnerService.getPartnerMasterOne(partnerMaster);
}
String binaryFileId = partnerMaster.getBinaryFileId();
if((!isEmpty(binaryFileId) && beforePartnerInfo == null) // 최초생성시 binary.txt File을 upload하였거나
|| (!isEmpty(binaryFileId) && beforePartnerInfo != null && !binaryFileId.equals(beforePartnerInfo.getBinaryFileId()))) { // binary.txt를 변경하였을 경우에만 동작.
List<String> binaryTxtList = CommonFunction.getBinaryListBinBinaryTxt(fileService.selectFileInfo(binaryFileId));
if(binaryTxtList != null && !binaryTxtList.isEmpty()) {
// 현재 osslist의 binary 목록을 격납
Map<String, ProjectIdentification> componentBinaryList = new HashMap<>();
for(ProjectIdentification bean : ossComponents) {
if(!isEmpty(bean.getBinaryName())) {
componentBinaryList.put(bean.getBinaryName(), bean);
}
}
List<ProjectIdentification> addComponentList = Lists.newArrayList();
// 존재여부 확인
for(String binaryNameTxt : binaryTxtList) {
if(!componentBinaryList.containsKey(binaryNameTxt)) {
// add 해야할 list
ProjectIdentification bean = new ProjectIdentification();
// 화면에서 추가한 것 처럼 jqg로 시작하는 component id를 임시로 설정한다.
bean.setGridId("jqg_"+binaryFileId+"_"+addComponentList.size());
bean.setBinaryName(binaryNameTxt);
addComponentList.add(bean);
// changeAdded += "<br> - " + binaryNameTxt;
} else { // exclude처리된 경우
ProjectIdentification bean = componentBinaryList.get(binaryNameTxt);
if(bean != null && CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
// changeExclude += "<br>" + binaryNameTxt;
}
}
}
if(addComponentList != null && !addComponentList.isEmpty()) {
ossComponents.addAll(addComponentList);
}
}
}
partnerService.registPartnerMaster(partnerMaster, ossComponents, ossComponentsLicense);
History h = partnerService.work(partnerMaster);
h.sethAction(!isNew ? CoConstDef.ACTION_CODE_UPDATE : CoConstDef.ACTION_CODE_INSERT);
if(!isEmpty(binaryFileId)) {
binaryDataService.autoIdentificationWithBinryTextFilePartner(partnerMaster);
}
historyService.storeData(h);
resCd="10";
} catch (Exception e) {
log.error(e.getMessage());
}
if ("10".equals(resCd) && !isEmpty(partnerMaster.getPartnerId())) {
String prjId = partnerMaster.getPartnerId();
// send invate mail
if (isNew) {
List<String> partnerInvateWatcherList = partnerService.getInvateWatcherList(prjId);
if (partnerInvateWatcherList != null && !partnerInvateWatcherList.isEmpty()) {
for (String _email : partnerInvateWatcherList) {
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_WATCHER_INVATED);
mailBean.setParamPartnerId(prjId);
mailBean.setParamUserId(partnerMaster.getLoginUserName());
mailBean.setParamEmail(_email);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// 분석 결과어 업로시 nickname 변경된 사항
// In the case of nickname is changed when uploading to analysis result
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, partnerMaster.getOssFileId())) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(
loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE,
partnerMaster.getOssFileId()), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
commentHisBean.setReferenceId(prjId);
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_PARTNER)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_PARTNER), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PARTNER_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, partnerMaster.getOssFileId())) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, partnerMaster.getOssFileId()), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
commentHisBean.setReferenceId(prjId);
commentHisBean.setContents(chagedOssVersion);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if (!isEmpty(partnerMaster.getPartnerId())) {
resMap.put("partnerId", partnerMaster.getPartnerId());
}
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=PARTNER.CHANGE_DIVISION_AJAX)
public @ResponseBody ResponseEntity<Object> saveBasicInfoOnConfirmAjax(
@RequestBody HashMap<String, Object> map
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String partnerId = (String)map.get("partnerId");
String division = (String)map.get("division");
try {
partnerService.updateDivision(partnerId, division);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader();
}
@PostMapping(value=PARTNER.DEL_AJAX)
public @ResponseBody ResponseEntity<Object> delAjax(
@ModelAttribute PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
HashMap<String, Object> resMap = new HashMap<>();
String resCd = "00";
try{
History h = partnerService.work(partnerMaster);
partnerService.deletePartnerMaster(partnerMaster);
h.sethAction(CoConstDef.ACTION_CODE_DELETE);
historyService.storeData(h);
resCd="10";
} catch (Exception e){
log.error(e.getMessage());
}
if ("10".equals(resCd)) {
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_DELETED);
mailBean.setParamPartnerId(partnerMaster.getPartnerId());
if (!isEmpty(partnerMaster.getUserComment())) {
mailBean.setComment(partnerMaster.getUserComment());
}
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_SW_VER_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteSwVerAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
return makeJsonResponseHeader(partnerService.getPartnerSwVerList(partnerMaster));
}
@GetMapping(value=PARTNER.AUTOCOMPLETE_CONF_SW_VER_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteConfSwVerAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
partnerMaster.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
partnerMaster.setStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
return makeJsonResponseHeader(partnerService.getPartnerSwVerList(partnerMaster));
}
@PostMapping(value = PARTNER.ADD_WATCHER)
public @ResponseBody ResponseEntity<Object> addWatcher(@RequestBody PartnerMaster project,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
// addWatcher로 email을 등록할 경우 ldap search로 존재하는 사용자의 email인지 check가 필요함.
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
if (CoConstDef.FLAG_YES.equals(ldapFlag) && !isEmpty(project.getParEmail())) {
Map<String, String> userInfo = new HashMap<>();
userInfo.put("USER_ID", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_ID));
userInfo.put("USER_PW", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_PW));
String filter = project.getParEmail().split("@")[0];
boolean isAuthenticated = userService.checkAdAccounts(userInfo, "USER_ID", "USER_PW", filter);
if (!isAuthenticated) {
throw new Exception("add Watcher Failure");
}
String email = (String) userInfo.get("EMAIL");
project.setParEmail(email);
// 사용자가 입력한 domain과 ldap search를 통해 확인된 domain이 다를 수 있기때문에 ldap search에서 확인된 domain을 우선적으로 처리함.
resultMap.put("email", email);
}
if (!isEmpty(project.getParUserId()) || !isEmpty(project.getParEmail())) {
partnerService.addWatcher(project);
resultMap.put("isValid", "true");
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resultMap);
}
@PostMapping(value = PARTNER.ADD_WATCHERS)
public @ResponseBody ResponseEntity<Object> addWatchers(@RequestBody PartnerMaster project,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
// addWatcher로 email을 등록할 경우 ldap search로 존재하는 사용자의 email인지 check가 필요함.
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
PartnerMaster param = new PartnerMaster();
for (Map<String, String> changeWatcher : project.getChangeWatcherList()) {
String parEmail = changeWatcher.get("parEmail");
if (CoConstDef.FLAG_YES.equals(ldapFlag) && !isEmpty(parEmail)) {
Map<String, String> userInfo = new HashMap<>();
userInfo.put("USER_ID", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_ID));
userInfo.put("USER_PW", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_PW));
boolean isAuthenticated = userService.checkAdAccounts(userInfo, "USER_ID", "USER_PW", parEmail);
if (!isAuthenticated) {
throw new Exception("add Watcher Failure");
}
}
param.setParUserId(changeWatcher.get("parUserId"));
param.setParDivision(changeWatcher.get("parDivision"));
param.setParEmail(parEmail);
for (String partnerId : project.getPartnerIds()) {
if (!isEmpty(param.getParUserId()) || !isEmpty(param.getParEmail())) {
param.setPartnerId(partnerId);
partnerService.addWatcher(param);
}
}
}
resultMap.put("isValid", "true");
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resultMap);
}
@PostMapping(value = PARTNER.REMOVE_WATCHER)
public @ResponseBody ResponseEntity<Object> removeWatcher(@RequestBody PartnerMaster project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
if (!isEmpty(project.getParUserId()) || !isEmpty(project.getParEmail())) {
partnerService.removeWatcher(project);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
@PostMapping(value = PARTNER.REMOVE_WATCHERS)
public @ResponseBody ResponseEntity<Object> removeWatchers(@RequestBody PartnerMaster project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
PartnerMaster param = new PartnerMaster();
for (Map<String, String> changeWatcher : project.getChangeWatcherList()) {
String parUserId = changeWatcher.get("parUserId");
String parEmail = changeWatcher.get("parEmail");
if (!isEmpty(parUserId) || !isEmpty(parEmail)) {
param.setParUserId(parUserId);
param.setParDivision(changeWatcher.get("parDivision"));
param.setParEmail(parEmail);
for (String partnerId : project.getPartnerIds()) {
param.setPartnerId(partnerId);
partnerService.removeWatcher(param);
}
}
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* Copys the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PARTNER.COPY_WATCHER)
public @ResponseBody ResponseEntity<Object> copyWatcher(@RequestBody PartnerMaster project,
HttpServletRequest req, HttpServletResponse res, Model model) {
HashMap<String, Object> resMap = new HashMap<>();
try {
if (!isEmpty(project.getListKind()) && !isEmpty(project.getListId()) ) {
List<PartnerMaster> result = partnerService.copyWatcher(project);
if (result != null) {
for (PartnerMaster pm : result) {
if (!StringUtils.isEmpty(pm.getDivision())) {
pm.setParDivision(pm.getDivision());
pm.setParDivisionName(CoCodeManager.getCodeString(CoConstDef.CD_USER_DIVISION, pm.getDivision()));
}
}
if (isEmpty(project.getCopyWatcherLocation()) && !isEmpty(project.getPartnerId())) {
boolean existPartnerWatcher = partnerService.existsWatcher(project);
for (PartnerMaster pm : result) {
pm.setPartnerId(project.getPartnerId());
if (existPartnerWatcher) {
partnerService.addWatcher(pm);
}
}
}
}
resMap.put("copyWatcher", result);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resMap);
}
/**
* update the publicYn.
*
* @param PartnerMaster the PartnerMaster
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PARTNER.UPDATE_PUBLIC_YN)
public @ResponseBody ResponseEntity<Object> updatePublicYn(@RequestBody PartnerMaster partner,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
partnerService.updatePublicYn(partner);
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* Change status.
*
* @param partnerMaster the partner master
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value=PARTNER.CHANGE_STATUS)
public @ResponseBody ResponseEntity<Object> changeStatus(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
CoMail mailbean = null;
String commentDiv = CoConstDef.CD_DTL_COMMENT_PARTNER_HIS;
String userComment = partnerMaster.getUserComment();
String statusCode = partnerMaster.getStatus();
String status = CoCodeManager.getCodeExpString(CoConstDef.CD_IDENTIFICATION_STATUS, statusCode);
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(partnerMaster.getStatus())) {
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
_param.setReferenceId(partnerMaster.getPartnerId());
Map<String, Object> map = projectService.getIdentificationGridList(_param);
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_PARTNER);
// main grid
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
//pv.setCheckForAdmin(true);
T2CoValidationResult vr = pv.validate(new HashMap<>());
// return validator result
if (!vr.isValid()) {
return makeJsonResponseHeader(vr.getValidMessageMap());
}
partnerService.updatePartnerConfirm(partnerMaster);
if(partnerMaster != null && !isEmpty(partnerMaster.getBinaryFileId()) && !(CoConstDef.FLAG_YES.equals(partnerMaster.getIgnoreBinaryDbFlag()))) {
try {
ProjectIdentification paramPartner = new ProjectIdentification();
paramPartner.setReferenceId(partnerMaster.getPartnerId());
paramPartner.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
// platform 정보
String platformName = "";
String platformVer = "";
String _partnerName = "[3rd-" + partnerMaster.getPartnerId() + "]" + partnerMaster.getPartnerName();
T2File binaryTextFile = fileService.selectFileInfo(partnerMaster.getBinaryFileId());
binaryDataService.insertBatConfirmBinOssWithChecksum(CoConstDef.CD_CHECK_OSS_PARTNER, _partnerName, platformName, platformVer, binaryTextFile, (List<ProjectIdentification>) map.get("mainData"));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
try {
mailbean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_CONF);
mailbean.setParamPartnerId(partnerMaster.getPartnerId());
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, CoConstDef.CD_MAIL_TYPE_PARTER_CONF));
if (!isEmpty(userComment)) {
mailbean.setComment(avoidNull(userComment) + "<br />" + _tempComment);
} else{
mailbean.setComment(_tempComment);
}
CoMailManager.getInstance().sendMail(mailbean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST.equals(partnerMaster.getStatus())) {
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
_param.setReferenceId(partnerMaster.getPartnerId());
Map<String, Object> map = projectService.getIdentificationGridList(_param);
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_PARTNER);
pv.setValidLevel(pv.VALID_LEVEL_REQUEST);
// main grid
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
// return validator result
if (!vr.isValid()) {
if (!vr.isDiff()) {
return makeJsonResponseHeader(false, "", "", vr.getValidMessageMap(), vr.getDiffMessageMap());
} else {
return makeJsonResponseHeader(false, "", "", vr.getValidMessageMap());
}
}
}
PartnerMaster _param2 = new PartnerMaster();
_param2.setPartnerId(partnerMaster.getPartnerId());
PartnerMaster orgInfo = partnerService.getPartnerMasterOne(_param2);
partnerService.changeStatus(partnerMaster, false);
try {
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST.equals(partnerMaster.getStatus())) {
mailbean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_REQ_REVIEW);
} else if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_PROGRESS.equals(partnerMaster.getStatus())) {
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(orgInfo.getStatus())) {
// confirm -> reject
mailbean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_CANCELED_CONF);
} else if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REVIEW.equals(orgInfo.getStatus())) {
// review -> reject
mailbean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_REJECT);
} else if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST.equals(orgInfo.getStatus())) {
// self reject
mailbean = new CoMail(CoConstDef.CD_MAIL_TYPE_PARTER_SELF_REJECT);
}
}
if (mailbean != null) {
mailbean.setParamPartnerId(partnerMaster.getPartnerId());
if (!isEmpty(userComment)) {
mailbean.setComment(userComment);
}
CoMailManager.getInstance().sendMail(mailbean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if (!isEmpty(avoidNull(userComment).trim())) {
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(commentDiv);
commHisBean.setReferenceId(partnerMaster.getPartnerId());
commHisBean.setContents(userComment);
commHisBean.setStatus(status);
commentService.registComment(commHisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if (!isEmpty(status)) {
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(commentDiv);
commHisBean.setReferenceId(partnerMaster.getPartnerId());
commHisBean.setContents(userComment);
commHisBean.setStatus(status);
commentService.registComment(commHisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return makeJsonResponseHeader(null);
}
/**
* Oss file.
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@ResponseBody
@PostMapping(value=PARTNER.OSS_FILE)
public String ossFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request, HttpServletResponse res, Model model) throws Exception{
String excel = req.getParameter("excel");
List<UploadFile> list = new ArrayList<UploadFile>();
ArrayList<Object> resultList = new ArrayList<Object>();
Map<String, MultipartFile> fileMap = req.getFileMap();
String fileExtension = StringUtils.getFilenameExtension(fileMap.get("myfile").getOriginalFilename());
if (req.getContentType() != null && req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
file.setCreator(loginUserName());
list = fileService.uploadFile(req, file);
if (fileExtension.equals("csv")) {
resultList = CommonFunction.checkCsvFileLimit(list);
} else {
resultList = CommonFunction.checkXlsxFileLimit(list);
}
if (resultList.size() > 0) {
return toJson(resultList);
}
}
if (fileExtension.equals("csv")) {
resultList.add(list);
resultList.add("SRC");
resultList.add("CSV_FILE");
return toJson(resultList);
} else {
// sheet name
List<Object> sheetNameList = null;
Boolean isSpdxSpreadsheet = false;
try {
if (CoConstDef.FLAG_YES.equals(excel)){
if (list != null && !list.isEmpty() && CoCodeManager.getCodeExpString(CoConstDef.CD_FILE_ACCEPT, "22").contains(list.get(0).getFileExt().toLowerCase())) {
sheetNameList = ExcelUtil.getSheetNames(list, RESOURCE_PUBLIC_UPLOAD_EXCEL_PATH_PREFIX);
}
}
for (Object sheet : sheetNameList) {
String sheetName = sheet.toString();
if (sheetName.contains("Package Info") || sheetName.contains("Per File Info")) {
isSpdxSpreadsheet = true;
}
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
if (isSpdxSpreadsheet){
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("SPDX_SPREADSHEET_FILE");
}
else {
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("EXCEL_FILE");
}
return toJson(resultList);
}
}
/**
* documents File
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@ResponseBody
@PostMapping(value = PARTNER.DOCUMENT_FILE)
public String documentsFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
// file registration
List<UploadFile> list = new ArrayList<UploadFile>();
String fileId = req.getParameter("registFileId");
// file registration
try {
if (req.getContentType() != null
&& req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
if (fileId == null) {
list = fileService.uploadFile(req, file);
} else {
list = fileService.uploadFile(req, file, null, fileId);
}
}
} catch (Exception e) {
log.error(e.getMessage());
}
// 결과값 resultList에 담기
// Put the result value in resultList
return toJson(list);
}
/**
* Send comment.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value=PARTNER.SEND_COMMENT)
public @ResponseBody ResponseEntity<Object> sendComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PARTER_ADDED_COMMENT);
commentService.registComment(commentsHistory);
return makeJsonResponseHeader();
}
/**
* Save comment.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value=PARTNER.SAVE_COMMENT)
public @ResponseBody ResponseEntity<Object> saveComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
commentService.registComment(commentsHistory);
return makeJsonResponseHeader();
}
/**
* Delete comment.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value=PARTNER.DELETE_COMMENT)
public @ResponseBody ResponseEntity<Object> deleteComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
T2CoValidationResult vResult = null;
try{
//validation check
vResult = validate(req);
}catch(Exception e){
log.error(e.getMessage());
}
if (!vResult.isValid()){
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
try{
commentService.deleteComment(commentsHistory);
} catch (Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
/**
* Gets the comment list.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the comment list
*/
@GetMapping(value=PARTNER.COMMENT_LIST)
public @ResponseBody ResponseEntity<Object> getCommentList(
CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
commentsHistory.setReferenceDiv("20");
List<CommentsHistory> result = null;
try{
result = commentService.getCommentList(commentsHistory);
}catch(Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(result);
}
/**
* Sample download.
*
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
* @throws Exception the exception
*/
@ResponseBody
@GetMapping(value = PARTNER.SAMPLEDOWNLOAD)
public ResponseEntity<FileSystemResource> sampleDownload (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
String fileName = req.getParameter("fileName");
String logiPath = req.getParameter("logiPath");
return excelToResponseEntity(RESOURCE_PUBLIC_EXCEL_TEMPLATE_PATH_PREFIX + logiPath, fileName);
}
@PostMapping(value = PARTNER.FILTERED_LIST)
public @ResponseBody ResponseEntity<Object> getfilteredList(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
Map<String, Object> resultMap = partnerService.getPartnerValidationList(partnerMaster);
try{
resultMap = partnerService.getFilterdList(resultMap);
return makeJsonResponseHeader(resultMap);
}catch(Exception e){
return makeJsonResponseHeader(false, "filterList Error");
}
}
@GetMapping(value=PARTNER.CHECK_STATUS)
public @ResponseBody ResponseEntity<Object> checkStatus(@PathVariable String partnerId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
Map<String, Object> resultMap = new HashMap<String, Object>();
PartnerMaster partnerMaster = new PartnerMaster();
partnerMaster.setPartnerId(partnerId);
partnerMaster = partnerService.getPartnerMasterOne(partnerMaster);
resultMap.put("status", partnerMaster.getStatus());
return makeJsonResponseHeader(resultMap);
}
@PostMapping(value=PARTNER.MAKE_YAML)
public @ResponseBody ResponseEntity<Object> makeYaml(
@RequestBody PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String yamlFileId = "";
try {
// partnerId / partnerName 필수 값.
yamlFileId = YamlUtil.makeYaml(CoConstDef.CD_DTL_COMPONENT_PARTNER, toJson(partnerMaster));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(yamlFileId);
}
@PostMapping(value=PARTNER.PARTNER_DIVISION)
public @ResponseBody ResponseEntity<Object> updatePartnerDivision(
@RequestBody PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<String> permissionCheckList = null;
if (!CommonFunction.isAdmin()) {
CommonFunction.setPartnerService(partnerService);
permissionCheckList = CommonFunction.checkUserPermissions(loginUserName(), partnerMaster.getPartnerIds(), "partner");
}
if (permissionCheckList == null || permissionCheckList.isEmpty()){
Map<String, List<PartnerMaster>> updatePartnerDivision = partnerService.updatePartnerDivision(partnerMaster);
if (updatePartnerDivision.containsKey("before") && updatePartnerDivision.containsKey("after")) {
List<PartnerMaster> beforePartnerList = (List<PartnerMaster>) updatePartnerDivision.get("before");
List<PartnerMaster> afterPartnerList = (List<PartnerMaster>) updatePartnerDivision.get("after");
if ((beforePartnerList != null && !beforePartnerList.isEmpty())
&& (afterPartnerList != null && !afterPartnerList.isEmpty())
&& beforePartnerList.size() == afterPartnerList.size()) {
for (int i=0; i<beforePartnerList.size(); i++) {
try {
String mailType = CoConstDef.CD_MAIL_TYPE_PARTNER_CHANGED;
CoMail mailBean = new CoMail(mailType);
mailBean.setParamPartnerId(afterPartnerList.get(i).getPartnerId());
mailBean.setCompareDataBefore(beforePartnerList.get(i));
mailBean.setCompareDataAfter(afterPartnerList.get(i));
CoMailManager.getInstance().sendMail(mailBean);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
try {
CommentsHistory commentsHistory = new CommentsHistory();
commentsHistory.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
commentsHistory.setReferenceId(afterPartnerList.get(i).getPartnerId());
commentsHistory.setContents(afterPartnerList.get(i).getUserComment());
commentService.registComment(commentsHistory, false);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
} else {
return makeJsonResponseHeader(false, null, permissionCheckList);
}
return makeJsonResponseHeader();
}
@PostMapping(value = PARTNER.UPDATE_DESCRIPTION)
public @ResponseBody ResponseEntity<Object> updateDescription(
@RequestBody PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
try {
partnerService.updateDescription(partnerMaster);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader();
}
@ResponseBody
@PostMapping(value = PARTNER.NOTICE_TEXT)
public String noticeText(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
String fileType = req.getParameter("fileType");
ArrayList<Object> resultList = new ArrayList<Object>();
// 파일등록
List<UploadFile> list = new ArrayList<UploadFile>();
String fileId = req.getParameter("registFileId");
Map<String, MultipartFile> fileMap = req.getFileMap();
String fileExtension = StringUtils.getFilenameExtension(fileMap.get("myfile").getOriginalFilename());
// 파일 등록
try {
if (req.getContentType() != null && req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
if (fileId == null) {
list = fileService.uploadFile(req, file);
} else {
list = fileService.uploadFile(req, file, null, fileId);
}
}
if(fileExtension.equals("csv")) {
resultList = CommonFunction.checkCsvFileLimit(list);
} else {
resultList = CommonFunction.checkXlsxFileLimit(list);
}
if(resultList.size() > 0) {
return toJson(resultList);
}
} catch (Exception e) {
log.error(e.getMessage());
}
if ("text".equals(fileType)) {
resultList.add(list);
resultList.add(fileType);
resultList.add("TEXT_FILE");
return toJson(resultList);
} else if (fileExtension.equals("csv")) {
resultList.add(list);
resultList.add("BIN");
resultList.add("CSV_FILE");
return toJson(resultList);
} else {
// sheet이름
List<Object> sheetNameList = null;
try {
sheetNameList = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} catch (Exception e) {
log.error(e.getMessage());
}
Boolean isSpdxSpreadsheet = false;
for(Object sheet : sheetNameList) {
String sheetName = sheet.toString();
if(sheetName.contains("Package Info") || sheetName.contains("Per File Info")) {
isSpdxSpreadsheet = true;
}
}
if(isSpdxSpreadsheet){
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("SPDX_SPREADSHEET_FILE");
}
else {
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("EXCEL_FILE");
}
return toJson(resultList);
}
}
@PostMapping(value = PARTNER.SAVE_BINARY_DB)
public @ResponseBody ResponseEntity<Object> saveBinaryDB(@RequestBody PartnerMaster partner,
HttpServletRequest req, HttpServletResponse res, Model model) {
boolean resultFlag = false;
try {
PartnerMaster partnerMaster = new PartnerMaster();
partnerMaster.setPartnerId(partner.getPartnerId());
partnerMaster = partnerService.getPartnerMasterOne(partnerMaster);
String binaryFileId = partnerMaster.getBinaryFileId();
if(!isEmpty(binaryFileId)) {
ProjectIdentification paramPartner = new ProjectIdentification();
paramPartner.setReferenceId(partnerMaster.getPartnerId());
paramPartner.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
Map<String, Object> mapPartner = projectService.getIdentificationGridList(paramPartner);
// platform 정보
String platformName = "";
String platformVer = "";
String _partnerName = "[3rd-" + partnerMaster.getPartnerId() + "]" + partnerMaster.getPartnerName();
T2File binaryTextFile = fileService.selectFileInfo(partnerMaster.getBinaryFileId());
binaryDataService.insertBatConfirmBinOssWithChecksum(CoConstDef.CD_CHECK_OSS_PARTNER, _partnerName, platformName, platformVer, binaryTextFile, (List<ProjectIdentification>) mapPartner.get("mainData"));
resultFlag = true;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(resultFlag, null);
}
@PostMapping(value = PARTNER.CHECK_SELECT_DOWNLOAD_FILE)
public @ResponseBody ResponseEntity<Object> checkSelectDownloadFile(@RequestBody PartnerMaster partnerMaster, HttpServletRequest req, HttpServletResponse res, Model model){
Map<String, Object> resMap = new HashMap<>();
try {
resMap = partnerService.checkSelectDownloadFile(partnerMaster);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(resMap);
}
}
| 58,835 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ConfigurationController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ConfigurationController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.SearchType;
import oss.fosslight.common.Url.CONFIGURATION;
import oss.fosslight.domain.Configuration;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.service.ConfigurationService;
import oss.fosslight.service.SearchService;
import oss.fosslight.service.T2UserService;
@Controller
@Slf4j
public class ConfigurationController extends CoTopComponent {
@Autowired ConfigurationService configurationService;
@Autowired SearchService searchService;
@Autowired T2UserService userService;
@GetMapping(value=CONFIGURATION.EDIT, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
model.addAttribute("userInfo", userService.getLoginUserInfo());
return CONFIGURATION.EDIT_JSP;
}
@PostMapping(value=CONFIGURATION.SAVE_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> updateDefaultSetting(@ModelAttribute Configuration configuration, HttpServletRequest req, HttpServletResponse res){
HashMap<String,Object> resMap = new HashMap<>();
try {
configurationService.updateDefaultSetting(configuration);
resMap.put("resCd", "10");
} catch (Exception e) {
log.error(e.getMessage(), e);
resMap.put("resCd", "20");
}
return makeJsonResponseHeader(resMap);
}
@GetMapping(value=CONFIGURATION.VIEW_SEARCH_CONDITION_AJAX, produces = "text/html; charset=utf-8")
public String loadDefaultSearchCondition(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Configuration configuration, Model model){
Object searchFilter = searchService.getSearchFilter(configuration.getDefaultSearchType(), loginUserName());
if (searchFilter != null) {
model.addAttribute("searchBean", searchFilter);
} else {
switch (SearchType.valueOf(configuration.getDefaultSearchType())) {
case LICENSE:
model.addAttribute("searchBean", new LicenseMaster());
break;
case OSS:
model.addAttribute("searchBean", new OssMaster());
break;
case PROJECT:
case SELF_CHECK:
model.addAttribute("searchBean", new Project());
break;
case THIRD_PARTY:
model.addAttribute("searchBean", new PartnerMaster());
break;
default:
break;
}
}
model.addAttribute("defaultSearchType", configuration.getDefaultSearchType());
return CONFIGURATION.VIEW_SEARCH_CONDITION_JSP;
}
@PostMapping(value=CONFIGURATION.UPDATE_SEARCH_CONDITION_AJAX)
public @ResponseBody ResponseEntity<Object> updateDefaultSearchCondition(@RequestParam Map<String, Object> params, HttpServletRequest req, HttpServletResponse res){
Map<String,Object> resMap = new HashMap<>();
try {
// Check Comma separated Multiple Checkbox values
List<String> unnecessaryKeys = new ArrayList<>();
for (String key : params.keySet()) {
if (key.startsWith("chk_")) {
params.put(key.replaceFirst("chk_", ""), params.get(key));
unnecessaryKeys.add(key);
}
}
if (!unnecessaryKeys.isEmpty()) {
for (String key : unnecessaryKeys) {
params.remove(key);
}
}
searchService.saveSearchFilter(params, loginUserName());
resMap.put("resCd", "10");
} catch (Exception e) {
log.error(e.getMessage(), e);
resMap.put("resCd", "20");
}
return makeJsonResponseHeader(resMap);
}
// @PostMapping(value=CONFIGURATION.SAVE_DEFAULT_LOCALE_AJAX, produces = "text/html; charset=utf-8")
// public @ResponseBody ResponseEntity<Object> saveDefaultLocale(@ModelAttribute Configuration configuration, HttpServletRequest req, HttpServletResponse res){
// HashMap<String,Object> resMap = new HashMap<>();
// configurationService.updateDefaultLocale(configuration);
// resMap.put("resCd", "10");
// return makeJsonResponseHeader(resMap);
// }
}
| 4,950 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
NoticeController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/NoticeController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.NOTICE;
import oss.fosslight.domain.Notice;
import oss.fosslight.service.NoticeService;
import oss.fosslight.validation.T2CoValidationResult;
@Controller
public class NoticeController extends CoTopComponent {
@Autowired NoticeService noticeService;
@GetMapping(value=NOTICE.LIST, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return NOTICE.LIST_JSP;
}
@GetMapping(value=NOTICE.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
@ModelAttribute Notice vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
vo.setCurPage(page);
vo.setPageListSize(rows);
vo.setSortField(sidx);
vo.setSortOrder(sord);
return makeJsonResponseHeader(noticeService.getNoticeList(vo));
}
@PostMapping(value=NOTICE.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@ModelAttribute Notice vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
T2CoValidationResult vResult = validateWithAppendix(req, "PROC_MODE", "ADD");
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
noticeService.setNotice(vo);
return makeJsonResponseHeader();
}
@RequestMapping(value=NOTICE.PUBLISHED_NOTICE, method = {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody ResponseEntity<Object> getPublishedNotice(
@ModelAttribute Notice vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
return makeJsonResponseHeader(noticeService.getPublishedNotice(vo));
}
}
| 2,797 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
DashboardController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/DashboardController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.DASHBOARD;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.service.DashboardService;
@Controller
public class DashboardController extends CoTopComponent{
@Autowired DashboardService dashboardService;
@GetMapping(value=DASHBOARD.LIST)
public String list(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
model.addAttribute("userId", loginUserName());
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
return DASHBOARD.LIST_JSP;
}
@GetMapping(value=DASHBOARD.JOBSLIST)
public @ResponseBody ResponseEntity<Object> jobsListAjax(
Project project
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
project.setCurPage(page);
project.setPageListSize(rows);
return makeJsonResponseHeader(dashboardService.getDashboardJobsList(project));
}
@GetMapping(value=DASHBOARD.COMMENTLIST)
public @ResponseBody ResponseEntity<Object> commentsListAjax(
CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
commentsHistory.setCurPage(page);
commentsHistory.setPageListSize(rows);
return makeJsonResponseHeader(dashboardService.getDashboardCommentsList(commentsHistory));
}
@GetMapping(value=DASHBOARD.OSSLIST)
public @ResponseBody ResponseEntity<Object> ossListAjax(
OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
ossMaster.setCurPage(page);
ossMaster.setPageListSize(rows);
return makeJsonResponseHeader(dashboardService.getDashboardOssList(ossMaster));
}
@GetMapping(value=DASHBOARD.LICENSELIST)
public @ResponseBody ResponseEntity<Object> licenseListAjax(
LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
licenseMaster.setCurPage(page);
licenseMaster.setPageListSize(rows);
return makeJsonResponseHeader(dashboardService.getDashboardLicenseList(licenseMaster));
}
@PostMapping(value=DASHBOARD.READCONFIRM_ALL)
public @ResponseBody ResponseEntity<Object> readConfirmAll(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String resCd="00";
HashMap<String,Object> resMap = new HashMap<>();
dashboardService.readConfirmAll(commentsHistory);
resCd="10";
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
}
| 4,371 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SentMailController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SentMailController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.SENT_MAIL;
import oss.fosslight.domain.CoMail;
import oss.fosslight.service.SentMailService;
@Controller
public class SentMailController extends CoTopComponent {
@Autowired SentMailService sentMailService;
@GetMapping(value=SENT_MAIL.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return SENT_MAIL.PAGE_JSP;
}
@GetMapping(value=SENT_MAIL.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> codeList(
@ModelAttribute CoMail vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
vo.setCurPage(page);
vo.setPageListSize(rows);
vo.setSortField(sidx);
vo.setSortOrder(sord);
Map<String, Object> map = sentMailService.getMailList(vo);
return makeJsonResponseHeader(map);
}
}
| 1,789 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
StatisticsController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/StatisticsController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.STATISTICS;
import oss.fosslight.domain.Statistics;
import oss.fosslight.service.StatisticsService;
import oss.fosslight.util.StringUtil;
@Controller
public class StatisticsController extends CoTopComponent{
/** The statistics service. */
@Autowired StatisticsService statisticsService;
@GetMapping(value=STATISTICS.VIEW)
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
return STATISTICS.VIEW_JSP;
}
@GetMapping(value=STATISTICS.DIVISIONAL_PROJECT_CHART)
public @ResponseBody ResponseEntity<Object> divisionProjectChart(HttpServletRequest req
, HttpServletResponse res
, Model model) {
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String type = req.getParameter("categoryType");
String isRawData = req.getParameter("isRawData");
Statistics stat = new Statistics();
stat.setStartDate(startDate);
stat.setEndDate(endDate);
stat.setCategoryType(type);
stat.setIsRawData(isRawData);
return makeJsonResponseHeader(statisticsService.getDivisionalProjectChartData(stat));
}
@GetMapping(value=STATISTICS.MOST_USED_CHART)
public @ResponseBody ResponseEntity<Object> mostUsedChart(HttpServletRequest req
, HttpServletResponse res
, Model model) {
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String divisionNo = req.getParameter("divisionNo");
int pieSize = Integer.parseInt(req.getParameter("pieSize"));
String chartType = req.getParameter("chartType");
String isRawData = req.getParameter("isRawData");
Statistics stat = new Statistics();
stat.setStartDate(startDate);
stat.setEndDate(endDate);
if (divisionNo.contains(",")) {
String[] divisionNums = divisionNo.split(",");
stat.setDivisionNums(divisionNums);
}else {
stat.setDivisionNo(divisionNo);
}
stat.setPieSize(pieSize);
stat.setChartType(chartType);
stat.setIsRawData(isRawData);
return makeJsonResponseHeader(statisticsService.getMostUsedChartData(stat));
}
@GetMapping(value=STATISTICS.UPDATED_CHART)
public @ResponseBody ResponseEntity<Object> updatedOssChart(HttpServletRequest req
, HttpServletResponse res
, Model model) {
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String type = req.getParameter("categoryType");
String chartType = req.getParameter("chartType");
String isRawData = req.getParameter("isRawData");
Statistics stat = new Statistics();
stat.setStartDate(startDate);
stat.setEndDate(endDate);
stat.setCategoryType(type);
stat.setChartType(chartType);
stat.setIsRawData(isRawData);
if ("OSS".equals(chartType)) {
return makeJsonResponseHeader(statisticsService.getUpdatedOssChartData(stat));
} else { // LICENSE
return makeJsonResponseHeader(statisticsService.getUpdatedLicenseChartData(stat));
}
}
@GetMapping(value=STATISTICS.TRDPARTY_RELATED_CHART)
public @ResponseBody ResponseEntity<Object> trdPartyRelatedChart(HttpServletRequest req
, HttpServletResponse res
, Model model) {
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String type = req.getParameter("categoryType");
String isRawData = req.getParameter("isRawData");
if ("STT".equals(type)) {
type = "3rd" + type;
}
Statistics stat = new Statistics();
stat.setStartDate(startDate);
stat.setEndDate(endDate);
stat.setCategoryType(type);
stat.setIsRawData(isRawData);
return makeJsonResponseHeader(statisticsService.getTrdPartyRelatedChartData(stat));
}
@GetMapping(value=STATISTICS.USER_RELATED_CHART)
public @ResponseBody ResponseEntity<Object> userRelatedChart(HttpServletRequest req
, HttpServletResponse res
, Model model) {
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String isRawData = req.getParameter("isRawData");
Statistics stat = new Statistics();
stat.setStartDate(startDate);
stat.setEndDate(endDate);
stat.setIsRawData(isRawData);
return makeJsonResponseHeader(statisticsService.getUserRelatedChartData(stat));
}
@GetMapping(value=STATISTICS.STATISTICS_POPUP)
public String binarypopup (
@ModelAttribute Statistics statistics
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
String startDate = req.getParameter("startDate");
String endDate = req.getParameter("endDate");
String categoryType = req.getParameter("categoryType");
String divisionNo = req.getParameter("divisionNo");
String pieSize = req.getParameter("pieSize");
String chartType = req.getParameter("chartType");
model.addAttribute("chartName", req.getParameter("chartName"));
if (!StringUtil.isEmpty(startDate)) {
model.addAttribute("startDate", startDate);
}
if (!StringUtil.isEmpty(endDate)) {
model.addAttribute("endDate", endDate);
}
if (!StringUtil.isEmpty(categoryType)) {
model.addAttribute("categoryType", categoryType);
}
if (!StringUtil.isEmpty(divisionNo)) {
model.addAttribute("divisionNo", divisionNo);
}
if (!StringUtil.isEmpty(pieSize)) {
model.addAttribute("pieSize", pieSize);
}
if (!StringUtil.isEmpty(chartType)) {
model.addAttribute("chartType", chartType);
}
return STATISTICS.STATISTICS_POPUP_JSP;
}
}
| 6,591 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ExcelDownloadController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ExcelDownloadController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.EXCELDOWNLOAD;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Statistics;
import oss.fosslight.domain.T2File;
import oss.fosslight.service.FileService;
import oss.fosslight.util.ExcelDownLoadUtil;
@Controller
@Slf4j
public class ExcelDownloadController extends CoTopComponent {
@Resource private Environment env;
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
@Autowired FileService fileService;
@PostMapping(value = EXCELDOWNLOAD.EXCEL_POST)
public @ResponseBody ResponseEntity<Object> getExcelPost(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String downloadId = null;
try {
if (map.containsKey("extParam")) {
downloadId = ExcelDownLoadUtil.getExcelDownloadId((String)map.get("type"), (String)map.get("parameter"), RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX, (String)map.get("extParam"));
} else {
downloadId = ExcelDownLoadUtil.getExcelDownloadId((String)map.get("type"), (String)map.get("parameter"), RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
if (isEmpty(downloadId)){
return makeJsonResponseHeader(false, "overflow");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value = EXCELDOWNLOAD.EXCEL_POST_OSS)
public @ResponseBody ResponseEntity<Object> getExcelPostOss(@ModelAttribute OssMaster ossMaster,
HttpServletRequest req, HttpServletResponse res, Model model) {
String downloadId = null;
try {
downloadId = ExcelDownLoadUtil.getExcelDownloadIdOss("OSS", ossMaster , RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
if (isEmpty(downloadId)){
return makeJsonResponseHeader(false, "overflow");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@ResponseBody
@GetMapping(value = EXCELDOWNLOAD.FILE, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> getFile (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
T2File fileInfo = fileService.selectFileInfo(req.getParameter("id"));
return excelToResponseEntity(fileInfo.getLogiPath() + fileInfo.getLogiNm(), fileInfo.getOrigNm());
}
@SuppressWarnings("unchecked")
@GetMapping(value = EXCELDOWNLOAD.CHART_EXCEL)
public @ResponseBody ResponseEntity<Object> getChartExcel(@ModelAttribute OssMaster ossMaster,
HttpServletRequest req, HttpServletResponse res, Model model) {
String chartParams = req.getParameter("params");
Type collectionType = new TypeToken<List<Statistics>>() {}.getType();
List<Statistics> params = (List<Statistics>) fromJson(chartParams, collectionType);
String downloadId = null;
try {
downloadId = ExcelDownLoadUtil.getChartExcel(params, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
if (isEmpty(downloadId)){
return makeJsonResponseHeader(false, "overflow");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
}
| 4,879 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
OssController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/OssController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.*;
import oss.fosslight.common.Url.OSS;
import oss.fosslight.domain.*;
import oss.fosslight.repository.PartnerMapper;
import oss.fosslight.repository.ProjectMapper;
import oss.fosslight.service.*;
import oss.fosslight.util.ExcelDownLoadUtil;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoOssValidator;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Controller
@Slf4j
public class OssController extends CoTopComponent{
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
@Autowired OssService ossService;
@Autowired HistoryService historyService;
@Autowired CommentService commentService;
@Autowired ProjectMapper projectMapper;
@Autowired PartnerMapper partnerMapper;
@Autowired SelfCheckService selfCheckService;
@Autowired ProjectService projectService;
@Autowired PartnerService partnerService;
@Autowired AutoFillOssInfoService autoFillOssInfoService;
@Autowired SearchService searchService;
@Autowired LicenseService licenseService;
private final String SESSION_KEY_SEARCH = "SESSION_KEY_OSS_LIST";
@GetMapping(value={OSS.LIST}, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model){
OssMaster searchBean = null;
if (!CoConstDef.FLAG_YES.equals(req.getParameter("gnbF"))) {
deleteSession(SESSION_KEY_SEARCH);
searchBean = searchService.getOssSearchFilter(loginUserName());
if (searchBean == null) {
searchBean = new OssMaster();
}
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
searchBean = (OssMaster) getSessionObject(SESSION_KEY_SEARCH);
if (searchBean != null && searchBean.getCopyrights() != null && searchBean.getCopyrights().length > 0) {
String _str = "";
for (String s : searchBean.getCopyrights()) {
if (!isEmpty(_str)) {
_str += "\r\n";
}
_str += s;
}
searchBean.setCopyright(_str);
}
}
if (req.getParameter("ossName") != null) { // OSS List 로드 시 Default로 ossName 검색조건에 추가
if (searchBean == null) {
searchBean = new OssMaster();
}
searchBean.setOssName(req.getParameter("ossName"));
}
if (getSessionObject("defaultLoadYn") != null) {
model.addAttribute("defaultLoadYn", CoConstDef.FLAG_YES);
deleteSession("defaultLoadYn");
}
model.addAttribute("searchBean", searchBean);
return OSS.LIST_JSP;
}
@GetMapping(value={OSS.LIST_LINK}, produces = "text/html; charset=utf-8")
public String listLink(@PathVariable String ossName, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
OssMaster searchBean = null;
if (!isEmpty(ossName)) {
if (searchBean == null) {
searchBean = new OssMaster();
}
searchBean.setOssName(ossName);
searchBean.setOssNameAllSearchFlag(CoConstDef.FLAG_YES);
searchBean.setLinkFlag(CoConstDef.FLAG_YES);
}
if (getSessionObject("defaultLoadYn") != null) {
model.addAttribute("defaultLoadYn", CoConstDef.FLAG_YES);
deleteSession("defaultLoadYn");
}
model.addAttribute("searchBean", searchBean);
return OSS.LIST_JSP;
}
@GetMapping(value=OSS.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
Map<String, Object> map = null;
if ("Y".equals(req.getParameter("ignoreSearchFlag"))) {
map = new HashMap<>();
map.put("rows", new ArrayList<>());
return makeJsonResponseHeader(map);
}
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
if (sidx != null) {
sidx = sidx.split("[,]")[1].trim();
}
ossMaster.setSidx(sidx);
ossMaster.setCurPage(page);
ossMaster.setPageListSize(rows);
// download location check
List<String> values = Arrays.asList("https://", "http://", "www.");
String homepage =req.getParameter("homepage");
if (!values.contains(homepage)){
homepage = homepage.replaceFirst("^((http|https)://)?(www.)*", "");
homepage = homepage.replaceFirst("/$", "");
ossMaster.setHomepage(homepage);
}
if ("search".equals(req.getParameter("act"))) {
// 검색 조건 저장
putSessionObject(SESSION_KEY_SEARCH, ossMaster);
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
ossMaster = (OssMaster) getSessionObject(SESSION_KEY_SEARCH);
}
ossMaster.setSearchFlag(CoConstDef.FLAG_YES); // 화면 검색일 경우 "Y" export시 "N"
try {
map = ossService.getOssMasterList(ossMaster);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
CustomXssFilter.ossMasterFilter((List<OssMaster>) map.get("rows"));
return makeJsonResponseHeader(map);
}
@GetMapping(value=OSS.AUTOCOMPLETE_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteAjax(
OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<OssMaster> list = ossService.getOssNameList();
CustomXssFilter.ossMasterFilter(list);
return makeJsonResponseHeader(list);
}
@GetMapping(value={OSS.EDIT}, produces = "text/html; charset=utf-8")
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NEWOSS_DEFAULT_DATA, null)) != null) {
OssMaster bean = (OssMaster) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NEWOSS_DEFAULT_DATA, null), true);
model.addAttribute("ossName", avoidNull(bean.getOssName()));
model.addAttribute("ossVersion", avoidNull(bean.getOssVersion()));
model.addAttribute("downloadLocation", avoidNull(bean.getDownloadLocation()));
model.addAttribute("homepage", avoidNull(bean.getHomepage()));
if (!isEmpty(avoidNull(bean.getLicenseName()))) {
List<OssLicense> licenseList = new ArrayList<OssLicense>();
HashMap<String, Object> map = new HashMap<String, Object>();
int idx = 1;
for (String licenseNm : bean.getLicenseName().split(",")) {
LicenseMaster master = CoCodeManager.LICENSE_INFO.get(licenseNm);
OssLicense result = new OssLicense();
result.setOssLicenseIdx(""+idx);
result.setOssLicenseComb(idx == 1 ? "" : "AND");
if (master != null) {
String shortIDentifier = isEmpty(master.getShortIdentifier()) ? master.getLicenseName() : master.getShortIdentifier();
result.setLicenseId(master.getLicenseId());
result.setLicenseName(master.getLicenseName());
result.setLicenseNameEx(shortIDentifier);
result.setObligation(master.getObligation());
result.setObligationChecks(master.getObligationChecks());
} else {
result.setLicenseName(licenseNm);
result.setLicenseNameEx(licenseNm);
}
licenseList.add(result);
idx++;
}
map.put("rows", licenseList);
model.addAttribute("list", toJson(map));
}
model.addAttribute("copyright", avoidNull(bean.getCopyright()));
model.addAttribute("ossType", avoidNull(bean.getOssType()));
// nick name 체크
// oss name으로 nickname이 존재할 경우 초기 표시되어야함
// 표시되지 않은 상태에서 save시 기존 nickname이 모두 삭제됨
model.addAttribute("ossNickList", toJson(ossService.getOssNickNameListByOssName(bean.getOssName())));
List<String> downloadLocationList = new ArrayList<>();
downloadLocationList.add(avoidNull(bean.getDownloadLocation()));
model.addAttribute("downloadLocationList", toJson(downloadLocationList));
} else {
// 신규 등록시에도 ossNickList 은 필수(empty array를 설정)
List<String> nickList = new ArrayList<>();
model.addAttribute("ossNickList", toJson(nickList.toArray(new String[nickList.size()])));
List<String> downloadLocationList = new ArrayList<>();
model.addAttribute("downloadLocationList", toJson(downloadLocationList.toArray(new String[downloadLocationList.size()])));
}
return OSS.EDIT_JSP;
}
@GetMapping(value={OSS.EDIT_ID}, produces = "text/html; charset=utf-8")
public String edit(@PathVariable String ossId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
OssMaster ossMaster = new OssMaster(ossId);
Map<String, Object> map = ossService.getOssLicenseList(ossMaster);
ossMaster = ossService.getOssMasterOne(ossMaster);
if (ossMaster.getOssVersion() == null) {
ossMaster.setOssVersion("");
}
//getDetectedLicenses()는 detectedLicenses가 null이면 비어있는 ArrayList객체를 생성해서 반환함.
if (!ossMaster.getDetectedLicenses().get(0).isEmpty()) {
List<String> detectedLicenseNames = ossMaster.getDetectedLicenses();
Map<String, String> detectedLicenseIdByName = new HashMap<>();
for (String name : detectedLicenseNames) {
detectedLicenseIdByName.put(name, CommonFunction.getLicenseIdByName(name));
}
model.addAttribute("detectedLicenseIdByName", toJson(detectedLicenseIdByName));
} else {
model.addAttribute("detectedLicenseIdByName", null);
}
model.addAttribute("list", toJson(map));
model.addAttribute("detail", toJson(ossMaster));
model.addAttribute("ossId", ossMaster.getOssId());
// 참조 프로젝트 목록 조회
boolean projectListFlag = CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES);
if (projectListFlag) {
// 성능이슈로 이전 son system의 프로젝트 조회와 신규 FOSSLight Hub 프로젝트 조회를 union 하지 않고 각각 조회한다.
List<OssComponents> components = projectMapper.selectOssRefPrjList1(ossMaster);
// 참조 partner 목록 조회
List<PartnerMaster> componentsPartner = new ArrayList<PartnerMaster>();
boolean partnerFlag = CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES);
if (partnerFlag) {
componentsPartner = partnerMapper.selectOssRefPartnerList(ossMaster);
}
model.addAttribute("components", toJson(components));
model.addAttribute("componentsPartner", toJson(componentsPartner));
}
model.addAttribute("projectListFlag", projectListFlag);
List<Vulnerability> vulnInfoList = ossService.getOssVulnerabilityList2(ossMaster);
if (vulnInfoList != null && !vulnInfoList.isEmpty()) {
if (vulnInfoList.size() == 5) {
model.addAttribute("vulnListMore", "vulnListMore");
}
model.addAttribute("vulnInfoList", toJson(vulnInfoList));
}
List<String> nickList = new ArrayList<>();
model.addAttribute("ossNickList", toJson(nickList.toArray(new String[nickList.size()])));
List<String> downloadLocationList = new ArrayList<>();
model.addAttribute("downloadLocationList", toJson(downloadLocationList.toArray(new String[downloadLocationList.size()])));
return CommonFunction.isAdmin() ? OSS.EDIT_JSP : OSS.VIEW_JSP;
}
@GetMapping(value={OSS.POPUPLIST_ID}, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> getPopupList(@PathVariable String ossId, OssMaster ossMaster, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
ossMaster.setCurPage(page);
ossMaster.setPageListSize(rows);
Map<String, Object> map = null;
try{
map = ossService.getOssPopupList(ossMaster);
}catch(Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
@SuppressWarnings("unchecked")
@GetMapping(value={OSS.COPY_ID}, produces = "text/html; charset=utf-8")
public String copy(@PathVariable String ossId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
OssMaster ossMaster = new OssMaster(ossId);
String _version = req.getParameter("ossVersion");
boolean isVersionup = false;
if (_version != null) {
isVersionup = true;
}
Map<String, Object> map = ossService.getOssLicenseList(ossMaster);
ossMaster = ossService.getOssMasterOne(ossMaster);
if (isVersionup) {
ossMaster.setOssVersion(_version);
} else {
ossMaster.setOssName(ossMaster.getOssName());
ossMaster.setOssVersion(avoidNull(ossMaster.getOssVersion()) + "_Copied");
}
ossMaster.setOssLicenses((List<OssLicense>) map.get("rows"));
ossMaster.setOssId(null);
model.addAttribute("copyData", toJson(ossMaster));
List<String> nickList = new ArrayList<>();
model.addAttribute("ossNickList", toJson(nickList.toArray(new String[nickList.size()])));
List<String> downloadLocationList = new ArrayList<>();
model.addAttribute("downloadLocationList", toJson(downloadLocationList.toArray(new String[downloadLocationList.size()])));
return OSS.EDIT_JSP;
}
@PostMapping(value=OSS.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
Map<String, Object> resMap = new HashMap<String, Object>();
try {
resMap = ossService.saveOss(ossMaster);
resMap = ossService.sendMailForSaveOss(resMap);
} catch (Exception e) {
resMap.put("resCd", "00");
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(resMap);
}
@PostMapping(value={OSS.DEL_AJAX})
public @ResponseBody ResponseEntity<Object> delAjax(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String resCd="00";
HashMap<String, Object> resMap = new HashMap<>();
// mail 발송을 위해 삭제전 data 취득
OssMaster ossMailInfo = ossService.getOssInfo(ossMaster.getOssId(), true);
if (ossMailInfo.getOssNicknames() != null) {
ossMailInfo.setOssNickname(CommonFunction.arrayToString(ossMailInfo.getOssNicknames(), "<br>"));
}
putSessionObject("defaultLoadYn", true); // 화면 로드 시 default로 리스트 조회 여부 flag
try {
History h = ossService.work(ossMaster);
h.sethAction(CoConstDef.ACTION_CODE_DELETE);
historyService.storeData(h);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_OSS_DELETE);
mailBean.setParamOssId(ossMaster.getOssId());
mailBean.setComment(ossMaster.getComment());
mailBean.setParamOssInfo(ossMailInfo);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// 삭제처리
try {
ossService.deleteOssMaster(ossMaster);
resCd="10";
CoCodeManager.getInstance().refreshOssInfo();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value={OSS.MULTI_DEL_AJAX})
public @ResponseBody ResponseEntity<Object> multiDelAjax(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String resCd="00";
HashMap<String, Object> resMap = new HashMap<>();
String[] ossIds = ossMaster.getOssIds();
List<String> notDelOssList = new ArrayList<>();
for (String ossId : ossIds) {
String existOssCnt = ossService.checkExistOssConf(ossId);
if (Integer.parseInt(existOssCnt) > 0) {
OssMaster oss = CoCodeManager.OSS_INFO_BY_ID.get(ossId);
String notDelOss = oss.getOssName() + " (" + avoidNull(oss.getOssVersion(), "N/A") + ")";
notDelOssList.add(notDelOss);
} else {
OssMaster ossMailBean = ossService.getOssInfo(ossId, true);
OssMaster param = new OssMaster();
param.setOssId(ossId);
param.setOssName(ossMailBean.getOssName());
param.setComment(ossMaster.getComment());
param.setLoginUserName(loginUserName());
param.setCreatedDate(ossMailBean.getCreatedDate());
if (ossMailBean.getOssNicknames() != null) {
ossMailBean.setOssNickname(CommonFunction.arrayToString(ossMailBean.getOssNicknames(), "<br>"));
}
putSessionObject("defaultLoadYn", true); // 화면 로드 시 default로 리스트 조회 여부 flag
try {
History h = ossService.work(param);
h.sethAction(CoConstDef.ACTION_CODE_DELETE);
historyService.storeData(h);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_OSS_DELETE);
mailBean.setParamOssId(ossId);
mailBean.setComment(param.getComment());
mailBean.setParamOssInfo(ossMailBean);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// 삭제처리
try {
ossService.deleteOssMaster(param);
resCd="10";
CoCodeManager.getInstance().refreshOssInfo();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
resMap.put("resCd", resCd);
if (notDelOssList != null && !notDelOssList.isEmpty()) resMap.put("notDelOssList", notDelOssList);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=OSS.DEL_OSS_VERSION_MERGE_AJAX)
public @ResponseBody ResponseEntity<Object> delOssWithVersionMeregeAjax(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String resCd="00";
HashMap<String, Object> resMap = new HashMap<>();
try {
ossService.deleteOssWithVersionMerege(ossMaster);
resCd = "10";
putSessionObject("defaultLoadYn", true); // 화면 로드 시 default로 리스트 조회 여부 flag
} catch (Exception e) {
log.error(e.getMessage(), e);
}
resMap.put("resCd", resCd);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=OSS.VALIDATION)
public @ResponseBody ResponseEntity<Object> validation(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
/*Json String -> Json Object*/
String jsonString = ossMaster.getOssLicensesJson();
Type collectionType = new TypeToken<List<OssLicense>>(){}.getType();
@SuppressWarnings("unchecked")
List<OssLicense> list = ossService.checkLicenseId((List<OssLicense>) fromJson(jsonString, collectionType) );
ossMaster.setOssLicenses(list);
// validator
T2CoOssValidator validator = new T2CoOssValidator();
Map<String, String> reqMap = new HashMap<>();
// form data set(with request)
validator.saveRequest(req, reqMap);
validator.setAppendix("ossMaster", ossMaster);
validator.setIgnore("LICENSE_TYPE");
T2CoValidationResult vr = validator.validateObject(reqMap, list, "OSS");
if (CoConstDef.FLAG_YES.equals(ossMaster.getRenameFlag())) {
boolean sameNameFlag = false;
boolean ossNicknameFlag= false;
OssMaster ossInfo = ossService.getOssInfo(ossMaster.getOssId(), false);
if (ossInfo != null && ossInfo.getOssName().equals(ossMaster.getOssName())) {
if (ossMaster.getOssNicknames() != null) {
if (ossInfo.getOssNicknames() != null) {
if (ossMaster.getOssNicknames().length == ossInfo.getOssNicknames().length) {
List<String> duplicateOssNicknames = Arrays.asList(ossMaster.getOssNicknames()).stream().filter(e -> !Arrays.asList(ossInfo.getOssNicknames()).contains(e.toString())).collect(Collectors.toList());
if (duplicateOssNicknames == null || duplicateOssNicknames.size() == 0) {
ossNicknameFlag = true;
}
}
}
}else {
if (ossInfo.getOssNicknames() == null) {
ossNicknameFlag = true;
}
}
if (ossNicknameFlag) {
return makeJsonResponseHeader(false, "rename");
}
}
List<String> checkList = new ArrayList<>();
List<String> duplicatedList = new ArrayList<>();
checkList.add(ossMaster.getOssName());
if (CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossMaster.getOssName().toUpperCase())) {
duplicatedList.add(ossMaster.getOssName());
return makeJsonResponseHeader(false, "rename", duplicatedList);
}
if (ossMaster.getOssNicknames() != null) {
for (String _nick : ossMaster.getOssNicknames()) {
if (!isEmpty(_nick)) {
if (ossMaster.getOssName().equals(_nick) || checkList.contains(_nick)) {
duplicatedList.add(_nick + " (The same OSS Name or Nick Name exists.)");
sameNameFlag = true;
break;
}
if (checkList.isEmpty() || !checkList.contains(_nick)) {
checkList.add(_nick);
}
}
}
}
if (sameNameFlag) {
return makeJsonResponseHeader(false, "rename", duplicatedList);
}
duplicatedList = ossService.getOssNicknameListWithoutOwn(ossInfo, checkList, duplicatedList);
if (duplicatedList != null && duplicatedList.size() > 0) {
return makeJsonResponseHeader(false, "rename", duplicatedList);
}
if (!vr.isValid()) {
Map<String, String> errMap = vr.getErrorCodeMap();
Map<String, String> checkErrMap = new HashMap<>();
for (String key : errMap.keySet()) {
if (!key.contains("OSS_NAME") && !key.contains("OSS_NICKNAMES")) {
checkErrMap.put(key, errMap.get(key));
}
}
vr.setErrorCodeMap(checkErrMap);
}
}
if (!vr.isValid()) {
return makeJsonResponseHeader(vr.getValidMessageMap());
}
if (isEmpty(ossMaster.getOssId())) {
OssMaster checkOssInfo = ossService.getOssInfo(ossMaster.getOssId(), ossMaster.getOssName(), false);
if (checkOssInfo != null && CoConstDef.FLAG_YES.equals(checkOssInfo.getDeactivateFlag())) {
return makeJsonResponseHeader(false, "deactivate");
} else {
// 신규 등록인 경우 nick name 체크(변경된 사항이 있는 경우, 삭제는 불가)
String[] _mergeNicknames = ossService.checkNickNameRegOss(ossMaster.getOssName(), ossMaster.getOssNicknames());
// 삭제는 불가능하기 때문에, 건수가 다르면 기존에 등록된 닉네임이 있다는 의미
// null을 반환하지는 않는다.
if (_mergeNicknames.length > 0) {
return makeJsonResponseHeader(false, null, _mergeNicknames);
}
}
} else {
// 수정이면서 oss name이 변경되었고, 변경하려고 하는 oss에 nick name이 등록되어 있는 경우, 사용자 confirm 필요
// 변경전 정보를 취득
OssMaster orgBean = ossService.getOssInfo(ossMaster.getOssId(), false);
if (CoConstDef.FLAG_YES.equals(ossMaster.getDeactivateFlag())
&& CoConstDef.FLAG_YES.equals(orgBean.getDeactivateFlag())) {
return makeJsonResponseHeader(false, "deactivate");
}
// oss name 변경 여부 확인
if (orgBean != null && !ossMaster.getOssName().equalsIgnoreCase(orgBean.getOssNameTemp())) {
// 기존 oss name 이 변경되었는데, oss nick name 까지 동시에 변경 할 경우 제외
String[] orgNickNames = ossService.getOssNickNameListByOssName(orgBean.getOssNameTemp());
if (orgNickNames != null && orgNickNames.length > 0) {
boolean ossNameCheck = false;
if (ossMaster.getOssNicknames() != null) {
if (orgNickNames.length != ossMaster.getOssNicknames().length) {
ossNameCheck = true;
} else {
if (!Arrays.equals(orgNickNames, ossMaster.getOssNicknames())){
ossNameCheck = true;
}
}
} else {
ossNameCheck = true;
}
if (ossNameCheck) {
return makeJsonResponseHeader(false, "notChange");
}
}
List<String> orgNickList = new ArrayList<>();
List<String> delNickList = new ArrayList<>();
// oss name이 변경 되었고, 변경 후 oss name이 이미 등록되어 있는 경우
Map<String, List<String>> diffMap = new HashMap<>();
String[] orgNicks = ossService.getOssNickNameListByOssName(ossMaster.getOssName());
if (orgNicks != null && orgNicks.length > 0) {
for (String s : orgNicks) {
orgNickList.add(s);
}
}
// 기존 oss name에 물려있는 nick name이 존재하는 경우, nick name은 무시됨
// 변경 후 oss name에 nick name이 존재하는 경우 이관됨
if (ossMaster.getOssNicknames() != null) {
for (String _nick : ossMaster.getOssNicknames()) {
if (!isEmpty(_nick)) {
// 삭제되는 oss
if (orgNickList.isEmpty() || !orgNickList.contains(_nick)) {
delNickList.add(_nick);
}
}
}
}
// 변경하려는 oss name에 nick name이 등록되어 있는 상태이면 merge 해야함
if (!orgNickList.isEmpty()) {
boolean isChange = !delNickList.isEmpty();
if (!isChange) {
// 대상 nick name과 현재 oss name이 동일하면 pass
List<String> currNickNameList = new ArrayList<>();
if (ossMaster.getOssNicknames() != null) {
for (String _nick : ossMaster.getOssNicknames()) {
if (!isEmpty(_nick)) {
currNickNameList.add(_nick);
}
}
}
if (orgNickList.size() != currNickNameList.size()) {
isChange = true;
}
for (String s : orgNickList) {
if (!currNickNameList.contains(s)) {
isChange = true;
break;
}
}
}
if (isChange) {
diffMap.put("addNickArr", orgNickList);
if (!delNickList.isEmpty()) {
diffMap.put("delNickArr", delNickList);
}
return makeJsonResponseHeader(false, "hasDelNick", diffMap);
}
}
}
}
return makeJsonResponseHeader();
}
@GetMapping(value = OSS.CHECK_EXIST_OSS_CONF)
public @ResponseBody String checkExistOssConf(HttpServletRequest req, HttpServletResponse res,
Model model, @RequestParam(value="ossId", required=true)String ossId) {
return ossService.checkExistOssConf(ossId);
}
@SuppressWarnings("unchecked")
@PostMapping(value = OSS.CHECK_VD_DIFF)
public @ResponseBody ResponseEntity<Object> checkVdiff(@RequestBody HashMap<String, Object> map, HttpServletRequest req, HttpServletResponse res,
Model model) {
Map<String, Object> reqMap = new HashMap<>();
reqMap.put("ossId", (String) map.get("ossId"));
reqMap.put("ossName", (String) map.get("ossName"));
if (map.containsKey("ossVersion")) reqMap.put("ossVersion", (String) map.get("ossVersion"));
Type collectionType = new TypeToken<List<OssLicense>>(){}.getType();
List<OssLicense> list = ossService.checkLicenseId((List<OssLicense>) fromJson((String) map.get("license"), collectionType));
reqMap.put("license", list);
HashMap<String, Object> resMap = new HashMap<>();
resMap.put("vFlag", ossService.checkVdiff(reqMap));
return makeJsonResponseHeader(resMap);
}
@PostMapping(value = OSS.SAVE_COMMENT)
public @ResponseBody ResponseEntity<Object> saveComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
T2CoValidationResult vResult = null;
try {
// validation check
vResult = validate(req);
} catch (Exception e) {
log.error(e.getMessage());
}
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
CommentsHistory result = null;
try {
result = commentService.registComment(commentsHistory);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(result);
}
@PostMapping(value=OSS.DELETE_COMMENT)
public @ResponseBody ResponseEntity<Object> deleteComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
T2CoValidationResult vResult = null;
try {
//validation check
vResult = validate(req);
} catch(Exception e) {
log.error(e.getMessage());
}
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
try {
commentService.deleteComment(commentsHistory);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
@GetMapping(value=OSS.OSS_MERGE_CHECK_LIST, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> ossMergeCheckList(@PathVariable String ossId, @PathVariable String newOssId, OssMaster ossMaster, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
Map<String, Object> map = ossService.ossMergeCheckList(ossMaster);
return makeJsonResponseHeader(map);
}
@PostMapping(value=OSS.URL_DUPLICATE_VALIDATION)
public @ResponseBody ResponseEntity<Object> urlDuplicateValidation(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
// validator
T2CoOssValidator validator = new T2CoOssValidator();
validator.setAppendix("ossMaster", ossMaster);
String validType = ossMaster.getValidationType();
if (validator.VALID_DOWNLOADLOCATION.equals(validType)){
validator.setVALIDATION_TYPE(validator.VALID_DOWNLOADLOCATION);
} else if (validator.VALID_DOWNLOADLOCATIONS.equals(validType)){
validator.setVALIDATION_TYPE(validator.VALID_DOWNLOADLOCATIONS);
}else if (validator.VALID_HOMEPAGE.equals(validType)){
validator.setVALIDATION_TYPE(validator.VALID_HOMEPAGE);
}
T2CoValidationResult vr = validator.validateObject(ossMaster);
if (!vr.isDiff()) {
return makeJsonResponseHeader(true, null, null, null, vr.getDiffMessageMap());
}
return makeJsonResponseHeader();
}
@PostMapping(value=OSS.SAVE_SESSION_OSS_INFO)
public @ResponseBody ResponseEntity<Object> saveSessionOssInfo(
@ModelAttribute OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
OssMaster orgMaster = null;
if (!isEmpty(ossMaster.getOssName())) {
if (CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossMaster.getOssName().toUpperCase())) {
orgMaster = ossService.getLastModifiedOssInfoByName(ossMaster);
}else {
orgMaster = ossService.getSaveSesstionOssInfoByName(ossMaster);
}
}
if (orgMaster != null && !isEmpty(orgMaster.getOssId())) {
return makeJsonResponseHeader(true, orgMaster.getOssId());
} else {
try {
if (!putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NEWOSS_DEFAULT_DATA, null), ossMaster)) {
log.error("failed save session oss edit (new) ");
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
}
@GetMapping(value = OSS.OSS_LIST_BY_NAME)
public @ResponseBody ResponseEntity<Object> getOssIdCheck(
@ModelAttribute OssMaster bean, Model model) {
Map<String, List<OssMaster>> resultMap = new HashMap<>();
resultMap.put("ossList", ossService.getOssListByName(bean));
return makeJsonResponseHeader(resultMap);
}
// @GetMapping(value=OSS.OSS_BULK_REG, produces = "text/html; charset=utf-8")
// public String ossBulkRegPage(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Project bean, Model model){
// // oss list (oss name으로만)
// model.addAttribute("projectInfo", bean);
//
// return OSS.OSS_BULK_REG_JSP;
// }
// @GetMapping(value = OSS.OSS_BULK_REG_AJAX, produces = "text/html; charset=utf-8")
// public @ResponseBody ResponseEntity<Object> getOssBulkRegAjax(
// HttpServletRequest req,
// HttpServletResponse res,
// @ModelAttribute ProjectIdentification paramBean,
// Model model) {
//
// Map<String, OssMaster> resultMap = new HashMap<>();
// Map<String, OssMaster> resultMapVer = new HashMap<>();
// List<String> dupCheckList = new ArrayList<>();
//
// // 일괄등록 대상 Identification의 모든 components 정보를 취득한다.
// paramBean.setBulkRegistYn(CoConstDef.FLAG_YES);
// List<ProjectIdentification> componentList = projectMapper.selectIdentificationGridList(paramBean);
// int gridIdSeq = 0;
//
// if (componentList != null) {
// // 미등록 OSS List 정보를 추출한다.
// for (ProjectIdentification bean : componentList) {
// if (isEmpty(bean.getOssName()) || "-".equals(bean.getOssName())) {
// continue;
// }
//
// String chkKey = (bean.getOssName().trim() + "_" + avoidNull(bean.getOssVersion()).trim()).toUpperCase();
//
// // 중복체크
// if (dupCheckList.contains(chkKey)) {
// continue;
// }
//
// // exclude 제외
// if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
// continue;
// }
//
// if (!CoCodeManager.OSS_INFO_UPPER.containsKey(chkKey)) {
// // licnese 정보 취득
// ProjectIdentification licenseParam = new ProjectIdentification();
// licenseParam.setComponentId(bean.getComponentId());
// List<ProjectIdentification> licenseList = projectMapper.identificationSubGrid(licenseParam);
//
// String licenseName = CommonFunction.makeLicenseExpressionIdentify(licenseList);
//
// if (CommonFunction.isIgnoreLicense(licenseName)){
// continue;
// }
//
// // OSS Master 형으로 변경
// OssMaster ossBean = new OssMaster();
// ossBean.setOssName(bean.getOssName().trim());
// ossBean.setOssVersion(avoidNull(bean.getOssVersion()).trim());
// ossBean.setLicenseName(licenseName);
// ossBean.setDownloadLocation(bean.getDownloadLocation());
// ossBean.setHomepage(bean.getHomepage());
// ossBean.setCopyright(bean.getCopyrightText());
//
// // OSS Name이 등록되어 있는 경우, NickName을 치환한다.
// if (CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossBean.getOssName().toUpperCase())) {
// ossBean.setOssName(CoCodeManager.OSS_INFO_UPPER_NAMES.get(ossBean.getOssName().toUpperCase()));
//
// // 등록되어 있는 oss name인 경우 마지막으로 생성한 oss를 기준으로 사용자 입력정보를 무시하고 DB에 등록된 정보를 설정한다.
// OssMaster lastCreatedOssBean = ossService.getLastModifiedOssInfoByName(ossBean);
// if (lastCreatedOssBean != null && !isEmpty(lastCreatedOssBean.getOssId())) {
// OssMaster masterBean = CoCodeManager.OSS_INFO_BY_ID.get(lastCreatedOssBean.getOssId());
// ossBean.setLicenseName(CommonFunction.makeLicenseExpression(masterBean.getOssLicenses()));
// String downloadLocation = StringUtil.isEmpty(lastCreatedOssBean.getDownloadLocationGroup()) ? lastCreatedOssBean.getDownloadLocation() : lastCreatedOssBean.getDownloadLocationGroup();
// ossBean.setDownloadLocation(downloadLocation);
// ossBean.setHomepage(masterBean.getHomepage());
// ossBean.setCopyright(masterBean.getCopyright());
// ossBean.setSummaryDescription(masterBean.getSummaryDescription()); // OSS bulk registration > Summary Description란 추가
//
// // nickname 정보를 설정한다.
// if (masterBean.getOssNicknames() != null) {
// ossBean.setOssNickname(CommonFunction.arrayToString(masterBean.getOssNicknames(), ","));
// }
// }
//
// ossBean.setRegType("VER");
// } else {
// ossBean.setRegType("OSS");
// }
//
// ossBean.setGridId("jqg_" + gridIdSeq++);
//
// // default 정렬
// if (CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossBean.getOssName().toUpperCase())) {
// resultMapVer.put(chkKey, ossBean);
// } else {
// resultMap.put(chkKey, ossBean);
// }
//
// dupCheckList.add(chkKey);
//
// // nick name 을 정식명칭으로 변경한 case도 중복체크에 포함한다.
// String chkKey2 = (bean.getOssName().trim() + "_" + avoidNull(bean.getOssVersion()).trim()).toUpperCase();
//
// if (!chkKey.equals(chkKey2)) {
// dupCheckList.add(chkKey2);
// }
// }
// }
// }
//
// List<OssMaster> list = null;
//
// if (!resultMap.isEmpty()) {
// list = new ArrayList<>(resultMap.values()) ;
// }
//
// if (!resultMapVer.isEmpty()) {
// if (list == null) {
// list = new ArrayList<>(resultMapVer.values()) ;
// } else {
// list.addAll(new ArrayList<>(resultMapVer.values()));
// }
// }
//
// if (list == null) {
// list = new ArrayList<>();
// }
//
// T2CoOssValidator validator = new T2CoOssValidator();
// validator.setAppendix("ossList", list);
// validator.setVALIDATION_TYPE(validator.VALID_OSSLIST_BULK);
// T2CoValidationResult vr = validator.validate(new HashMap<>());
// Map<String, String> validMapResult = vr.getValidMessageMap();
// Map<String, String> diffMapResult = vr.getDiffMessageMap();
//
// HashMap<String, Object> resMap = new HashMap<>();
// resMap.put("ossList", list);
// resMap.put("validMapResult", validMapResult);
// resMap.put("diffMapResult", diffMapResult);
//
// return makeJsonResponseHeader(resMap);
// }
@GetMapping(value = OSS.OSS_BULK_REG, produces = "text/html; charset=utf-8")
public String LicenseBulkRegPage(HttpServletRequest req, HttpServletResponse res, Model model, @ModelAttribute Project projectData) {
model.addAttribute("projectData", projectData);
return OSS.OSS_BULK_REG_JSP;
}
@PostMapping(value = OSS.BULK_REG_AJAX)
public @ResponseBody
ResponseEntity<Object> saveAjaxJson(
@RequestBody List<OssMaster> ossMasters
, HttpServletRequest req
, HttpServletResponse res
, Model model) {
List<Map<String, Object>> ossDataMapList = new ArrayList<>();
Map<String, Object> resMap = new HashMap<>();
if (ossMasters.isEmpty()) {
//When the ossMaster List delivered from the client is empty (if the upload button is pressed without uploading the file)
resMap.put("res", false);
return makeJsonResponseHeader(resMap);
}
boolean licenseCheck;
for (OssMaster oss : ossMasters) {
Map<String, Object> ossDataMap = new HashMap<>();
oss.setOssCopyFlag(CoConstDef.FLAG_NO);
oss.setRenameFlag(CoConstDef.FLAG_NO);
oss.setAddNicknameYn(CoConstDef.FLAG_YES); // Append nickname only
licenseCheck = false;
LicenseMaster licenseMaster;
List<String> declaredLicenses = oss.getDeclaredLicenses();
String downloadLocation = oss.getDownloadLocation();
if (downloadLocation != null) {
oss.setDownloadLocations(downloadLocation.split(","));
}
boolean[] check = new boolean[declaredLicenses.size() + 1];
List<OssLicense> ossLicenses = new ArrayList<>();
int licenseCount = 1;
if (declaredLicenses == null || declaredLicenses.isEmpty()) {
log.debug("DeclaredLicenses is null:" + oss.getOssName());
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Required missing)");
ossDataMapList.add(ossDataMap);
continue;
}
if (Objects.isNull(oss.getOssName()) || StringUtil.isBlank(oss.getOssName())) {
log.debug("OSS name is required.");
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Required missing)");
ossDataMapList.add(ossDataMap);
continue;
}
for (String licenseName : declaredLicenses) {
licenseMaster = new LicenseMaster();
licenseMaster.setLicenseName(licenseName);
LicenseMaster existsLicense = licenseService.checkExistsLicense(licenseMaster);
if (existsLicense == null) {
log.debug("Unconfirmed license:" + licenseName);
licenseCheck = true;
break;
}
check[licenseCount - 1] = true;
OssLicense convert = new OssLicense();
convert.setLicenseId(existsLicense.getLicenseId());
convert.setLicenseName(existsLicense.getLicenseName());
if (licenseCount > 1) {
convert.setOssLicenseComb("AND");
} else {
convert.setOssLicenseComb("");
}
convert.setLicenseNameEx(existsLicense.getLicenseNameTemp());
convert.setLicenseType(existsLicense.getLicenseType());
if (CoConstDef.FLAG_YES.equals(avoidNull(existsLicense.getObligationNeedsCheckYn()))) {
convert.setObligation(CoConstDef.CD_DTL_OBLIGATION_NEEDSCHECK);
} else if (CoConstDef.FLAG_YES.equals(avoidNull(existsLicense.getObligationDisclosingSrcYn()))) {
convert.setObligation(CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE);
} else if (CoConstDef.FLAG_YES.equals(avoidNull(existsLicense.getObligationNotificationYn()))) {
convert.setObligation(CoConstDef.CD_DTL_OBLIGATION_NOTICE);
} else {
convert.setObligation("");
}
convert.setObligationChecks(existsLicense.getObligationChecks());
ossLicenses.add(convert);
licenseCount++;
}
for (String licenseName : oss.getDetectedLicenses()) {
licenseMaster = new LicenseMaster();
licenseMaster.setLicenseName(licenseName);
LicenseMaster existsLicense = licenseService.checkExistsLicense(licenseMaster);
if (existsLicense == null) {
log.debug("Unconfirmed license:" + licenseName);
licenseCheck = true;
break;
}
}
if (licenseCheck) {
log.debug("Add failed due to declared license:" + oss.getOssName());
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Unconfirmed license)");
ossDataMapList.add(ossDataMap);
continue;
}
for (int i = 0; i < ossLicenses.size(); i++) {
OssLicense ossLicense = ossLicenses.get(i);
if (!check[i]) {
continue;
}
if (licenseCount <= 2) {
ossLicense.setLicenseType("S");
} else {
ossLicense.setLicenseType("M");
}
}
oss.setOssLicenses(ossLicenses);
if (licenseCount > 2) {
oss.setLicenseDiv("M");
} else {
oss.setLicenseDiv("S");
}
boolean checkDuplicated = true;
if (ossService.checkExistsOss(oss) != null) {
log.debug("Same OSS, version already exists.:" + oss.getOssName() + " v" + oss.getOssVersion());
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Duplicated Version)");
ossDataMapList.add(ossDataMap);
checkDuplicated = false;
} else {
OssMaster nameCheck = new OssMaster();
nameCheck.setOssName(oss.getOssName());
nameCheck.setOssNameTemp(oss.getOssName());
OssMaster checkName = ossService.checkExistsOssNickname2(nameCheck);
if (checkName != null) {
log.debug(oss.getOssName() + " is stored as a nick in " + checkName.getOssName());
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Duplicated : " + oss.getOssName() + ")");
ossDataMapList.add(ossDataMap);
checkDuplicated = false;
}
}
if (checkDuplicated && oss.getOssNicknames() != null) {
for (String nick : oss.getOssNicknames()) {
OssMaster nickCheck = new OssMaster();
nickCheck.setOssName(nick);
nickCheck.setOssNameTemp(oss.getOssName());
OssMaster checkNick = ossService.checkExistsOssNickname(nickCheck);
if (checkNick != null) {
log.debug(nick + " is stored as a nick or name in " + checkNick.getOssName());
ossDataMap = ossService.getOssDataMap(oss.getGridId(), false, "X (Duplicated : " + nick + ")");
ossDataMapList.add(ossDataMap);
checkDuplicated = false;
break;
}
}
}
if (checkDuplicated) {
Map<String, Object> result = ossService.saveOss(oss);
result = ossService.sendMailForSaveOss(result);
if (result.get("resCd").equals("10")) {
ossDataMap = ossService.getOssDataMap(oss.getGridId(), true, "O");
ossDataMapList.add(ossDataMap);
}
}
}
resMap.put("res", true);
resMap.put("value", ossDataMapList);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=Url.OSS.BULK_VALIDATION)
public @ResponseBody ResponseEntity<Object> bulkValidation(
@RequestBody List<OssMaster> ossMasters){
Map<String, Object> resMap = new HashMap<>();
T2CoOssValidator validator = new T2CoOssValidator();
validator.setAppendix("ossList", ossMasters);
validator.setVALIDATION_TYPE(validator.VALID_OSSLIST_BULK);
T2CoValidationResult vr = validator.validate(new HashMap<>());
resMap.put("validData", vr.getValidMessageMap());
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=OSS.SAVE_OSS_BULK_REG)
public @ResponseBody ResponseEntity<Object> saveOssBulkReg(
@RequestBody OssMaster ossMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
// 이미등록되어 있는 OSS의 경우 Skip한다.
if (CoCodeManager.OSS_INFO_UPPER.containsKey( (ossMaster.getOssName() + "_" + avoidNull(ossMaster.getOssVersion())).toUpperCase() )) {
return makeJsonResponseHeader(true, "Skip");
}
// validator
T2CoOssValidator validator = new T2CoOssValidator();
validator.setAppendix("ossMaster", ossMaster);
validator.setVALIDATION_TYPE(validator.VALID_OSS_BULK);
T2CoValidationResult vr = validator.validate(new HashMap<>());
Map<String, String> validMapResult = vr.getValidMessageMap();
Map<String, String> diffMapResult = vr.getDiffMessageMap();
HashMap<String, Object> resMap = new HashMap<>();
resMap.put("validMapResult", validMapResult);
resMap.put("diffMapResult", diffMapResult);
if (!vr.isValid()) {
return makeJsonResponseHeader(resMap);
}
// 기존에 동일한 이름으로 등록되어 있는 OSS Name인 지 확인
boolean isNewVersion = CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossMaster.getOssName().toUpperCase());
if (isNewVersion) {
ossMaster.setExistOssNickNames(ossService.getOssNickNameListByOssName(ossMaster.getOssName()));
}
ossMaster.setLicenseDiv(CoConstDef.LICENSE_DIV_SINGLE); // default
// multi license 대응
List<OssLicense> ossLicenseList = new ArrayList<>();
int licenseIdx = 0;
for (String s : ossMaster.getLicenseName().toUpperCase().split(" OR ")) {
// 순서가 중요
String orGroupStr = s.replaceAll("\\(", " ").replaceAll("\\)", " ");
boolean groupFirst = true;
for (String s2 : orGroupStr.split(" AND ")) {
LicenseMaster license = CoCodeManager.LICENSE_INFO_UPPER.get(s2.trim().toUpperCase());
OssLicense licenseBean = new OssLicense();
licenseBean.setOssLicenseIdx(String.valueOf(licenseIdx++));
licenseBean.setLicenseId(license.getLicenseId());
licenseBean.setLicenseName(license.getLicenseNameTemp());
licenseBean.setOssLicenseComb(groupFirst ? "OR" : "AND");
ossLicenseList.add(licenseBean);
groupFirst = false;
}
}
ossMaster.setOssLicenses(ossLicenseList);
if (ossLicenseList.size() > 1) {
ossMaster.setLicenseDiv(CoConstDef.LICENSE_DIV_MULTI);
}
// nick Name을 Array형으로 변경해줌
if (!isEmpty(ossMaster.getOssNickname())) {
// trim 처리는 registOssMaster 내에서 처리한다.
ossMaster.setOssNicknames(ossMaster.getOssNickname().split(","));
}
if (!isEmpty(ossMaster.getDownloadLocation())){
List<String> duplicateDownloadLocation = new ArrayList<>();
String result = "";
boolean isFirst = true;
for (String url : ossMaster.getDownloadLocation().split(",")) {
if (duplicateDownloadLocation.contains(url)) {
continue;
}
if (!isEmpty(result)) {
result += ",";
}
if (url.endsWith("/")) {
result += url.substring(0, url.length()-1);
}else {
result += url;
}
if (isFirst) {
ossMaster.setDownloadLocation(result);
isFirst = false;
}
duplicateDownloadLocation.add(url);
}
ossMaster.setDownloadLocations(result.split(","));
}
if (!isEmpty(ossMaster.getHomepage())) {
if (ossMaster.getHomepage().endsWith("/")) {
String homepage = ossMaster.getHomepage();
ossMaster.setHomepage(homepage.substring(0, homepage.length()-1));
}
}
// editor를 이용하지 않고, textarea로 등록된 코멘트의 경우 br 태그로 변경
ossMaster.setComment(CommonFunction.lineReplaceToBR(ossMaster.getComment()));
ossMaster.setAddNicknameYn(CoConstDef.FLAG_YES); //nickname을 clear&insert 하지 않고, 중복제거를 한 나머지 nickname에 대해서는 add함.
String resultOssId = "";
try {
resultOssId = ossService.registOssMaster(ossMaster);
} catch (Exception e) {
resMap.put("resCd", "00");
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false);
}
CoCodeManager.getInstance().refreshOssInfo();
History h = ossService.work(ossMaster);
h.sethAction(CoConstDef.ACTION_CODE_INSERT);
historyService.storeData(h);
// history 저장 성공 후 메일 발송
try {
CoMail mailBean = new CoMail(isNewVersion ? CoConstDef.CD_MAIL_TYPE_OSS_REGIST_NEWVERSION : CoConstDef.CD_MAIL_TYPE_OSS_REGIST);
mailBean.setParamOssId(resultOssId);
mailBean.setComment(ossMaster.getComment());
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(true, "Success", diffMapResult);
}
@GetMapping(value=OSS.OSS_POPUP, produces = "text/html; charset=utf-8")
public String viewOssPopup(HttpServletRequest req, HttpServletResponse res, @ModelAttribute OssMaster bean, Model model){
// oss list (oss name으로만)
model.addAttribute("ossInfo", bean);
return OSS.OSS_POPUP_JSP;
}
@GetMapping(value=OSS.OSS_DETAIL_VIEW_AJAX, produces = "text/html; charset=utf-8")
public String ossDetailView(HttpServletRequest req, HttpServletResponse res, @ModelAttribute OssMaster bean, Model model){
List<OssMaster> ossList = ossService.getOssListByName(bean);
if (ossList != null && !ossList.isEmpty()) {
OssMaster _bean = ossList.get(0);
_bean.setOssName(StringUtil.replaceHtmlEscape(_bean.getOssName()));
model.addAttribute("ossInfo", ossList.get(0));
CommentsHistory commentsHistory = new CommentsHistory();
commentsHistory.setReferenceId(bean.getOssId());
commentsHistory.setReferenceDiv("oss");
model.addAttribute("commentList", commentService.getCommentListHis(commentsHistory));
} else {
model.addAttribute("ossInfo", new OssMaster());
}
return OSS.OSS_DETAILS_VIEW_AJAX_JSP;
}
@GetMapping(value = OSS.CHECK_EXISTS_OSS_BY_NAME)
public @ResponseBody ResponseEntity<Object> checkExistsOssByname(
@ModelAttribute OssMaster bean, Model model) {
return makeJsonResponseHeader(ossService.checkExistsOssByname(bean) > 0, "unconfirmed oss");
}
@GetMapping(value = OSS.CHECK_OSS_LICENSE)
public String checkOssLicense(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Project bean, Model model){
model.addAttribute("projectInfo", bean);
return OSS.CHECK_OSS_LICENSE_JSP;
}
@SuppressWarnings("unchecked")
@GetMapping(value = OSS.CHECK_OSS_LICENSE_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> getCheckOssLicenseAjax(
HttpServletRequest req,
HttpServletResponse res,
@ModelAttribute ProjectIdentification paramBean,
Model model,
@PathVariable String targetName) {
Map<String, Object> resMap = new HashMap<>();
Map<String, Object> map = null;
List<ProjectIdentification> result = new ArrayList<ProjectIdentification>();
switch(targetName.toUpperCase()) {
case CoConstDef.CD_CHECK_OSS_SELF:
map = selfCheckService.getIdentificationGridList(paramBean);
break;
case CoConstDef.CD_CHECK_OSS_IDENTIFICATION:
map = projectService.getIdentificationGridList(paramBean);
break;
case CoConstDef.CD_CHECK_OSS_PARTNER:
map = partnerService.getIdentificationGridList(paramBean);
break;
}
// intermediate storage function correspondence : validation check when loading data
if (map != null) {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
List<ProjectIdentification> mainData = (List<ProjectIdentification>) map.get("mainData");
pv.setAppendix("mainList", mainData);
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
Map<String, String> validMap = vr.getValidMessageMap();
result.addAll(autoFillOssInfoService.checkOssLicenseData(mainData, validMap, null));
resMap.put("validMap", validMap);
}
if (!vr.isDiff()){
Map<String, String> diffMap = vr.getDiffMessageMap();
result.addAll(autoFillOssInfoService.checkOssLicenseData(mainData, null, diffMap));
resMap.put("diffMap", diffMap);
}
}
if (result.size() > 0) {
Map<String, Object> data = autoFillOssInfoService.checkOssLicense(result);
resMap.put("list", data.get("checkedData"));
resMap.put("error", data.get("error"));
}
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=OSS.SAVE_OSS_CHECK_LICENSE)
public @ResponseBody ResponseEntity<Object> saveOssCheckLicense(
@RequestBody ProjectIdentification paramBean
, HttpServletRequest req
, HttpServletResponse res
, Model model
, @PathVariable String targetName){
Map<String, Object> map = autoFillOssInfoService.saveOssCheckLicense(paramBean, targetName);
return makeJsonResponseHeader(map);
}
@GetMapping(value=OSS.CHECK_OSS_NAME, produces = "text/html; charset=utf-8")
public String checkOssName(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Project bean, Model model){
// oss list (oss name으로만)
model.addAttribute("projectInfo", bean);
return OSS.CHECK_OSS_NAME_JSP;
}
@SuppressWarnings("unchecked")
@GetMapping(value = OSS.CHECK_OSS_NAME_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> getCheckOssNameAjax(
HttpServletRequest req,
HttpServletResponse res,
@ModelAttribute ProjectIdentification paramBean,
Model model,
@PathVariable String targetName) {
Map<String, Object> resMap = new HashMap<>();
resMap = ossService.getCheckOssNameAjax(paramBean, targetName);
/*Map<String, Object> map = null;
List<ProjectIdentification> result = new ArrayList<ProjectIdentification>();
switch(targetName.toUpperCase()) {
case CoConstDef.CD_CHECK_OSS_SELF:
map = selfCheckService.getIdentificationGridList(paramBean);
break;
case CoConstDef.CD_CHECK_OSS_IDENTIFICATION:
map = projectService.getIdentificationGridList(paramBean);
break;
case CoConstDef.CD_CHECK_OSS_PARTNER:
map = partnerService.getIdentificationGridList(paramBean);
break;
}
// intermediate storage function correspondence : validation check when loading data
if (map != null) {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
List<ProjectIdentification> mainData = (List<ProjectIdentification>) map.get("mainData");
pv.setAppendix("mainList", mainData);
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
Map<String, String> validMap = vr.getValidMessageMap();
result.addAll(ossService.checkOssNameData(mainData, validMap, null));
resMap.put("validMap", validMap);
}
if (!vr.isDiff()){
Map<String, String> diffMap = vr.getDiffMessageMap();
result.addAll(ossService.checkOssNameData(mainData, null, diffMap));
resMap.put("diffMap", diffMap);
}
result.addAll(ossService.checkOssNameData(mainData, null, null));
}
if (result.size() > 0) {
result = ossService.checkOssName(result);
List<ProjectIdentification> valid = new ArrayList<ProjectIdentification>();
List<ProjectIdentification> invalid = new ArrayList<ProjectIdentification>();
for (ProjectIdentification prj : result){
if (prj.getCheckOssList().equals("I")){
invalid.add(prj);
} else{
valid.add(prj);
}
}
resMap.put("list", Stream.concat(valid.stream(), invalid.stream())
.collect(Collectors.toList()));
}*/
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=OSS.SAVE_OSS_CHECK_NAME)
public @ResponseBody ResponseEntity<Object> saveOssCheckName(
@RequestBody ProjectIdentification paramBean
, HttpServletRequest req
, HttpServletResponse res
, Model model
, @PathVariable String targetName){
Map<String, Object> map = ossService.saveOssCheckName(paramBean, targetName);
return makeJsonResponseHeader(map);
}
@PostMapping(value=OSS.SAVE_OSS_URL_NICKNAME)
public @ResponseBody ResponseEntity<Object> saveOssURLNickname(
@RequestBody ProjectIdentification paramBean
, HttpServletRequest req
, HttpServletResponse res
, Model model){
OssMaster beforeBean = ossService.getOssInfo(null, paramBean.getCheckName(), true);
Map<String, Object> map = ossService.saveOssURLNickname(paramBean);
boolean updatedFlag = (boolean) map.get("isValid");
if (updatedFlag) {
CoCodeManager.getInstance().refreshOssInfo();
String action = CoConstDef.ACTION_CODE_UPDATE;
OssMaster afterBean = ossService.getOssInfo(null, paramBean.getCheckName(), true);
History h = ossService.work(afterBean);
h.sethAction(action);
historyService.storeData(h);
// history 저장 성공 후 메일 발송
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_OSS_UPDATE);
mailBean.setParamOssId(afterBean.getOssId());
mailBean.setComment(afterBean.getComment());
mailBean.setCompareDataBefore(beforeBean);
mailBean.setCompareDataAfter(afterBean);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return makeJsonResponseHeader((boolean) map.get("isValid"), (String) map.get("returnType"));
}
@PostMapping(value=OSS.SAVE_OSS_NICKNAME)
public @ResponseBody ResponseEntity<Object> saveOssNickname(
@RequestBody ProjectIdentification paramBean
, HttpServletRequest req
, HttpServletResponse res
, Model model){
OssMaster beforeBean = ossService.getOssInfo(null, paramBean.getCheckName(), true);
Map<String, Object> map = ossService.saveOssNickname(paramBean);
boolean updatedFlag = (boolean) map.get("isValid");
if (updatedFlag) {
CoCodeManager.getInstance().refreshOssInfo();
String action = CoConstDef.ACTION_CODE_UPDATE;
OssMaster afterBean = ossService.getOssInfo(null, paramBean.getCheckName(), true);
History h = ossService.work(afterBean);
h.sethAction(action);
historyService.storeData(h);
// history 저장 성공 후 메일 발송
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_ADDNICKNAME_UPDATE);
mailBean.setParamOssId(afterBean.getOssId());
mailBean.setComment(afterBean.getComment());
mailBean.setCompareDataBefore(beforeBean);
mailBean.setCompareDataAfter(afterBean);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return makeJsonResponseHeader((boolean) map.get("isValid"), (String) map.get("returnType"));
}
@PostMapping(value=OSS.SAVE_OSS_ANALYSIS_LIST)
public @ResponseBody ResponseEntity<Object> saveOssAnalysisList(
@RequestBody OssMaster ossBean
, HttpServletRequest req
, HttpServletResponse res
, Model model
, @PathVariable String targetName){
Map<String, Object> map = ossService.saveOssAnalysisList(ossBean, targetName.toUpperCase());
return makeJsonResponseHeader((boolean) map.get("isValid"), (String) map.get("returnType"));
}
@RequestMapping(value=OSS.OSS_AUTO_ANALYSIS, method = {RequestMethod.POST, RequestMethod.GET}, produces = "text/html; charset=utf-8")
public String ossAutoRegist(HttpServletRequest req, HttpServletResponse res, @ModelAttribute Project bean, Model model){
// oss list (oss name으로만)
model.addAttribute("projectInfo", bean);
return OSS.OSS_AUTO_ANALYSIS_JSP;
}
@GetMapping(value=OSS.AUTO_ANALYSIS_LIST)
public @ResponseBody ResponseEntity<Object> getAutoAnalysisList(
HttpServletRequest req,
HttpServletResponse res,
@ModelAttribute OssMaster ossBean,
Model model) {
Map<String, Object> result = ossService.getOssAnalysisList(ossBean);
return makeJsonResponseHeader(result);
}
@PostMapping(value=OSS.START_ANALYSIS)
public @ResponseBody ResponseEntity<Object> startAnalysis(
@RequestBody OssMaster ossBean
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String downloadId = null;
Map<String, Object> result = null;
try {
downloadId = ExcelDownLoadUtil.getExcelDownloadId("autoAnalysis", ossBean.getPrjId(), RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
if (!isEmpty(downloadId)) {
result = ossService.startAnalysis(ossBean.getPrjId(), downloadId, null);
return makeJsonResponseHeader(result);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
result = new HashMap<String, Object>();
result.put("isValid", false);
result.put("returnMsg", "Failure");
return makeJsonResponseHeader(result);
}
@SuppressWarnings("unchecked")
@GetMapping(value=OSS.ANALYSIS_RESULT_LIST)
public @ResponseBody ResponseEntity<Object> getAnalysisResultList(
HttpServletRequest req,
HttpServletResponse res,
@ModelAttribute OssMaster ossMaster,
Model model) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
if (sidx != null) {
sidx = sidx.split("[,]")[1].trim();
}
ossMaster.setSidx(sidx);
if (page == 0) {
page = ossService.getAnalysisListPage(rows, ossMaster.getPrjId());
}
ossMaster.setCurPage(page);
ossMaster.setPageListSize(rows);
Map<String, Object> result = new HashMap<>();
Map<String, Object> map = new HashMap<>();
String analysisResultListPath = CommonFunction.emptyCheckProperty("autoanalysis.output.path", "/autoanalysis/out/dev") + "/" + ossMaster.getPrjId() + "/result";
map.put("analysisResultListPath", analysisResultListPath);
map = ExcelUtil.getCsvData(map, ossMaster);
if (map == null || map.isEmpty()) {
return makeJsonResponseHeader(result);
}
List<String[]> allData = (List<String[]>) map.get("csvData");
map = ossService.getOssAnalysisList(ossMaster);
result = ExcelUtil.readAnalysisList(allData, (List<OssAnalysis>) map.get("rows"));
if (!result.isEmpty()) {
// isValid - false(throws 발생) || true(data 조합)
if ((boolean) result.get("isValid")) {
CommonFunction.setAnalysisResultList(result);
result.put("page", (int) map.get("page"));
result.put("total", (int) map.get("total"));
result.put("records", (int) map.get("records"));
} else {
result.put("rows", new ArrayList<OssAnalysis>());
}
}
return makeJsonResponseHeader(result);
}
@SuppressWarnings("unchecked")
@PostMapping(value=OSS.SET_SESSION_ANALYSIS_RESULT_DATA)
public @ResponseBody ResponseEntity<Object> setSessionAnalysisResultData(
HttpServletRequest req,
HttpServletResponse res,
@RequestBody HashMap<String, Object> map,
Model model){
// oss list (oss name으로만)
String groupId = (String) map.get("groupId");
String dataString = (String) map.get("dataString");
Type typeAnalysis = new TypeToken<List<OssAnalysis>>() {}.getType();
List<OssAnalysis> analysisResultData = new ArrayList<OssAnalysis>();
analysisResultData = (List<OssAnalysis>) fromJson(dataString, typeAnalysis);
for (OssAnalysis oa : analysisResultData) {
if (oa.getTitle().contains("최신 등록 정보")) {
oa.setOssId(ossService.getOssInfo(null, oa.getOssName(), false).getOssId());
}
}
String sessionKey = CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_ANALYSIS_RESULT_DATA, groupId);
if (getSessionObject(sessionKey) != null) {
deleteSession(sessionKey);
}
return makeJsonResponseHeader(putSessionObject(sessionKey, analysisResultData));
}
@GetMapping(value=OSS.ANALYSIS_RESULT_DETAIL_ID)
public String analysisResultDetail(HttpServletRequest req, HttpServletResponse res, @PathVariable String groupId, Model model){
model.addAttribute("groupId", groupId);
return OSS.ANALYSIS_RESULT_DETAIL_JSP;
}
@SuppressWarnings("unchecked")
@PostMapping(value=OSS.SESSION_ANALYSIS_RESULT_DATA)
public @ResponseBody ResponseEntity<Object> getSessionAnalysisResultData(
HttpServletRequest req,
HttpServletResponse res,
@RequestBody OssAnalysis analysisBean,
Model model){
Map<String, Object> result = new HashMap<String, Object>();
String sessionKey = CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_ANALYSIS_RESULT_DATA, analysisBean.getGroupId());
List<OssAnalysis> detailData = (List<OssAnalysis>) getSessionObject(sessionKey);
if (detailData != null) {
for (OssAnalysis oa : detailData) {
if (ossService.checkOssTypeForAnalysisResult(oa)) oa.setOssType("V");
}
result.put("isValid", true);
result.put("detailData", detailData);
result.put("cloneLicenseData", new OssMaster());
CommonFunction.getAnalysisValidation(result, detailData);
} else {
result.put("isValid", false);
}
return makeJsonResponseHeader(result);
}
@PostMapping(value=OSS.UPDATE_ANALYSIS_COMPLETE)
public @ResponseBody ResponseEntity<Object> updateAnalysisComplete(
HttpServletRequest req,
HttpServletResponse res,
@RequestBody OssAnalysis analysisBean,
Model model){
Map<String, Object> result = null;
try {
result = ossService.updateAnalysisComplete(analysisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
result.put("isValid", false);
result.put("returnMsg", "Complete Failure");
}
return makeJsonResponseHeader(result);
}
@PostMapping(value=OSS.SAVE_OSS_ANALYSIS_DATA)
public @ResponseBody ResponseEntity<Object> saveOssAnalysisData(
@RequestBody OssAnalysis analysisBean
, HttpServletRequest req
, HttpServletResponse res
, Model model){
// 이미등록되어 있는 OSS의 경우 Skip한다.
if (CoCodeManager.OSS_INFO_UPPER.containsKey( (analysisBean.getOssName() + "_" + avoidNull(analysisBean.getOssVersion())).toUpperCase() )) {
return makeJsonResponseHeader(false, "Skip");
}
// analysis Data -> OssMaster 변환
OssMaster resultData = new OssMaster();
if (!isEmpty(analysisBean.getOssName())) {
resultData.setOssName(analysisBean.getOssName());
}
if (!isEmpty(analysisBean.getOssVersion())) {
resultData.setOssVersion(analysisBean.getOssVersion());
}
// 기존에 동일한 이름으로 등록되어 있는 OSS Name인 지 확인
boolean isNewVersion = CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(analysisBean.getOssName().toUpperCase());
if (isNewVersion) {
resultData.setExistOssNickNames(ossService.getOssNickNameListByOssName(resultData.getOssName()));
}
resultData.setGridId(analysisBean.getGridId());
resultData.setLicenseDiv(CoConstDef.LICENSE_DIV_SINGLE); // default
// multi license 대응
List<OssLicense> ossLicenseList = new ArrayList<>();
int licenseIdx = 0;
if (!isEmpty(analysisBean.getLicenseName())) {
// for (String s : analysisBean.getLicenseName().toUpperCase().split(" OR ")) {
// 순서가 중요
String orGroupStr = analysisBean.getLicenseName();
boolean multiLicenseFlag = false;
if (orGroupStr.contains(",")) {
multiLicenseFlag = true;
if (orGroupStr.startsWith("(")) {
orGroupStr = orGroupStr.substring(1, orGroupStr.length());
if (orGroupStr.endsWith(")")) {
orGroupStr = orGroupStr.substring(0, orGroupStr.length()-1);
}
}
}
// boolean groupFirst = true;
for (String s2 : orGroupStr.split(",")) {
LicenseMaster license = CoCodeManager.LICENSE_INFO_UPPER.get(s2.trim().toUpperCase());
OssLicense licenseBean = new OssLicense();
if (license != null) {
licenseBean.setOssLicenseIdx(String.valueOf(licenseIdx++));
licenseBean.setLicenseId(license.getLicenseId());
licenseBean.setLicenseName(license.getLicenseNameTemp());
if (multiLicenseFlag) licenseBean.setOssLicenseComb("AND");
} else {
licenseBean.setOssLicenseIdx(String.valueOf(licenseIdx++));
licenseBean.setLicenseId("");
licenseBean.setLicenseName(s2);
if (multiLicenseFlag) licenseBean.setOssLicenseComb("AND");
}
ossLicenseList.add(licenseBean);
// groupFirst = false;
}
// }
resultData.setLicenseName(analysisBean.getLicenseName());
resultData.setOssLicenses(ossLicenseList);
} else {
resultData.setLicenseName("");
}
if (ossLicenseList.size() > 1) {
resultData.setLicenseDiv(CoConstDef.LICENSE_DIV_MULTI);
}
// nick Name을 Array형으로 변경해줌
if (!isEmpty(analysisBean.getOssNickname())) {
// trim 처리는 registOssMaster 내에서 처리한다.
resultData.setOssNickname(analysisBean.getOssNickname());
resultData.setOssNicknames(analysisBean.getOssNickname().split(","));
}
if (!isEmpty(analysisBean.getDownloadLocation())){
String result = "";
for (String url : analysisBean.getDownloadLocation().split(",")) {
if (!isEmpty(result)) {
result += ",";
}
if (url.endsWith("/")) {
result += url.substring(0, url.length()-1);
} else {
result += url;
}
}
resultData.setDownloadLocations(result.split(","));
resultData.setDownloadLocation(result);
} else {
resultData.setDownloadLocation("");
}
if (!isEmpty(analysisBean.getHomepage())) {
if (analysisBean.getHomepage().endsWith("/")) {
String homepage = analysisBean.getHomepage();
resultData.setHomepage(homepage.substring(0, homepage.length()-1));
} else {
resultData.setHomepage(analysisBean.getHomepage());
}
} else {
resultData.setHomepage("");
}
resultData.setCopyright(analysisBean.getOssCopyright());
resultData.setSummaryDescription(analysisBean.getSummaryDescription());
// editor를 이용하지 않고, textarea로 등록된 코멘트의 경우 br 태그로 변경
resultData.setComment(CommonFunction.lineReplaceToBR(analysisBean.getComment()) );
resultData.setAddNicknameYn(CoConstDef.FLAG_YES); //nickname을 clear&insert 하지 않고, 중복제거를 한 나머지 nickname에 대해서는 add함.
HashMap<String, Object> resMap = new HashMap<>();
try {
// validator
T2CoOssValidator validator = new T2CoOssValidator();
validator.setAppendix("ossAnalysis", analysisBean);
validator.setVALIDATION_TYPE(validator.VALID_OSSANALYSIS);
T2CoValidationResult vr = validator.validate(new HashMap<>());
Map<String, String> validMapResult = vr.getValidMessageMap();
Map<String, String> diffMapResult = vr.getDiffMessageMap();
resMap.put("validMapResult", validMapResult);
resMap.put("diffMapResult", diffMapResult);
if (!vr.isValid()) {
return makeJsonResponseHeader(false, "Fail", resMap);
}
} catch (Exception e) {
log.error(e.getMessage());
return makeJsonResponseHeader(false, "Fail");
}
Map<String, Object> result = null;
String resultOssId = "";
try {
resultOssId = ossService.registOssMaster(resultData); // oss 정보 등록
analysisBean.setComponentId(analysisBean.getGroupId());
analysisBean.setReferenceOssId(resultOssId);
result = ossService.updateAnalysisComplete(analysisBean); // auto-analysis 완료처리
} catch(Exception e) {
resMap.put("resCd", "00");
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, "Fail");
}
CoCodeManager.getInstance().refreshOssInfo(); // 등록된 oss info 갱신
History h = ossService.work(resultData);
h.sethAction(CoConstDef.ACTION_CODE_INSERT);
historyService.storeData(h);
// history 저장 성공 후 메일 발송
try {
CoMail mailBean = new CoMail(isNewVersion ? CoConstDef.CD_MAIL_TYPE_OSS_REGIST_NEWVERSION : CoConstDef.CD_MAIL_TYPE_OSS_REGIST);
mailBean.setParamOssId(resultOssId);
mailBean.setComment(resultData.getComment());
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(result);
}
@GetMapping(value=OSS.OSS_SYNC_POPUP, produces = "text/html; charset=utf-8")
public String viewSyncOssPopup(HttpServletRequest req, HttpServletResponse res, @ModelAttribute OssMaster bean, Model model){
// oss list (oss name으로만)
model.addAttribute("ossInfo", bean);
return OSS.OSS_SYNC_POPUP_JSP;
}
@PostMapping(value=OSS.OSS_SYNC_LIST_VALIDATION)
public ResponseEntity<Object> ossSyncListValidation(HttpServletResponse res, Model model
, @RequestParam(value="ossId", required=true)String ossId
, @RequestParam(value="ossIds", required=true)String ossIds){
OssMaster bean = new OssMaster();
bean.setOssId(ossId);
try {
List<OssMaster> ossList = ossService.getOssListBySync(bean);
String[] ossIdArr = ossIds.split(",");
List<String> chkOssIdList = new ArrayList<String>();
for (int i=0; i<ossIdArr.length; i++) {
bean.setOssId(ossIdArr[i]);
List<OssMaster> syncCheckList = ossService.getOssListBySync(bean);
List<String> checkList = ossService.getOssListSyncCheck(syncCheckList, ossList);
if (checkList.size() == 0) {
chkOssIdList.add(ossIdArr[i]);
}
}
return makeJsonResponseHeader(true, "true", chkOssIdList);
} catch (Exception e){
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(false);
}
@GetMapping(value=OSS.OSS_SYNC_DETAIL_VIEW_AJAX, produces = "text/html; charset=utf-8")
public String ossSyncDetailView(HttpServletRequest req, HttpServletResponse res, @ModelAttribute OssMaster bean, Model model){
List<OssMaster> selectOssList = ossService.getOssListBySync(bean);
bean.setOssId(bean.getSyncRefOssId());
List<OssMaster> standardOssList = ossService.getOssListBySync(bean);
// sync check
List<String> syncCheckList = ossService.getOssListSyncCheck(selectOssList, standardOssList);
if (selectOssList != null && !selectOssList.isEmpty()) {
OssMaster _bean = selectOssList.get(0);
_bean.setOssName(StringUtil.replaceHtmlEscape(_bean.getOssName()));
model.addAttribute("ossInfo", selectOssList.get(0));
} else {
model.addAttribute("ossInfo", new OssMaster());
}
model.addAttribute("syncCheckList" , syncCheckList);
return OSS.OSS_SYNC_DETAILS_VIEW_AJAX_JSP;
}
@PostMapping(value=OSS.OSS_SYNC_UPDATE)
public ResponseEntity<Object> ossSyncUpdate(HttpServletResponse res, Model model
, @RequestParam(value="ossId", required=true)String ossId
, @RequestParam(value="ossName", required=true)String ossName
, @RequestParam(value="comment", required=true)String comment
, @RequestParam(value="ossIds", required=true)String ossIds
, @RequestParam(value="syncItem", required=true)String syncItem){
String[] ossIdsArr = ossIds.split(",");
String[] syncItemArr = syncItem.split(",");
String action = CoConstDef.ACTION_CODE_UPDATE;
OssMaster param = new OssMaster();
param.setOssId(ossId);
param.setOssName(ossName.trim());
try {
OssMaster standardOss = ossService.getOssMasterOne(param);
boolean declaredLicenseCheckFlag;
boolean detectedLicenseCheckFlag;
boolean downloadLocationCheckFlag;
boolean ossMasterCheclFlag;
boolean onlyCommentRegistFlag;
for (int i=0; i<ossIdsArr.length; i++) {
param.setOssId(ossIdsArr[i]);
OssMaster beforeBean = ossService.getOssMasterOne(param);
OssMaster syncBean = (OssMaster) BeanUtils.cloneBean(beforeBean);
syncBean.setCopyright(CommonFunction.brReplaceToLine(syncBean.getCopyright()));
syncBean.setSummaryDescription(CommonFunction.brReplaceToLine(syncBean.getSummaryDescription()));
syncBean.setAttribution(CommonFunction.brReplaceToLine(syncBean.getAttribution()));
if (syncBean.getLicenseDiv().contains("Single")) {
syncBean.setLicenseDiv("S");
}else {
syncBean.setLicenseDiv("M");
}
syncBean.setComment(comment);
declaredLicenseCheckFlag = false;
detectedLicenseCheckFlag = false;
downloadLocationCheckFlag = false;
ossMasterCheclFlag = false;
onlyCommentRegistFlag = false;
for (int j=0; j<syncItemArr.length; j++) {
switch(syncItemArr[j]) {
case "Declared License" :
if (!CommonFunction.makeLicenseExpression(standardOss.getOssLicenses()).equals(CommonFunction.makeLicenseExpression(syncBean.getOssLicenses()))) {
syncBean.setOssLicenses(standardOss.getOssLicenses());
syncBean.setLicenseName(CommonFunction.makeLicenseExpression(standardOss.getOssLicenses()));
if (standardOss.getLicenseDiv().contains("Single")) {
syncBean.setLicenseDiv("S");
}else {
syncBean.setLicenseDiv("M");
}
declaredLicenseCheckFlag = true;
}
break;
case "Detected License" :
if (syncBean.getDetectedLicenses() == null) {
if (standardOss.getDetectedLicenses() != null) {
syncBean.setDetectedLicenses(standardOss.getDetectedLicenses());
detectedLicenseCheckFlag = true;
}
}else {
if (standardOss.getDetectedLicenses() != null) {
if (!Arrays.equals(standardOss.getDetectedLicenses().toArray(), syncBean.getDetectedLicenses().toArray())) {
syncBean.setDetectedLicenses(standardOss.getDetectedLicenses());
detectedLicenseCheckFlag = true;
}
}else {
syncBean.setDetectedLicenses(standardOss.getDetectedLicenses());
detectedLicenseCheckFlag = true;
}
}
break;
case "Copyright" :
if (!standardOss.getCopyright().equals(syncBean.getCopyright())) {
syncBean.setCopyright(standardOss.getCopyright());
ossMasterCheclFlag = true;
}
break;
case "Download Location" :
if (standardOss.getDownloadLocations() != null) {
if (syncBean.getDownloadLocations() == null) {
syncBean.setDownloadLocations(standardOss.getDownloadLocations());
syncBean.setDownloadLocation(standardOss.getDownloadLocation());
downloadLocationCheckFlag = true;
}else {
if (!Arrays.equals(Arrays.asList(standardOss.getDownloadLocations()).toArray(), Arrays.asList(syncBean.getDownloadLocations()).toArray())){
syncBean.setDownloadLocations(standardOss.getDownloadLocations());
syncBean.setDownloadLocation(standardOss.getDownloadLocation());
downloadLocationCheckFlag = true;
}
}
}else {
if (syncBean.getDownloadLocations() != null) {
syncBean.setDownloadLocations(standardOss.getDownloadLocations());
syncBean.setDownloadLocation(standardOss.getDownloadLocation());
downloadLocationCheckFlag = true;
}
}
break;
case "Home Page" :
if (!standardOss.getHomepage().equals(syncBean.getHomepage())) {
syncBean.setHomepage(standardOss.getHomepage());
ossMasterCheclFlag = true;
}
break;
case "Summary Description" :
if (!standardOss.getSummaryDescription().equals(syncBean.getSummaryDescription())) {
syncBean.setSummaryDescription(standardOss.getSummaryDescription());
ossMasterCheclFlag = true;
}
break;
case "Attribution" :
if (!standardOss.getAttribution().equals(syncBean.getAttribution())) {
syncBean.setAttribution(standardOss.getAttribution());
ossMasterCheclFlag = true;
}
break;
}
}
if (!ossMasterCheclFlag && !declaredLicenseCheckFlag && !detectedLicenseCheckFlag && !downloadLocationCheckFlag){
if (!isEmpty(comment)) {
onlyCommentRegistFlag = true;
}
}
if ((ossMasterCheclFlag || declaredLicenseCheckFlag || detectedLicenseCheckFlag || downloadLocationCheckFlag) || onlyCommentRegistFlag) {
ossService.syncOssMaster(syncBean, declaredLicenseCheckFlag, detectedLicenseCheckFlag, downloadLocationCheckFlag);
if (!onlyCommentRegistFlag) {
History h = new History();
h = ossService.work(syncBean);
h.sethAction(action);
historyService.storeData(h);
}
beforeBean.setDownloadLocation(String.join(",", beforeBean.getDownloadLocations()));
OssMaster afterBean = ossService.getOssMasterOne(param);
afterBean.setDownloadLocation(String.join(",", afterBean.getDownloadLocations()));
try {
String mailType = CoConstDef.CD_MAIL_TYPE_OSS_UPDATE;
CoMail mailBean = new CoMail(mailType);
mailBean.setParamOssId(ossIdsArr[i]);
mailBean.setComment(comment);
mailBean.setCompareDataBefore(ossService.makeEmailSendFormat(beforeBean));
mailBean.setCompareDataAfter(ossService.makeEmailSendFormat(afterBean));
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
CoCodeManager.getInstance().refreshOssInfo();
return makeJsonResponseHeader(true, "true");
} catch (Exception e) {
log.error("OSS Sync Failed.", e);
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(false, "false");
}
@PostMapping(value=OSS.OSS_BULK_EDIT_POPUP)
public String bulkEditPopup(HttpServletRequest req, HttpServletResponse res,
@RequestParam(value="rowId", required=true)String rowId,
@RequestParam(value="target", required=true)String target,
Model model){
model.addAttribute("rowId", rowId);
model.addAttribute("target", target);
return OSS.OSS_BULK_EDIT_POPUP_JSP;
}
@PostMapping(value = OSS.CHECK_OSS_VERSION_DIFF)
public @ResponseBody ResponseEntity<Object> checkOssVersionDiff(@RequestBody HashMap<String, Object> map, HttpServletRequest req, HttpServletResponse res,
Model model) {
OssMaster om = new OssMaster();
om.setOssId((String) map.get("ossId"));
om.setOssName((String) map.get("ossName"));
HashMap<String, Object> resMap = new HashMap<>();
resMap.put("vFlag", ossService.checkOssVersionDiff(om));
return makeJsonResponseHeader(resMap);
}
@ResponseBody
@PostMapping(value = OSS.CSV_FILE)
public ResponseEntity<Object> csvFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
List<Object> limitCheckFiles = new ArrayList<>();
List<UploadFile> list = new ArrayList<UploadFile>();
List<OssMaster> ossList = new ArrayList<>();
Iterator<String> fileNames = req.getFileNames();
List<Map<String, Object>> ossWithStatusList = new ArrayList<>();
Map<String, Object> resMap = new HashMap<>();
while (fileNames.hasNext()) {
UploadFile uploadFile = new UploadFile();
MultipartFile multipart = req.getFile(fileNames.next());
uploadFile.setSize(multipart.getSize());
list.add(uploadFile);
}
limitCheckFiles = CommonFunction.checkXlsxFileLimit(list);
resMap.put("limitCheck", limitCheckFiles);
ossList = ExcelUtil.readOssList(req, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
if (ossList != null) {
Map<String, Object> ossWithStatus;
for (int i = 0; i < ossList.size(); i++) {
ossWithStatus = new HashMap<>();
ossWithStatus.put("oss", ossList.get(i));
ossWithStatus.put("status", "Ready");
ossWithStatusList.add(ossWithStatus);
}
} else {
resMap.put("res", false);
return makeJsonResponseHeader(resMap);
}
resMap.put("res", true);
resMap.put("value", ossWithStatusList);
return makeJsonResponseHeader(resMap);
}
}
| 87,347 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ProjectController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ProjectController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.PROJECT;
import oss.fosslight.common.CustomXssFilter;
import oss.fosslight.domain.CoMail;
import oss.fosslight.domain.CoMailManager;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.History;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.T2Users;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.repository.CodeMapper;
import oss.fosslight.service.BinaryDataService;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.PartnerService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SearchService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.service.VerificationService;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.OssComponentUtil;
import oss.fosslight.util.StringUtil;
import oss.fosslight.util.YamlUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Controller
@Slf4j
public class ProjectController extends CoTopComponent {
/** The file service. */
@Autowired FileService fileService;
/** The partner service. */
@Autowired PartnerService partnerService;
/** The project service. */
@Autowired ProjectService projectService;
/** The user service. */
@Autowired T2UserService userService;
/** The comment service. */
@Autowired CommentService commentService;
/** The history service. */
@Autowired HistoryService historyService;
@Autowired VerificationService verificationService;
@Autowired CodeMapper codeMapper;
@Autowired ResponseService responseService;
@Autowired SearchService searchService;
@Autowired private BinaryDataService binaryDataService;
/** The env. */
@Resource
private Environment env;
/** The session key search. */
private final String SESSION_KEY_SEARCH = "SESSION_KEY_PROJECT_LIST";
/**
* [화면] 프로젝트 목록 조회.
*
* @param req the req
* @param res the res
* @param model the model
* @return the string
*/
@GetMapping(value = PROJECT.LIST, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model) {
T2Users param = new T2Users();
param.setSortField("userName");
param.setSortOrder("asc");
// 여기까지 고정
// 전체 사용자 리스트
model.addAttribute("creator", userService.getAllUsers(param));
model.addAttribute("reviewer", userService.getReviwer());
Project searchBean = null;
Object _param = getSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + "OSSLISTMORE", true);
Object _param2 = getSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + "PARTNERLISTMORE", true);
if (_param != null) {
String defaultSearchOssId = (String) _param;
searchBean = new Project();
if (!isEmpty(defaultSearchOssId)) {
deleteSession(SESSION_KEY_SEARCH);
OssMaster ossBean = CoCodeManager.OSS_INFO_BY_ID.get(defaultSearchOssId);
if (ossBean != null) {
searchBean.setOssName(ossBean.getOssName());
searchBean.setOssVersion(ossBean.getOssVersion());
}
}
} else if (_param2 != null) {
String defaultSearchRefPartnerId = (String) _param2;
searchBean = new Project();
if (!isEmpty(defaultSearchRefPartnerId)) {
deleteSession(SESSION_KEY_SEARCH);
searchBean.setRefPartnerId(defaultSearchRefPartnerId);
}
} else {
if (!CoConstDef.FLAG_YES.equals(req.getParameter("gnbF"))) {
deleteSession(SESSION_KEY_SEARCH);
searchBean = searchService.getProjectSearchFilter(loginUserName());
if (searchBean == null) {
searchBean = new Project();
}
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
searchBean = (Project) getSessionObject(SESSION_KEY_SEARCH);
}
}
model.addAttribute("searchBean", searchBean);
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
CommonFunction.setProjectService(projectService);
return PROJECT.LIST_JSP;
}
/**
* Auto complete ajax.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.AUTOCOMPLETE_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
project.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
List<Project> list = projectService.getProjectNameList(project);
CustomXssFilter.projectFilter(list);
return makeJsonResponseHeader(list);
}
@GetMapping(value = PROJECT.AUTOCOMPLETE_ID_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteIdAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
project.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
List<Project> list = projectService.getProjectIdList(project);
return makeJsonResponseHeader(list);
}
/**
* Auto complete version ajax.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.AUTOCOMPLETE_VERSION_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteVersionAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
project.setCreator(CommonFunction.isAdmin() ? "ADMIN" : loginUserName());
return makeJsonResponseHeader(projectService.getProjectVersionList(project));
}
/**
* Auto complete model ajax.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.AUTOCOMPLETE_MODEL_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteModelAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
return makeJsonResponseHeader(projectService.getProjectModelNameList());
}
/**
* Gets the user id list.
*
* @param req the req
* @param res the res
* @param model the model
* @return the user id list
*/
@GetMapping(value = PROJECT.USER_ID_LIST)
public @ResponseBody String getUserIdList(HttpServletRequest req, HttpServletResponse res, Model model) {
String reviewerFlag = req.getParameter("reviewerFlag");
String userIdList = "";
if (CoConstDef.FLAG_YES.equals(reviewerFlag)) {
userIdList = projectService.getReviewerList(CoConstDef.FLAG_YES);
} else {
userIdList = projectService.getAdminUserList();
}
return userIdList;
}
/**
* [API] 프로젝트 목록 조회.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
if (project.getStatuses() != null) {
String statuses = project.getStatuses();
if (!isEmpty(statuses)){
String[] arrStatuses = statuses.split(",");
project.setArrStatuses(arrStatuses);
}
}
project.setPublicYn(isEmpty(project.getPublicYn())?CoConstDef.FLAG_YES:project.getPublicYn());
if ("search".equals(req.getParameter("act"))) {
// 검색 조건 저장
putSessionObject(SESSION_KEY_SEARCH, project);
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
project = (Project) getSessionObject(SESSION_KEY_SEARCH);
}
Map<String, Object> map = projectService.getProjectList(project);
@SuppressWarnings("unchecked")
List<Project> list = (List<Project>) map.get("rows");
for (Project prj : list) {
List<String> permissionCheckList = CommonFunction.checkUserPermissions("", new String[] {prj.getPrjId()}, "project");
if (permissionCheckList != null) {
if (prj.getPublicYn().equals(CoConstDef.FLAG_NO)
&& !CommonFunction.isAdmin()
&& !permissionCheckList.contains(loginUserName())) {
prj.setPermission(0);
prj.setStatusPermission(0);
} else {
if (!CommonFunction.isAdmin() && !permissionCheckList.contains(loginUserName())) {
prj.setStatusPermission(0);
} else {
prj.setStatusPermission(1);
}
prj.setPermission(1);
}
}
}
CustomXssFilter.projectFilter(list);
return makeJsonResponseHeader(map);
}
/**
* [화면] 프로젝트 상세.
*
* @param req the req
* @param res the res
* @param model the model
* @return the string
*/
@RequestMapping(value = { PROJECT.EDIT }, method = RequestMethod.GET, produces = "text/html; charset=utf-8")
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setNoticeType(CoConstDef.CD_GENERAL_MODEL);
project.setPriority(CoConstDef.CD_PRIORITY_P2);
Object _param = getSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + "PARTNER", true);
if (_param != null) {
String partnerKey = (String) _param;
if (!isEmpty(partnerKey)) {
deleteSession(SESSION_KEY_SEARCH);
String[] partnerArr = partnerKey.split("\\|\\|");
String refPartnerId = partnerArr[0];
String partnerName = partnerArr[1];
String softwareName = partnerArr[2];
project.setRefPartnerId(refPartnerId); // refPartnerId
String comment = "Copied from [3rd-" + refPartnerId + "] " + partnerName + " (" + softwareName.replace("[]", "/") + ")";
project.setComment(comment);
model.addAttribute("createThird", toJson(comment));
}
}
model.addAttribute("project", project);
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
return PROJECT.EDIT_JSP;
}
/**
* [API] 프로젝트 상세 조회.
*
* @param prjId the prj id
* @param req the req
* @param res the res
* @param model the model
* @return the string
*/
@RequestMapping(value = { PROJECT.EDIT_ID }, method = { RequestMethod.GET,
RequestMethod.POST }, produces = "text/html; charset=utf-8")
public String edit(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(prjId);
project = projectService.getProjectDetail(project);
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_USER);
comHisBean.setReferenceId(project.getPrjId());
project.setUserComment(commentService.getUserComment(comHisBean));
model.addAttribute("project", project);
model.addAttribute("detail", toJson(project));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
List<String> permissionCheckList = null;
boolean permissionFlag = false;
if (!CommonFunction.isAdmin()) {
CommonFunction.setProjectService(projectService);
project.setPrjIds(new String[] {prjId});
permissionCheckList = CommonFunction.checkUserPermissions("", project.getPrjIds(), "project");
if (permissionCheckList.contains(loginUserName())) {
permissionFlag = true;
}
}
if (project.getPublicYn().equals(CoConstDef.FLAG_NO)
&& !CommonFunction.isAdmin()
&& !permissionFlag) {
model.addAttribute("projectPermission", CoConstDef.FLAG_NO);
return PROJECT.VIEW_JSP;
} else {
if (!permissionFlag) {
List<T2Users> userList = userService.selectAllUsers();
if (userList != null) {
model.addAttribute("userWithDivisionList", userList);
}
}
return PROJECT.EDIT_JSP;
}
}
@RequestMapping(value = { PROJECT.VIEW_ID }, method = { RequestMethod.GET,
RequestMethod.POST }, produces = "text/html; charset=utf-8")
public String view(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(prjId);
try {
project = projectService.getProjectDetail(project);
if (CoConstDef.FLAG_YES.equals(project.getUseYn())) {
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_USER);
comHisBean.setReferenceId(prjId);
project.setUserComment(commentService.getUserComment(comHisBean));
model.addAttribute("project", project);
model.addAttribute("detail", toJson(project));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
if (CommonFunction.isAdmin()) {
List<T2Users> userList = userService.selectAllUsers();
if (userList != null) {
model.addAttribute("userWithDivisionList", userList);
}
}
} else {
model.addAttribute("message", "Reqeusted URL is for a deleted Project. Please contact the creator or watcher of the project.");
}
} catch (Exception e) {
model.addAttribute("message", "Reqeusted URL contains Project ID that doesn't exist. Please check the Project ID again.");
}
return PROJECT.VIEW_JSP;
}
/**
* [API] Identification 공통 메인 조회.
* Identification 각 Tab에 저장되어있는 SRC / BIN / BIN(Android) / BOM 정보를 반환한다.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @param prjId the prj id
* @param code the code
* @return the response entity
*/
@GetMapping(value = PROJECT.IDENTIFICATION_GRID_ID_CD)
public @ResponseBody ResponseEntity<Object> srcMainGridAjax(@ModelAttribute ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId,
@PathVariable String code) {
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(code)) {
String merge = req.getParameter("merge");
identification.setMerge(merge);
}
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PARTNER,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_DEP,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BAT,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_BAT,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), identification.getReferenceDiv(),
identification.getReferenceId()));
Map<String, Object> result = new HashMap<String, Object>();
try {
result = getOssComponentDataInfo(identification, code);
} catch (Exception e) {
log.error(e.getMessage(), e); // Identification에서 data를 호출할 때 문제가 발생한다면 error는 여기서 전부 모이게 됨.
}
if (result != null) {
CommonFunction.setDeduplicatedMessageInfo(result);
if (CoConstDef.CD_DTL_COMPONENT_BAT.equals(code) && isEmpty(identification.getReferenceId())
&& !isEmpty(identification.getRefBatId())) {
code = CoConstDef.CD_DTL_COMPONENT_ID_BAT;
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), code, prjId), result);
}
return makeJsonResponseHeader(result);
}
/**
* Gets the oss component data info.
*
* @param identification the identification
* @param code the code
* @return the oss component data info
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getOssComponentDataInfo(ProjectIdentification identification, String code) {
if (isEmpty(identification.getReferenceDiv())) {
identification.setReferenceDiv(code);
}
if (!isEmpty(identification.getMainData())) {
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {
}.getType();
identification.setMainDataGridList(
(List<ProjectIdentification>) fromJson(identification.getMainData(), collectionType2));
}
if (!isEmpty(identification.getSubData())) {
Type collectionType3 = new TypeToken<List<List<ProjectIdentification>>>() {
}.getType();
identification.setSubDataGridList(
(List<List<ProjectIdentification>>) fromJson(identification.getSubData(), collectionType3));
}
// bat apply 여부 flag
boolean isBatResult = !isEmpty(identification.getRefBatId());
boolean isSortOnBom = false;
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(code)) {
if (!isEmpty(identification.getSidxOrg())) {
String[] _sortIdxs = identification.getSidxOrg().split(",");
if (_sortIdxs.length == 2) {
if (!isEmpty(_sortIdxs[1].trim())) {
isSortOnBom = true;
}
identification.setSortField(_sortIdxs[1].trim());
identification.setSortOrder(identification.getSord());
}
}
String filterCondition = CommonFunction.getFilterToString(identification.getFilters());
if (!isEmpty(filterCondition)) {
identification.setFilterCondition(filterCondition);
}
}
Map<String, Object> map = projectService.getIdentificationGridList(identification, true);
T2CoProjectValidator pv = new T2CoProjectValidator();
if ((CoConstDef.CD_DTL_COMPONENT_ID_DEP.equals(code) || CoConstDef.CD_DTL_COMPONENT_ID_SRC.equals(code) || CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(code)) && map != null) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
if (CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(code)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BIN);
}
pv.setAppendix("projectId", avoidNull(identification.getReferenceId()));
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
map.replace("mainData", CommonFunction
.identificationSortByValidInfo((List<ProjectIdentification>) map.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false));
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
}
} else if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(code) && map != null) {
List<String> noticeBinaryList = null;
List<String> existsBinaryName = null;
if (!isEmpty(identification.getReferenceId())) {
// 다른 project에서 load하는 경우
if (CoConstDef.FLAG_YES.equals(identification.getLoadFromAndroidProjectFlag())) {
if (!isEmpty(identification.getAndroidNoticeFileId())) {
log.info("identification.getAndroidNoticeFileId() : OK");
noticeBinaryList = CommonFunction.getNoticeBinaryList(
fileService.selectFileInfoById(identification.getAndroidNoticeFileId()));
}
if (!isEmpty(identification.getAndroidResultFileId())) {
List<String> removedCheckList = null;
List<OssComponents> addCheckList = null;
log.info("identification.getAndroidResultFileId() : OK");
existsBinaryName = CommonFunction.getExistsBinaryNames(
fileService.selectFileInfoById(identification.getAndroidResultFileId()));
List<String> _checkExistsBinaryName = new ArrayList<>();
List<ProjectIdentification> _list = (List<ProjectIdentification>) map.get("mainData");
for (ProjectIdentification bean : _list) {
if (!isEmpty(bean.getBinaryName())) {
_checkExistsBinaryName.add(bean.getBinaryName());
}
}
T2File resultFileInfo = fileService.selectFileInfoById(identification.getAndroidResultFileId());
Map<String, Object> _resultFileInfoMap = CommonFunction.getAndroidResultFileInfo(resultFileInfo,
_checkExistsBinaryName);
if (_resultFileInfoMap.containsKey("removedCheckList")) {
removedCheckList = (List<String>) _resultFileInfoMap.get("removedCheckList");
}
if (_resultFileInfoMap.containsKey("addCheckList")) {
addCheckList = (List<OssComponents>) _resultFileInfoMap.get("addCheckList");
}
if (removedCheckList != null) {
for (ProjectIdentification bean : _list) {
if (removedCheckList.contains(bean.getBinaryName())) {
bean.setExcludeYn(CoConstDef.FLAG_YES);
}
}
}
if (addCheckList != null) {
// ossComponent에서 ProjectIdentification으로 변환
try {
OssComponentUtil.getInstance().makeOssComponent(addCheckList, true);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
log.error(e.getMessage());
}
for (OssComponents bean : addCheckList) {
ProjectIdentification _tempBean = new ProjectIdentification();
_tempBean.setBinaryName(bean.getBinaryName());
_tempBean.setFilePath(bean.getFilePath());
_tempBean.setBinaryNotice(bean.getBinaryNotice());
_tempBean.setOssName(bean.getOssName());
_tempBean.setOssVersion(bean.getOssVersion());
_tempBean.setLicenseName(bean.getLicenseName());
_tempBean.setDownloadLocation(bean.getDownloadLocation());
_tempBean.setHomepage(bean.getHomepage());
_tempBean.setCopyrightText(bean.getCopyrightText());
_tempBean.setExcludeYn(bean.getExcludeYn());
_tempBean.setEditable(CoConstDef.FLAG_YES);
_list.add(_tempBean);
}
}
map.replace("mainData", _list);
}
} else {
Project prjInfo = projectService.getProjectBasicInfo(identification.getReferenceId());
if (prjInfo != null) {
if (!isEmpty(prjInfo.getSrcAndroidNoticeXmlId())) {
noticeBinaryList = CommonFunction.getNoticeBinaryList(
fileService.selectFileInfoById(prjInfo.getSrcAndroidNoticeXmlId()));
}
if (isEmpty(prjInfo.getSrcAndroidNoticeXmlId()) && !isEmpty(prjInfo.getSrcAndroidNoticeFileId())) {
noticeBinaryList = CommonFunction.getNoticeBinaryList(
fileService.selectFileInfoById(prjInfo.getSrcAndroidNoticeFileId()));
}
if (!isEmpty(prjInfo.getSrcAndroidResultFileId())) {
existsBinaryName = CommonFunction.getExistsBinaryNames(
fileService.selectFileInfoById(prjInfo.getSrcAndroidResultFileId()));
}
}
}
}
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setAppendix("projectId", avoidNull(identification.getReferenceId()));
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
if (noticeBinaryList != null) {
pv.setAppendix("noticeBinaryList", noticeBinaryList);
}
if (existsBinaryName != null) {
pv.setAppendix("existsResultBinaryName", existsBinaryName);
}
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
map.replace("mainData", CommonFunction
.identificationSortByValidInfo((List<ProjectIdentification>) map.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false, true));
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
}
} else if ((CoConstDef.CD_DTL_COMPONENT_ID_BAT.equals(code) || CoConstDef.CD_DTL_COMPONENT_BAT.equals(code) || CoConstDef.CD_DTL_COMPONENT_PARTNER_BAT.equals(code))
&& map != null) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BAT);
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
if (!CoConstDef.CD_DTL_COMPONENT_BAT.equals(code)){
map.replace("mainData", CommonFunction
.identificationSortByValidInfo((List<ProjectIdentification>) map.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false));
}
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
}
} else if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(code) && map != null && map.containsKey("rows")
&& !((List<ProjectIdentification>) map.get("rows")).isEmpty()) {
map.replace("rows", projectService.setMergeGridData((List<ProjectIdentification>) map.get("rows")));
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BOM_MERGE);
pv.setAppendix("bomList", (List<ProjectIdentification>) map.get("rows"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
if (!isSortOnBom) {
map.replace("rows", CommonFunction
.identificationSortByValidInfo((List<ProjectIdentification>) map.get("rows"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false, true));
}
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
} else {
map.replace("rows", CommonFunction
.identificationSortByValidInfo((List<ProjectIdentification>) map.get("rows"), null, null, null, false, true));
}
} else if (CoConstDef.CD_DTL_COMPONENT_PARTNER.equals(code)) {
PartnerMaster partnerInfo = new PartnerMaster();
if (identification.getPartnerId() == null){
partnerInfo.setPartnerId(identification.getReferenceId());
}else{
partnerInfo.setPartnerId(identification.getPartnerId());
}
partnerInfo = partnerService.getPartnerMasterOne(partnerInfo);
if (partnerInfo != null) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_PARTNER);
// main grid
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
if ((CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST.equals(partnerInfo.getStatus())
|| CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REVIEW.equals(partnerInfo.getStatus()))
&& CommonFunction.isAdmin()) {
pv.setCheckForAdmin(true);
}
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
map.replace("mainData", CommonFunction.identificationSortByValidInfo(
(List<ProjectIdentification>) map.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false, true));
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
}
}
} else if (isBatResult) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BAT);
// main grid
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
map.replace("mainData", CommonFunction.identificationSortByValidInfo((List<ProjectIdentification>) map.get("mainData")
, vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false));
if (!vr.isValid()) {
map.put("validData", vr.getValidMessageMap());
}
if (!vr.isDiff()) {
map.put("diffData", vr.getDiffMessageMap());
}
if (vr.hasInfo()) {
map.put("infoData", vr.getInfoMessageMap());
}
}
}
return map;
}
/**
* [API] 프로젝트 상세 모델 목록 조회.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.MODELLIST_AJAX)
public @ResponseBody ResponseEntity<Object> modellistAjax(@ModelAttribute Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, List<Project>> map = projectService.getModelList(project.getPrjId());
if (map != null && !map.isEmpty() && CoConstDef.FLAG_YES.equals(project.getCopy())) {
List<Project> list = map.get("currentModelList");
if (list != null) {
List<Project> list2 = new ArrayList<>();
for (Project modelBean : list) {
modelBean.setReleaseDate(null);
modelBean.setModifier(null);
modelBean.setModifiedDate(null);
modelBean.setOsddSyncYn(null);
modelBean.setOsddSyncTime(null);
list2.add(modelBean);
}
map.put("currentModelList", list2);
}
}
return makeJsonResponseHeader(map);
}
/**
* [API] 카테고리 코드 조회.
*
* @param req the req
* @param res the res
* @param model the model
* @return the category code to json
*/
@GetMapping(value = PROJECT.CATEGORY_CODE_TOJSON)
public @ResponseBody ResponseEntity<Object> getCategoryCodeToJson(HttpServletRequest req, HttpServletResponse res,
Model model) {
String code = avoidNull(req.getParameter("code"), CoConstDef.CD_MODEL_TYPE);
return makeJsonResponseHeader(projectService.getCategoryCodeToJson(code));
}
/**
* [API] Identification OssNames 조회.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @return the oss names
*/
@GetMapping(value = PROJECT.OSS_NAMES)
public @ResponseBody ResponseEntity<Object> getOssNames(ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model) {
List<ProjectIdentification> list = projectService.getOssNames(identification);
return makeJsonResponseHeader(list);
}
/**
* [API] Identification OssVersions 조회.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @return the oss versions
*/
@GetMapping(value = PROJECT.OSS_VERSIONS)
public @ResponseBody ResponseEntity<Object> getOssVersions(ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model) {
String ossName = req.getParameter("ossName");
List<ProjectIdentification> list = projectService.getOssVersions(ossName);
return makeJsonResponseHeader(list);
}
/**
* [API] 프로젝트 목록 Reviewer 저장.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.UPDATE_REVIEWER)
public @ResponseBody ResponseEntity<Object> updateReviewer(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Project orgProject = projectService.getProjectBasicInfo(project.getPrjId());
String beforeReviewer = orgProject.getReviewer();
project.setModifier(project.getLoginUserName());
project.setModifiedDate(project.getCreatedDate());
if (!isEmpty(project.getReviewer()) && project.getReviewer().equals(orgProject.getReviewer())) {
return makeJsonResponseHeader();
}
projectService.updateReviewer(project);
try {
History h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (!isEmpty(project.getReviewer())) {
String mailType = isEmpty(beforeReviewer) ? CoConstDef.CD_MAIL_TYPE_PROJECT_REVIEWER_ADD : CoConstDef.CD_MAIL_TYPE_PROJECT_REVIEWER_CHANGED;
CoMail mailBean = new CoMail(mailType);
mailBean.setToIds(new String[] { orgProject.getReviewer(), project.getReviewer() }); // change reviewer 변경 전후 reviewer 전부에게 mail 전송
mailBean.setParamPrjId(project.getPrjId());
CoMailManager.getInstance().sendMail(mailBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader();
}
/**
* [API] 프로젝트 목록 Reject 저장.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.UPDATE_REJECT)
public @ResponseBody ResponseEntity<Object> updateReject(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
try {
project.setModifier(project.getLoginUserName());
project.setModifiedDate(project.getCreatedDate());
projectService.updateReject(project);
for (String prjId : project.getPrjIds()) {
project.setPrjId(prjId);
History h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader();
}
/**
* [API] 카테고리 코드 조회.
*
* @param req the req
* @param res the res
* @param model the model
* @return the category code
*/
@GetMapping(value = PROJECT.CATEGORY_CODE)
public @ResponseBody String getCategoryCode(HttpServletRequest req, HttpServletResponse res, Model model) {
String code = req.getParameter("code");
String gubun = req.getParameter("gubun");
return projectService.getCategoryCode(code, gubun);
}
/**
* [API] Comment Update.
*
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.UPDATE_COMMENT)
public @ResponseBody ResponseEntity<Object> updateComment(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
try {
projectService.updateComment(project);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader();
}
/**
* [API] 프로젝트 저장.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(@ModelAttribute Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
String jsonString = project.getPrjModelJson();
Type collectionType = new TypeToken<List<Project>>() {}.getType();
List<Project> list = (List<Project>) fromJson(jsonString, collectionType);
project.setModelList(list);
if (project.getWatchers() == null) {
String[] watcherArr = req.getParameterValues("watchers");
if (watcherArr == null) {
String watcherArrTemp = req.getParameter("watchers");
if (watcherArrTemp != null) {
String[] tempWatcherArr = {watcherArrTemp};
watcherArr = tempWatcherArr;
}
}
project.setWatchers(watcherArr);
}
Boolean isNew = StringUtil.isEmpty(project.getPrjId());
Project beforeBean = null;
Project afterBean = null;
String copy = req.getParameter("copy");
String confirmStatusCopy = req.getParameter("confirmStatusCopy");
String creatorIdByName = null;
if (CommonFunction.isAdmin() && !isNew && !"true".equals(copy)) {
if (!isEmpty(project.getCreatorNm())) {
List<T2Users> userList = userService.getUserListByName(project.getCreatorNm());
if (userList != null) {
for (T2Users _bean : userList) {
if (_bean.getUserId().equals(project.getCreator())) {
creatorIdByName = _bean.getUserId();
if (!creatorIdByName.equals(project.getCreator())) {
project.setCreator(_bean.getUserId());
}
break;
}
}
}
}
}
// validation check
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_BASICINFO);
Map<String, String> reqMap = new HashMap<>();
pv.saveRequest(req, reqMap);
if (!isEmpty(creatorIdByName)) {
reqMap.put("CREATOR_NM", creatorIdByName);
}
if ("true".equals(copy) && reqMap.containsKey("PRJ_ID")) {
reqMap.put("PRJ_ID", "");
}
T2CoValidationResult vr = pv.validateObject(reqMap, list);
if (!vr.isValid()) {
return makeJsonResponseHeader(vr.getValidMessageMap());
}
project.setCopy(copy);
try {
History h = new History();
if (isNew) {
projectService.registProject(project);
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_INSERT);
} else {
beforeBean = projectService.getProjectBasicInfo(project.getPrjId());
beforeBean.setModelList(projectService.getModelListExcel(project));
beforeBean.setWatcherList(projectService.getWatcherList(project));
projectService.registProject(project);
if (copy.equals("true") && (project.getNoticeType() != null && project.getNoticeType().equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED))) {
projectService.copySrcAndroidNoticeFile(project);
}
afterBean = projectService.getProjectBasicInfo(project.getPrjId());
afterBean.setModelList(list);
afterBean.setWatchers(project.getWatchers());
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
}
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
Map<String, String> lastResult = new HashMap<>();
lastResult.put("prjId", project.getPrjId());
String flag = "false";
if (!isNew && afterBean.getModelList() != null && afterBean.getModelList().size() > 0) {
if (beforeBean.getModelList() == null || beforeBean.getModelList().size() == 0) {
flag = "true";
} else {
for (int i=0; i < afterBean.getModelList().size(); i++){
int cnt = 0;
boolean ck_flag = false;
String after = afterBean.getModelList().get(i).getCategory()+"|"+afterBean.getModelList().get(i).getModelName()+"|"+afterBean.getModelList().get(i).getReleaseDate();
for (int j=0; j < beforeBean.getModelList().size(); j++){
String before = beforeBean.getModelList().get(j).getCategory()+"|"+beforeBean.getModelList().get(j).getModelName()+"|"+beforeBean.getModelList().get(j).getReleaseDate();
if (avoidNull(after).equals(before)){
cnt++;
}
if (!avoidNull(after).equals(before) && cnt == 0){
ck_flag = true;
}
}
if (cnt == 0 && ck_flag == true){
flag = "true";
}
}
}
}
lastResult.put("isAdd", flag);
String userComment = project.getUserComment();
if (!isEmpty(userComment) && !isEmpty(project.getPrjId())) {
CommentsHistory commentsHistory = new CommentsHistory();
commentsHistory.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_HIS);
commentsHistory.setReferenceId(project.getPrjId());
commentsHistory.setContents(userComment);
commentService.registComment(commentsHistory);
}
if (!isNew) {
try {
String mailType = "true".equals(copy)?CoConstDef.CD_MAIL_TYPE_PROJECT_COPIED:CoConstDef.CD_MAIL_TYPE_PROJECT_CHANGED;
String diffDivisionComment = "";
if (CoConstDef.CD_MAIL_TYPE_PROJECT_CHANGED.equals(mailType) && !beforeBean.getDivision().equals(afterBean.getDivision())){
diffDivisionComment = CommonFunction.getDiffItemComment(beforeBean, afterBean);
}
CoMail mailBean = new CoMail(mailType);
mailBean.setParamPrjId(project.getPrjId());
mailBean.setCompareDataBefore(beforeBean);
mailBean.setCompareDataAfter(afterBean);
if ("true".equals(copy)) {
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, CoConstDef.CD_MAIL_TYPE_PROJECT_COPIED));
userComment = avoidNull(userComment) + "<br />" + _tempComment;
}
mailBean.setComment(userComment);
CoMailManager.getInstance().sendMail(mailBean);
if (CoConstDef.CD_MAIL_TYPE_PROJECT_CHANGED.equals(mailType)){
String diffItemComment = CommonFunction.getDiffItemComment(beforeBean, afterBean, true);
try {
if (!isEmpty(diffItemComment) || !isEmpty(diffDivisionComment)) {
diffItemComment += diffDivisionComment;
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_HIS);
commHisBean.setReferenceId(project.getPrjId());
commHisBean.setContents(diffItemComment);
commHisBean.setStatus("Changed");
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else {
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PROJECT_CREATED);
mailBean.setParamPrjId(project.getPrjId());
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, CoConstDef.CD_MAIL_TYPE_PROJECT_CREATED));
userComment = avoidNull(userComment) + "<br />" + _tempComment;
mailBean.setComment(userComment);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if ((isNew || "true".equals(copy)) && !isEmpty(project.getPrjId()) && project.getWatchers() != null && project.getWatchers().length > 0) {
List<String> mailList = new ArrayList<>();
if (!isNew && !"true".equals(copy)) {
String[] arr;
List<String> emailList = new ArrayList<>();
List<String> emailList2 = new ArrayList<>();
for (String watcher : project.getWatchers()) {
arr = watcher.split("\\/");
if ("Email".equals(arr[1])){
if (!emailList.contains(arr[0])) {
emailList.add(arr[0]);
}
}
}
if (beforeBean.getWatcherList() != null && !beforeBean.getWatcherList().isEmpty()) {
for (Project _prj : beforeBean.getWatcherList()) {
emailList2.add(_prj.getPrjEmail());
}
}
for (String s : emailList) {
if (!emailList2.contains(s)) {
// 신규 추가 이면
mailList.add(s);
}
}
} else {
List<Project> _prjList = projectService.getWatcherList(project);
if (_prjList != null) {
for (Project _prj : _prjList) {
if (!StringUtil.isEmptyTrimmed(_prj.getPrjEmail())) {
String _mailAddr = _prj.getPrjEmail().trim();
if (!mailList.contains(_mailAddr)) {
mailList.add(_mailAddr);
}
}
}
}
}
if (!mailList.isEmpty()) {
for (String addr : mailList) {
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PROJECT_WATCHER_INVATED);
mailBean.setParamPrjId(project.getPrjId());
mailBean.setParamUserId(project.getLoginUserName());
mailBean.setParamEmail(addr);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
try {
// 1. 신규 생성 & partner id가 존재함. -> 이미 완료된 시점
if (isNew && !isEmpty(project.getRefPartnerId())) {
// 2. RefPartnerId 기준으로 OSS Component & OSS Component License Data -> Identification > 3rd Party에 copy함.
// 3. PROJECT_PARTNER_MAP 생성
// -> Identification > 3rd party save처리와 동일한 상태
projectService.addPartnerData(project);
// 4. merge and save 처리
projectService.registBom(project.getPrjId(), CoConstDef.FLAG_YES, new ArrayList<>(), new ArrayList<>()); // 신규생성이기 때문에 default Data가 없음.
// 5. validation check로 project status를 정리함.
ProjectIdentification identification = new ProjectIdentification();
identification.setReferenceId(project.getPrjId());
identification.setMerge(CoConstDef.FLAG_NO);
Map<String, Object> result = getOssComponentDataInfo(identification, CoConstDef.CD_DTL_COMPONENT_ID_BOM);
// 6. mail & comment를 남김.(status가 정리된 내용까지 전부 포함.)
Project prjBean = new Project();
prjBean.setPrjId(project.getPrjId());
prjBean.setIdentificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(project);
updateProjectNotification(project, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (!result.containsKey("validData")) {
// review Start에서는 status말고 변경되는 정보가 없어서 우선은 pass함.
prjBean.setIdentificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
prjBean.setIgnoreBinaryDbFlag(CoConstDef.FLAG_NO);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(prjBean);
updateProjectNotification(prjBean, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (copy.equals("true") && !confirmStatusCopy.equals("false")) {
Map<String, Object> copyConfirmStatusResultMap = updateCopyConfirmStatus(req, project, confirmStatusCopy, userComment);
if (copyConfirmStatusResultMap.get("result").equals("true")) {
lastResult.put("confirmCopyStatusSuccess", "true");
}else {
String falseStep = "";
if (copyConfirmStatusResultMap.get("step").equals("verificationProgress")) {
falseStep = "verification";
project.setIdentificationStatus(null);
project.setVerificationStatus(CoConstDef.CD_DTL_PROJECT_STATUS_PROGRESS);
} else {
falseStep = "identification";
project.setIdentificationStatus(CoConstDef.CD_DTL_PROJECT_STATUS_PROGRESS);
project.setVerificationStatus(null);
}
Project prj = projectService.getProjectBasicInfo(project.getPrjId());
if (falseStep.equals("verification") && !isEmpty(prj.getVerificationStatus())) {
project.setVerificationStatus(prj.getVerificationStatus());
}
projectService.updateCopyConfirmStatusProjectStatus(project);
lastResult.put("confirmCopyStatusSuccess", "false");
if (!confirmStatusCopy.equals("IdentificationProg")) {
lastResult.put("confirmCopyStatusFail", falseStep);
}
}
}
return makeJsonResponseHeader(true, null, lastResult);
}
@SuppressWarnings("unchecked")
private Map<String, Object> updateCopyConfirmStatus(HttpServletRequest req, Project project, String confirmStatusCopy, String userComment) {
log.info("copyConfirmStatus Start >>> " + project.getPrjId());
Map<String, Object> returnMap = new HashMap<String, Object>();
boolean identificationStatusRequest = false;
boolean identificationStatusConfirm = false;
if (!project.getNoticeType().equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED)) {
ProjectIdentification identification = new ProjectIdentification();
identification.setReferenceId(project.getCopyPrjId());
identification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BOM);
identification.setMerge(CoConstDef.FLAG_NO);
Map<String, Object> result = getOssComponentDataInfo(identification, CoConstDef.CD_DTL_COMPONENT_ID_BOM);
projectService.insertCopyConfirmStatusBomList(project, identification);
if (result.containsKey("validData") && (confirmStatusCopy.equals("IdentificationConf") || confirmStatusCopy.equals("verificationConf"))) {
log.error("copyConfirmStatus error >>> bom validation");
returnMap.put("result", "false");
returnMap.put("step", "IdentificationProgress");
return returnMap;
}
if (!result.containsKey("validData") && !confirmStatusCopy.equals("IdentificationProg")) {
project.setIdentificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(project);
resultMap.put("userComment", "");
updateProjectNotification(project, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
} finally {
identificationStatusRequest = true;
}
}
}else {
ProjectIdentification param = new ProjectIdentification();
param.setReferenceId(project.getPrjId());
param.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
Map<String, Object> map = null;
map = projectService.getIdentificationGridList(param);
if (map != null && map.containsKey("mainData")
&& !((List<ProjectIdentification>) map.get("mainData")).isEmpty()) {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setAppendix("mainList", (List<ProjectIdentification>) map.get("mainData"));
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) map.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
log.error("copyConfirmStatus error >>> mainData validation");
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
}
}else {
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
}
if (isEmpty(projectService.getProjectBasicInfo(project.getPrjId()).getSrcAndroidNoticeFileId())) {
log.error("copyConfirmStatus error > androidNoticeFile empty");
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
}
if (!confirmStatusCopy.equals("IdentificationProg")) {
project.setIdentificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(project);
resultMap.put("userComment", "");
updateProjectNotification(project, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
} finally {
identificationStatusRequest = true;
}
}
}
if (identificationStatusRequest) {
project.setIdentificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
project.setIgnoreBinaryDbFlag(CoConstDef.FLAG_NO);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(project);
resultMap.put("userComment", "");
updateProjectNotification(project, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "identificationProgress");
return returnMap;
} finally {
identificationStatusConfirm = true;
}
}
if (identificationStatusConfirm && confirmStatusCopy.equals("verificationConf")) {
Project prjInfo = projectService.getProjectBasicInfo(project.getPrjId());
Project copyPrjInfo = projectService.getProjectBasicInfo(project.getCopyPrjId());
if (!project.getNetworkServerType().equals(copyPrjInfo.getNetworkServerType())) {
returnMap.put("result", "false");
returnMap.put("step", "verificationProgress");
return returnMap;
}
String filePath = CommonFunction.emptyCheckProperty("packaging.path", "/upload/packaging");
List<String> fileSeqsList = projectService.getPackageFileList(project, filePath);
if (fileSeqsList.size() > 0) {
ProjectIdentification identification = new ProjectIdentification();
identification.setReferenceId(project.getPrjId());
identification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PACKAGING);
// verify
T2File file = new T2File();
file.setCreator(loginUserName());
List<Map<String, Object>> verifyResult = new ArrayList<Map<String,Object>>();
Map<String, Object> resMap = null;
List<String> filePathList = new ArrayList<>();
List<String> componentIdList = new ArrayList<>();
List<ProjectIdentification> ocList = projectService.selectIdentificationGridList(identification);
for (ProjectIdentification pi : ocList) {
filePathList.add(pi.getFilePath());
componentIdList.add(pi.getComponentId());
}
Map<Object, Object> map = new HashMap<>();
map.put("prjId", project.getPrjId());
map.put("fileSeqs", fileSeqsList);
map.put("gridFilePaths", filePathList);
map.put("gridComponentIds", componentIdList);
try {
boolean isChangedPackageFile = verificationService.getChangedPackageFile(project.getPrjId(), fileSeqsList);
int seq = 1;
for (String fileSeq : fileSeqsList){
map.put("fileSeq", fileSeq);
map.put("packagingFileIdx", seq++);
map.put("isChangedPackageFile", isChangedPackageFile);
verifyResult.add(verificationService.processVerification(map, file, project));
}
resMap = verifyResult.get(0);
if (fileSeqsList.size() > 1){
resMap.put("verifyValid", verifyResult.get(verifyResult.size()-1).get("verifyValid"));
resMap.put("fileCounts", verifyResult.get(verifyResult.size()-1).get("fileCounts"));
}
verificationService.updateVerifyFileCount((ArrayList<String>) resMap.get("verifyValid"));
verificationService.updateVerifyFileCount((HashMap<String,Object>) resMap.get("fileCounts"));
} catch(Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "verificationProgress");
return returnMap;
}
}
OssNotice ossNotice = verificationService.selectOssNoticeOne(project.getCopyPrjId());
ossNotice.setPrjId(project.getPrjId());
ossNotice.setNoticeType(avoidNull(project.getNoticeType(), avoidNull(copyPrjInfo.getNoticeType(), CoConstDef.CD_NOTICE_TYPE_GENERAL)));
verificationService.registOssNoticeConfirmStatus(ossNotice);
// download flag
prjInfo.setAllowDownloadNoticeHTMLYn(copyPrjInfo.getAllowDownloadNoticeHTMLYn());
prjInfo.setAllowDownloadNoticeTextYn(copyPrjInfo.getAllowDownloadNoticeTextYn());
prjInfo.setAllowDownloadSimpleHTMLYn(copyPrjInfo.getAllowDownloadSimpleHTMLYn());
prjInfo.setAllowDownloadSimpleTextYn(copyPrjInfo.getAllowDownloadSimpleTextYn());
prjInfo.setAllowDownloadSPDXSheetYn(copyPrjInfo.getAllowDownloadSPDXSheetYn());
prjInfo.setAllowDownloadSPDXRdfYn(copyPrjInfo.getAllowDownloadSPDXRdfYn());
prjInfo.setAllowDownloadSPDXTagYn(copyPrjInfo.getAllowDownloadSPDXTagYn());
prjInfo.setAllowDownloadSPDXJsonYn(copyPrjInfo.getAllowDownloadSPDXJsonYn());
prjInfo.setAllowDownloadSPDXYamlYn(copyPrjInfo.getAllowDownloadSPDXYamlYn());
verificationService.updateProjectAllowDownloadBitFlag(prjInfo);
boolean ignoreMailSend = false;
prjInfo.setIdentificationStatus(null);
prjInfo.setCompleteYn(null);
prjInfo.setVerificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_REQUEST);
prjInfo.setDestributionStatus(null);
prjInfo.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
try {
Map<String, Object> resultMap = projectService.updateProjectStatus(prjInfo);
resultMap.put("userComment", "");
updateProjectNotification(prjInfo, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "verificationProgress");
return returnMap;
}
prjInfo.setVerificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
prjInfo.setDestributionStatus(null);
/* if ("T".equals(avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_DISTRIBUTION_TYPE, project.getDistributionType())).trim().toUpperCase())
|| (CoConstDef.FLAG_NO.equals(avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_DISTRIBUTION_TYPE, project.getDistributionType())).trim().toUpperCase())
&& verificationService.checkNetworkServer(ossNotice.getPrjId())
)
|| CoConstDef.CD_NOTICE_TYPE_NA.equals(project.getNoticeType())
) {
prjInfo.setDestributionStatus(CoConstDef.CD_DTL_DISTRIBUTE_STATUS_NA);
} else {
ossNotice.setDomain(CommonFunction.getDomain(req));
try {
verificationService.getNoticeHtmlFile(ossNotice);
} catch(Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "verificationProgress");
return returnMap;
}
prjInfo.setDestributionStatus(null);
} */
prjInfo.setModifier(loginUserName());
try {
verificationService.updateStatusWithConfirm(prjInfo, ossNotice, true);
} catch(Exception e) {
log.error(e.getMessage(), e);
returnMap.put("result", "false");
returnMap.put("step", "verificationProgress");
return returnMap;
}
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(project.getPrjId());
commHisBean.setContents("");
commHisBean.setStatus(CoCodeManager.getCodeExpString(CoConstDef.CD_IDENTIFICATION_STATUS, CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM));
commentService.registComment(commHisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (prjInfo != null) {
String noticeUserComment = ossNotice.getUserComment();
try {
String mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_CONF;
String mailContentCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_CONF;
if (ignoreMailSend) {
mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_COMFIRMED_ONLY;
mailContentCode = mailTemplateCode;
} else if (CoConstDef.FLAG_YES.equals(prjInfo.getAndroidFlag())) {
mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_COMFIRMED_ONLY;
}
CoMail mailBean = new CoMail(mailTemplateCode);
mailBean.setParamPrjId(ossNotice.getPrjId());
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, mailContentCode));
noticeUserComment = avoidNull(noticeUserComment) + "<br />" + _tempComment;
if (!isEmpty(noticeUserComment)) {
mailBean.setComment(noticeUserComment);
}
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
verificationService.changePackageFileNameDistributeFormat(ossNotice.getPrjId());
}
}
returnMap.put("result", "true");
return returnMap;
}
/**
* [API] 프로젝트 삭제.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.DEL_AJAX)
public @ResponseBody ResponseEntity<Object> delAjax(@ModelAttribute Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Project projectInfo = projectService.getProjectDetail(project);
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_DELETE);
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PROJECT_DELETED);
mailBean.setParamPrjId(project.getPrjId());
if (!isEmpty(project.getUserComment())) {
mailBean.setComment(project.getUserComment());
}
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
String rtnFlag = "11"; // default error
HashMap<String, Object> resMap = new HashMap<>();
try {
projectService.deleteProject(project);
rtnFlag = "10"; // Success
try {
// Delete project ref files
projectService.deleteProjectRefFiles(projectInfo);
} catch (Exception e) {
log.error(e.getMessage());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
resMap.put("resCd", rtnFlag);
return makeJsonResponseHeader(resMap);
}
/**
* [API] Identification OssId Licenses 조회.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @return the oss id licenses
*/
@GetMapping(value = PROJECT.OSS_ID_LICENSES)
public @ResponseBody ResponseEntity<Object> getOssIdLicenses(ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model) {
String ossName = req.getParameter("ossName");
String ossVersion = req.getParameter("ossVersion");
identification.setOssName(ossName);
identification.setOssVersion(ossVersion);
Map<String, Object> map = projectService.getOssIdLicenses(identification);
return makeJsonResponseHeader(map);
}
/**
* Save 3 rd.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_3RD)
public @ResponseBody ResponseEntity<Object> save3rd(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String prjId = (String) map.get("referenceId");
String identificationSubStatusPartner = (String) map.get("identificationSubStatusPartner");
String mainGrid = (String) map.get("mainData");
String thirdPartyGrid = (String) map.get("thirdPartyData");
// 메인그리드
Type collectionType = new TypeToken<List<OssComponents>>() {}.getType();
List<OssComponents> ossComponents = new ArrayList<>();
ossComponents = (List<OssComponents>) fromJson(mainGrid, collectionType);
Type collectionType1 = new TypeToken<List<PartnerMaster>>() {}.getType();
List<PartnerMaster> thirdPartyList = new ArrayList<>();
thirdPartyList = (List<PartnerMaster>) fromJson(thirdPartyGrid, collectionType1);
Project project = new Project();
if (CoConstDef.FLAG_NO.equals(identificationSubStatusPartner)) {
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER);
project.setIdentificationSubStatusPartner(identificationSubStatusPartner);
// 상태값 변경
projectService.updateSubStatus(project);
} else {
// 서브그리드
projectService.registComponentsThird(prjId, identificationSubStatusPartner, ossComponents, thirdPartyList);
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_PARTNER)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_PARTNER), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("3rd party");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
project.setPrjId(prjId);
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage());
}
}
return makeJsonResponseHeader(true, "success", projectService.getProjectDetail(project).getIdentificationStatus());
}
/**
* Save bin.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_BIN)
public @ResponseBody ResponseEntity<Object> saveBin(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String prjId = (String) map.get("prjId");
String csvFileId = (String) map.get("binCsvFileId");
String binaryFileId = (String) map.get("binBinaryFileId");
String delFileString = (String) map.get("csvDelFileIds");
String identificationSubStatusBin = (String) map.get("identificationSubStatusBin");
String mainDataString = (String) map.get("mainData");
String binAddListDataString = (String) map.get("binAddListData");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>(); delFile =
(List<T2File>) fromJson(delFileString, collectionType);
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {
}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
Type collectionType4 = new TypeToken<List<Project>>() {
}.getType();
List<Project> binAddList = new ArrayList<Project>();
binAddList = (List<Project>) fromJson(binAddListDataString, collectionType4);
if (CoConstDef.FLAG_NO.equals(identificationSubStatusBin)) {
Project project = new Project();
project.setIdentificationSubStatusBin(identificationSubStatusBin);
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BIN);
projectService.updateSubStatus(project);
} else {
/*
* 중간저장 대응을 위해 save시에는 validation check 를 수행하지 않는다. 문제가 생길경우, 꼭
* 필요한 체크를 별도의 type으로 추가해야함 // grid validation only
* customValidation check!! // 모든 체크 파라미터를 customValidation에 코딩
* 해야한다. T2CoProjectValidator pv = new T2CoProjectValidator();
* pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE); // main
* grid pv.setAppendix("mainList", ossComponents); // sub grid
* pv.setAppendix("subList", ossComponentsLicense);
*
* // basic validator는 무시, validate를 호출하여 custom validator를
* 수행한다. T2CoValidationResult vr = pv.validate(new HashMap<>());
*
* // return validator result if (!vr.isValid()) { return
* makeJsonResponseHeader(vr.getValidMessageMap()); }
*/
try {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BIN);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
Project project = new Project();
project.setPrjId(prjId);
project.setBinCsvFileId(csvFileId);
project.setBinBinaryFileId(binaryFileId);
project.setCsvFile(delFile);
project.setIdentificationSubStatusBin(identificationSubStatusBin);
Map<String, Object> remakeComponentsMap = CommonFunction.remakeMutiLicenseComponents(ossComponents, ossComponentsLicense);
ossComponents = (List<ProjectIdentification>) remakeComponentsMap.get("mainList");
ossComponentsLicense = (List<List<ProjectIdentification>>) remakeComponentsMap.get("subList");
String changeExclude = "";
String changeAdded = "";
// result txt가 존재하는 경우에 한해
// result.txt에 있으나 OSS Report에 없는 경우 => load되는 OSS List에 해당 Binary를 추가. 팝업을 띄우고 Comment로 추가된 binary목록을 남김.
// result.txt에 있으나 OSS Report에서 exclude 처리된 경우 => Exclude체크 된 것을 유지. 2번의 Comment내용과 함께 팝업에도 뜨고 Comment로 exclude되어있음을 남김
// binary.txt 파일이 변경된 경우 최초 한번만 수행
Project beforeProjectIfno = projectService.getProjectBasicInfo(prjId);
if (!isEmpty(binaryFileId) && beforeProjectIfno != null && !binaryFileId.equals(beforeProjectIfno.getBinBinaryFileId())) {
List<String> binaryTxtList = CommonFunction.getBinaryListBinBinaryTxt(fileService.selectFileInfoById(binaryFileId));
if (binaryTxtList != null && !binaryTxtList.isEmpty()) {
// 현재 osslist의 binary 목록을 격납
Map<String, ProjectIdentification> componentBinaryList = new HashMap<>();
for (ProjectIdentification bean : ossComponents) {
if (!isEmpty(bean.getBinaryName())) {
if (componentBinaryList.containsKey(bean.getBinaryName())) {
ProjectIdentification identification = componentBinaryList.get(bean.getBinaryName());
if (bean.getExcludeYn().equals(CoConstDef.FLAG_NO)) {
componentBinaryList.put(bean.getBinaryName(), bean);
} else if (identification.getExcludeYn().equals(CoConstDef.FLAG_NO)) {
componentBinaryList.put(identification.getBinaryName(), identification);
}
} else {
componentBinaryList.put(bean.getBinaryName(), bean);
}
}
}
List<ProjectIdentification> addComponentList = Lists.newArrayList();
// 존재여부 확인
for (String binaryNameTxt : binaryTxtList) {
if (!componentBinaryList.containsKey(binaryNameTxt)) {
// add 해야할 list
ProjectIdentification bean = new ProjectIdentification();
// 화면에서 추가한 것 처럼 jqg로 시작하는 component id를 임시로 설정한다.
bean.setGridId("jqg_"+binaryFileId+"_"+addComponentList.size());
bean.setBinaryName(binaryNameTxt);
addComponentList.add(bean);
changeAdded += "<br> - " + binaryNameTxt;
} else { // exclude처리된 경우
ProjectIdentification bean = componentBinaryList.get(binaryNameTxt);
if (bean != null && CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
changeExclude += "<br>" + binaryNameTxt;
}
}
}
if (addComponentList != null && !addComponentList.isEmpty()) {
ossComponents.addAll(addComponentList);
}
}
}
projectService.registSrcOss(ossComponents, ossComponentsLicense, project, CoConstDef.CD_DTL_COMPONENT_ID_BIN);
binaryDataService.autoIdentificationWithBinryTextFile(project);
if (!isEmpty(changeExclude) || !isEmpty(changeAdded)) {
String changedByResultTxt = "";
if (!isEmpty(changeAdded)) {
changedByResultTxt += "<b>The following binaries were added to OSS List automatically because they exist in the fosslight_binary.txt.</b><br>";
changedByResultTxt += changeAdded;
}
if (!isEmpty(changeExclude)) {
if (!isEmpty(changedByResultTxt)) {
changedByResultTxt += "<br><br>";
}
changedByResultTxt += "<b>The following binaries are written to the OSS report as excluded, but they are in the fosslight_binary.txt. Make sure it is not included in the final firmware.</b><br>";
changedByResultTxt += changeExclude;
}
resMap.put("changeBySystemNotice", changedByResultTxt);
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedByResultTxt);
commentService.registComment(commentHisBean, false);
}
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(
loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// oss name이 nick name으로 등록되어 있는 경우, 자동치환된 Data를 comment his에 등록
try {
if (getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId,
CoConstDef.CD_DTL_COMPONENT_ID_BIN)) != null) {
String changedLicenseName = (String) getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED,
prjId, CoConstDef.CD_DTL_COMPONENT_ID_BIN),
true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId)) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(chagedOssVersion);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Project project = new Project();
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BIN);
projectService.existsAddList(project);
projectService.insertAddList(binAddList);
// session 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_BIN, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN, prjId));
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
resMap.put("resultData", projectService.getProjectDetail(project).getIdentificationStatus());
return makeJsonResponseHeader(resMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, null);
}
}
/**
* Save dep.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_DEP)
public @ResponseBody ResponseEntity<Object> saveDep(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String prjId = (String) map.get("prjId");
String csvFileId = (String) map.get("csvFileId");
String delFileString = (String) map.get("csvDelFileIds");
String FileSeqs = (String) map.get("csvFileSeqs");
String identificationSubStatusDep = (String) map.get("identificationSubStatusDep");
String mainDataString = (String) map.get("mainData");
String depAddListDataString = (String) map.get("depAddListData");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>();
delFile = (List<T2File>) fromJson(delFileString, collectionType);
List<T2File> addFile = new ArrayList<T2File>();
addFile = (List<T2File>) fromJson(FileSeqs, collectionType);
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
Type collectionType4 = new TypeToken<List<Project>>() {}.getType();
List<Project> depAddList = new ArrayList<Project>();
depAddList = (List<Project>) fromJson(depAddListDataString, collectionType4);
if (CoConstDef.FLAG_NO.equals(identificationSubStatusDep)) {
Project project = new Project();
project.setIdentificationSubStatusDep(identificationSubStatusDep);
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
projectService.updateSubStatus(project);
} else {
/*
* 중간저장 대응을 위해 save시에는 validation check 를 수행하지 않는다. 문제가 생길경우, 꼭 필요한
* 체크를 별도의 type으로 추가해야함 // grid validation only customValidation
* check!! // 모든 체크 파라미터를 customValidation에 코딩 해야한다.
* T2CoProjectValidator pv = new T2CoProjectValidator();
* pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE); // main grid
* pv.setAppendix("mainList", ossComponents); // sub grid
* pv.setAppendix("subList", ossComponentsLicense);
*
* // basic validator는 무시, validate를 호출하여 custom validator를 수행한다.
* T2CoValidationResult vr = pv.validate(new HashMap<>());
*
* // return validator result if(!vr.isValid()) { return
* makeJsonResponseHeader(vr.getValidMessageMap()); }
*/
// save 시 가장 기본적인 유효성 체크만 진행 (길이, 형식 체크)
T2CoProjectValidator pv = new T2CoProjectValidator();
//pv.setIgnore("LICENSE_NAME"); // 예외처리를 추가함.
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
if(CommonFunction.booleanOssNameFormatForValidMsg(vr.getValidMessageMap())) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap(), ossComponents), vr.getValidMessageMap());
}else {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
}
Project project = new Project();
project.setPrjId(prjId);
project.setDepCsvFileId(csvFileId);
project.setCsvFile(delFile);
project.setCsvFileSeq(addFile);
project.setIdentificationSubStatusDep(identificationSubStatusDep);
Map<String, Object> remakeComponentsMap = CommonFunction.remakeMutiLicenseComponents(ossComponents, ossComponentsLicense);
ossComponents = (List<ProjectIdentification>) remakeComponentsMap.get("mainList");
ossComponentsLicense = (List<List<ProjectIdentification>>) remakeComponentsMap.get("subList");
projectService.registDepOss(ossComponents, ossComponentsLicense, project);
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
if (addFile != null) {
for (T2File _file : addFile) {
if (!isEmpty(_file.getFileSeq())) {
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, _file.getFileSeq())) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(
loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE,
_file.getFileSeq()), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("DEP");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if(getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, _file.getFileSeq())) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, _file.getFileSeq()), true);
if(!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("DEP");
commentHisBean.setContents(chagedOssVersion);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Project project = new Project();
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
projectService.existsAddList(project);
projectService.insertAddList(depAddList);
// 정상처리된 경우 세션 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_DEP, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_DEP, prjId));
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
resMap.put("resultData", projectService.getProjectDetail(project).getIdentificationStatus());
return makeJsonResponseHeader(resMap);
}
/**
* Save src.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_SRC)
public @ResponseBody ResponseEntity<Object> saveSrc(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String prjId = (String) map.get("prjId");
String csvFileId = (String) map.get("csvFileId");
String delFileString = (String) map.get("csvDelFileIds");
String FileSeqs = (String) map.get("csvFileSeqs");
String identificationSubStatusSrc = (String) map.get("identificationSubStatusSrc");
String mainDataString = (String) map.get("mainData");
String srcAddListDataString = (String) map.get("srcAddListData");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>();
delFile = (List<T2File>) fromJson(delFileString, collectionType);
List<T2File> addFile = new ArrayList<T2File>();
addFile = (List<T2File>) fromJson(FileSeqs, collectionType);
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
Type collectionType4 = new TypeToken<List<Project>>() {}.getType();
List<Project> srcAddList = new ArrayList<Project>();
srcAddList = (List<Project>) fromJson(srcAddListDataString, collectionType4);
if (CoConstDef.FLAG_NO.equals(identificationSubStatusSrc)) {
Project project = new Project();
project.setIdentificationSubStatusSrc(identificationSubStatusSrc);
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_SRC);
projectService.updateSubStatus(project);
} else {
/*
* 중간저장 대응을 위해 save시에는 validation check 를 수행하지 않는다. 문제가 생길경우, 꼭 필요한
* 체크를 별도의 type으로 추가해야함 // grid validation only customValidation
* check!! // 모든 체크 파라미터를 customValidation에 코딩 해야한다.
* T2CoProjectValidator pv = new T2CoProjectValidator();
* pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE); // main grid
* pv.setAppendix("mainList", ossComponents); // sub grid
* pv.setAppendix("subList", ossComponentsLicense);
*
* // basic validator는 무시, validate를 호출하여 custom validator를 수행한다.
* T2CoValidationResult vr = pv.validate(new HashMap<>());
*
* // return validator result if (!vr.isValid()) { return
* makeJsonResponseHeader(vr.getValidMessageMap()); }
*/
// save 시 가장 기본적인 유효성 체크만 진행 (길이, 형식 체크)
T2CoProjectValidator pv = new T2CoProjectValidator();
//pv.setIgnore("LICENSE_NAME"); // 예외처리를 추가함.
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
Project project = new Project();
project.setPrjId(prjId);
project.setSrcCsvFileId(csvFileId);
project.setCsvFile(delFile);
project.setCsvFileSeq(addFile);
project.setIdentificationSubStatusSrc(identificationSubStatusSrc);
Map<String, Object> remakeComponentsMap = CommonFunction.remakeMutiLicenseComponents(ossComponents, ossComponentsLicense);
ossComponents = (List<ProjectIdentification>) remakeComponentsMap.get("mainList");
ossComponentsLicense = (List<List<ProjectIdentification>>) remakeComponentsMap.get("subList");
projectService.registSrcOss(ossComponents, ossComponentsLicense, project);
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
if (addFile != null) {
for (T2File _file : addFile) {
if (!isEmpty(_file.getFileSeq())) {
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, _file.getFileSeq())) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(
loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE,
_file.getFileSeq()), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("SRC");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, _file.getFileSeq())) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, _file.getFileSeq()), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("SRC");
commentHisBean.setContents(chagedOssVersion);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// oss name이 nick name으로 등록되어 있는 경우, 자동치환된 Data를 comment his에 등록
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_SRC)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_SRC), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("SRC");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Project project = new Project();
project.setPrjId(prjId);
project.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_SRC);
projectService.existsAddList(project);
projectService.insertAddList(srcAddList);
// 정상처리된 경우 세션 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_SRC, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC, prjId));
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
resMap.put("resultData", projectService.getProjectDetail(project).getIdentificationStatus());
return makeJsonResponseHeader(resMap);
}
/**
* Nick name valid.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @param code the code
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.NICKNAME_CD)
public @ResponseBody ResponseEntity<Object> nickNameValid(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String code) {
Map<String, List<String>> result = null;
String mainDataString = (String) map.get("mainData");
String prjId = (String) map.get("prjId");
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> ossComponent = new ArrayList<ProjectIdentification>();
ossComponent = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
List<List<ProjectIdentification>> ossComponentLicense = null;
if (code.equals(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER)) {
ossComponentLicense = CommonFunction.setOssComponentLicense(ossComponent, true);
} else {
ossComponentLicense = CommonFunction.setOssComponentLicense(ossComponent);
}
ossComponentLicense = CommonFunction.mergeGridAndSession(
CommonFunction.makeSessionKey(loginUserName(), code, prjId), ossComponent, ossComponentLicense,
CommonFunction.makeSessionReportKey(loginUserName(), code, prjId));
result = projectService.nickNameValid(ossComponent, ossComponentLicense);
StringBuffer resultSb = new StringBuffer();
if (result != null) {
boolean hasOssNick = false;
boolean hasLicenseNick = false;
List<String> ossNickList = result.get("OSS");
List<String> licenseNickList = result.get("LICENSE");
if ((ossNickList != null && !ossNickList.isEmpty()) || (licenseNickList != null && !licenseNickList.isEmpty())) {
resultSb.append(messageSource.getMessage("msg.oss.changed.by.system",null, LocaleContextHolder.getLocale()));
if (ossNickList != null) {
for (String s : ossNickList) {
if (hasOssNick) {
resultSb.append("<br>");
} else {
hasOssNick = true;
resultSb.append("<b>Open Source Name</b><br>");
}
resultSb.append(s);
}
if (hasOssNick) {
resultSb.append("<br><br>");
}
}
if (licenseNickList != null) {
for (String s : licenseNickList) {
if (hasLicenseNick) {
resultSb.append("<br>");
} else {
hasLicenseNick = true;
resultSb.append("<b>License Names</b><br>");
}
resultSb.append(s);
}
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, code), resultSb.toString());
return makeJsonResponseHeader(true, resultSb.toString());
}
}
return makeJsonResponseHeader();
}
/**
* Save bin android.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings({ "unchecked", "deprecation" })
@PostMapping(value = PROJECT.SAVE_BINANDROID)
public @ResponseBody ResponseEntity<Object> saveBinAndroid(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String prjId = (String) map.get("prjId");
String androidCsvFileId = (String) map.get("androidCsvFileId");
String androidNoticeFileId = (String) map.get("androidNoticeFileId");
String androidNoticeXmlId = (String) map.get("androidNoticeXmlId");
String androidResultFileId = (String) map.get("androidResultFileId");
String identificationSubStatusAndroid = (String) map.get("identificationSubStatusAndroid");
String loadFromAndroidProjectFlag = (String) map.get("loadFromAndroidProjectFlag");
String mainDataString = (String) map.get("mainData");
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {
}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
List<List<ProjectIdentification>> ossComponentsLicense = CommonFunction.setOssComponentLicense(ossComponents);
try {
String fileId = null;
if (!isEmpty(androidNoticeXmlId)) {
fileId = androidNoticeXmlId;
}
if (isEmpty(androidNoticeXmlId)
&& !isEmpty(androidNoticeFileId)) {
fileId = androidNoticeFileId;
}
T2File noticeFile = fileService.selectFileInfoById(fileId);
List<String> noticeBinaryList = CommonFunction.getAndroidNoticeBinaryList(
FileUtils.readFileToString(new File(noticeFile.getLogiPath() + "/" + noticeFile.getLogiNm())));
Map<String, Object> syncMap = projectService.applySrcAndroidModel(ossComponents, noticeBinaryList);
ossComponents = (List<ProjectIdentification>) syncMap.get("reportData");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Project prj = new Project();
prj.setPrjId(prjId);
if (CoConstDef.FLAG_NO.equals(identificationSubStatusAndroid)) {
prj.setIdentificationSubStatusAndroid(identificationSubStatusAndroid);
prj.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
projectService.updateSubStatus(prj);
} else {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
Project project = new Project();
project.setPrjId(prjId);
project.setSrcAndroidCsvFileId(androidCsvFileId);
project.setSrcAndroidNoticeFileId(androidNoticeFileId);
project.setSrcAndroidNoticeXmlId(androidNoticeXmlId);
project.setSrcAndroidResultFileId(androidResultFileId);
project.setIdentificationSubStatusAndroid(identificationSubStatusAndroid);
if (CoConstDef.FLAG_YES.equals(loadFromAndroidProjectFlag)) {
project.setLoadFromAndroidProjectFlag(loadFromAndroidProjectFlag);
}
projectService.registSrcOss(ossComponents, ossComponentsLicense, project,
CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
binaryDataService.autoIdentificationWithAndroidResultTextFile(project);
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, androidResultFileId)) != null) {
String changedByResultTxt = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, androidResultFileId), true);
if (!isEmpty(changedByResultTxt)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedByResultTxt);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, androidCsvFileId)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, androidCsvFileId), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// oss name이 nick name으로 등록되어 있는 경우, 자동치환된 Data를 comment his에 등록
try {
if (getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId,
CoConstDef.CD_DTL_COMPONENT_ID_ANDROID)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedLicenseName);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, androidCsvFileId)) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, androidCsvFileId), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(chagedOssVersion);
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
// session 정보 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_ANDROID, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID, prjId));
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
resMap.put("resultData", projectService.getProjectDetail(prj).getIdentificationStatus());
return makeJsonResponseHeader(resMap);
}
/**
* Save bom.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_BOM)
public @ResponseBody ResponseEntity<Object> saveBom(@RequestBody Map<String, Object> map, HttpServletRequest req,
HttpServletResponse res, Model model) {
String prjId = (String) map.get("referenceId");
String merge = (String) map.get("merge");
String gridString = (String) map.get("gridData");
String checkGridString = (String) map.get("checkGridData");
// bom에서 admin check선택한 data
Type collectionType = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> projectIdentification = new ArrayList<>();
projectIdentification = (List<ProjectIdentification>) fromJson(gridString, collectionType);
List<ProjectIdentification> checkGridBomList = new ArrayList<>();
checkGridBomList = (List<ProjectIdentification>) fromJson(checkGridString, collectionType);
projectService.registBom(prjId, merge, projectIdentification, checkGridBomList);
Map<String, String> resMap = new HashMap<>();
try {
Project param = new Project();
param.setPrjId(prjId);
Project pDat = projectService.getProjectDetail(param);
resMap.put("identificationStatus", pDat.getIdentificationStatus());
History h = projectService.work(pDat);
h.sethAction(CoConstDef.ACTION_CODE_NEEDED);
historyService.storeData(h); // 메일로 보낼 데이터를 History에 저장합니다. -> h.gethData()로 확인 가능
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(resMap);
}
/**
* [API] 프로젝트 상태 변경.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings({ "unchecked", "unused" })
@PostMapping(value = PROJECT.UPDATE_PROJECT_STATUS)
public @ResponseBody ResponseEntity<Object> updateProjectStatus(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
log.info("URI: "+ "/project/updateProjectStatus");
log.debug("PARAM: " + "useCustomNoticeYn="+project.getUseCustomNoticeYn());
/* 2018-07-27 choye 추가 */
String resCd = "";
String resMsg = "";
if (project.getPrjId() == null || "".equals(project.getPrjId())) {
return makeJsonResponseHeader(false, "prjId is empty", null);
}
if (project.getDelOsdd()!=null && (project.getDelOsdd().equals(CoConstDef.FLAG_YES) || project.getDelOsdd().equals(CoConstDef.FLAG_NO))) {
project.setCompleteYn(CoConstDef.FLAG_NO);
project.setStatusRequestYn(CoConstDef.FLAG_NO);
project.setCommId(null);
project.setUserComment(project.getUserComment());
project.setIgnoreUserCommentReg(CoConstDef.FLAG_YES);
resMsg = getMessage("msg.distribute.reset");
if ("10".equals(resCd)){
}
else if ("20".equals(resCd)){
resMsg="server error.";
} else{
resMsg = resCd;
}
if (!resCd.equals("10")) {
return makeJsonResponseHeader(false, resMsg, null);
}
}
Map<String, Object> resultMap = new HashMap<>();
try {
resultMap = projectService.updateProjectStatus(project);
if (resultMap.containsKey("androidMessage")) {
return makeJsonResponseHeader(false, getMessage("msg.project.android.valid"));
}
if (resultMap.containsKey("diffMap")) {
return makeJsonResponseHeader(false, null, (Map<String, Object>) resultMap.get("validMap"), (Map<String, Object>) resultMap.get("diffMap"));
}
if (resultMap.containsKey("validMap")) {
return makeJsonResponseHeader(false, null, (Map<String, Object>) resultMap.get("validMap"));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
updateProjectNotification(project, resultMap);
return makeJsonResponseHeader();
}
/**
* [화면] Identification 화면.
*
* @param req the req
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@GetMapping(value = PROJECT.IDENTIFICATION_ID_DIV, produces = "text/html; charset=utf-8")
public String identification(HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId,
@PathVariable String initDiv) throws Exception {
Project project = new Project();
project.setPrjId(prjId);
Project projectMaster = projectService.getProjectDetail(project);
boolean partnerFlag = CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES);
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICATION_USER);
comHisBean.setReferenceId(projectMaster.getPrjId());
projectMaster.setUserComment(commentService.getUserComment(comHisBean));
projectMaster.setNoticeTypeEtc(CommonFunction.tabTitleSubStr(CoConstDef.CD_PLATFORM_GENERATED, projectMaster.getNoticeTypeEtc()));
// 프로젝트 정보
model.addAttribute("project", projectMaster);
// android model이면서 bom화면을 표시하려고하는 경우, android bin tab index로 치환한다.
if (!"4".equals(initDiv) && CoConstDef.FLAG_YES.equals(projectMaster.getAndroidFlag())) {
initDiv = "4";
}
if (!partnerFlag && "0".equals(initDiv)) {
initDiv = "2";
}
model.addAttribute("initDiv", initDiv);
model.addAttribute("autoAnalysisFlag", CommonFunction.propertyFlagCheck("autoanalysis.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", partnerFlag);
return PROJECT.IDENTIFICATION_JSP;
}
/**
* Src main grid ajax post.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.IDENTIFICATION_GRID_POST)
public @ResponseBody ResponseEntity<Object> srcMainGridAjaxPost(@RequestBody ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> result = getOssComponentDataInfo(identification, identification.getReferenceDiv());
if (result != null) CommonFunction.setDeduplicatedMessageInfo(result);
return makeJsonResponseHeader(result);
}
/**
* [API] Identification 공통 메인 조회.
* Identification 각 Tab에 저장되어있는 SRC / BIN / BIN(Android) / BOM 정보를 반환한다.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @param prjId the prj id
* @param code the code
* @return the response entity
*/
@PostMapping(value = PROJECT.IDENTIFICATION_MERGED_GRID_ID_CD)
public @ResponseBody ResponseEntity<Object> srcMainGridMergedAjax(@RequestBody ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId,
@PathVariable String code) {
// session key 초기화
// referenceId에 해당하는 모든 report (분석결과서) 세션 정보를 초기화 한다.
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PARTNER,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BAT,
identification.getReferenceId()));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_BAT,
identification.getReferenceId()));
// 요청한 reference의 이전 정보도 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), identification.getReferenceDiv(),
identification.getReferenceId()));
Map<String, Object> result = getOssComponentDataInfo(identification, code);
if (result != null) {
CommonFunction.setDeduplicatedMessageInfo(result);
// Project Identification에서 BAT Apply 인 경우 (BAT List 와
// Identification의 BAT 를 구분
if (CoConstDef.CD_DTL_COMPONENT_BAT.equals(code) && isEmpty(identification.getReferenceId())
&& !isEmpty(identification.getRefBatId())) {
code = CoConstDef.CD_DTL_COMPONENT_ID_BAT;
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), code, prjId), result);
}
return makeJsonResponseHeader(result);
}
/**
* identification project.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @param code the code
* @return the response entity
*/
@GetMapping(value = PROJECT.IDENTIFICATION_CD)
public @ResponseBody ResponseEntity<Object> identificationProject(Project project, HttpServletRequest req,
HttpServletResponse res, Model model, @PathVariable String code) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
project.setCode(code);
Map<String, Object> map = projectService.getIdentificationProject(project);
return makeJsonResponseHeader(map);
}
/**
* List ajax.
*
* @param ossComponents the oss components
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@RequestMapping(value = PROJECT.TRD_OSS)
public @ResponseBody ResponseEntity<Object> listAjax(OssComponents ossComponents, HttpServletRequest req,
HttpServletResponse res, Model model) {
ossComponents.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
Map<String, Object> map = projectService.getPartnerOssList(ossComponents);
return makeJsonResponseHeader(map);
}
/**
* Third project.
*
* @param projectIdentification the project identification
* @param req the req
* @param res the res
* @param model the model
* @param code the code
* @return the response entity
*/
@GetMapping(value = PROJECT.IDENTIFICATION_PROJECT_SEARCH_CD)
public @ResponseBody ResponseEntity<Object> thirdProject(ProjectIdentification projectIdentification,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String code) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
projectIdentification.setCurPage(page);
projectIdentification.setPageListSize(rows);
projectIdentification.setSortField(sidx);
projectIdentification.setSortOrder(sord);
projectIdentification.setReferenceDiv(code);
Map<String, Object> map = projectService.getIdentificationProjectSearch(projectIdentification);
return makeJsonResponseHeader(map);
}
/**
* Project Identification > 3rd oss list 취득.
*
* @param ossComponents the oss components
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@GetMapping(value = PROJECT.IDENTIFICATION_THIRD)
public @ResponseBody ResponseEntity<Object> identificationThird(OssComponents ossComponents, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = projectService.getIdentificationThird(ossComponents);
return makeJsonResponseHeader(map);
}
/**
* Android sheet name.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.ANDROID_SHEET_NAME)
public @ResponseBody ResponseEntity<Object> androidSheetName(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
List<UploadFile> list = new ArrayList<UploadFile>();
list = projectService.selectAndroidFileDetail(project);
List<Object> sheetNameList = null;
try {
sheetNameList = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(sheetNameList);
}
/**
* Gets the oss id check.
*
* @param projectIdentification the project identification
* @param model the model
* @return the oss id check
*/
@GetMapping(value = PROJECT.OSS_ID_CHECK)
public @ResponseBody ResponseEntity<Object> getOssIdCheck(
@ModelAttribute ProjectIdentification projectIdentification, Model model) {
Map<String, Object> map = projectService.getOssIdCheck(projectIdentification);
return makeJsonResponseHeader(map);
}
/**
* Gets the check change data.
*
* @param map the map
* @return the check change data
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.CHECK_CHANGE_DATA)
public @ResponseBody ResponseEntity<Object> getCheckChangeData(@RequestBody HashMap<String, Object> map) {
String prjId = (String) map.get("referenceId");
String partyGrid = (String) map.get("partyGrid");
String srcMainGrid = (String) map.get("srcMainGrid");
String binMainGrid = (String) map.get("binMainGrid");
String status = (String) map.get("status");
// party
Type partyType = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> partyData = new ArrayList<ProjectIdentification>();
partyData = (List<ProjectIdentification>) fromJson(partyGrid, partyType);
// src
Type srcType = new TypeToken<List<ProjectIdentification>>() {}.getType();
List<ProjectIdentification> srcData = new ArrayList<ProjectIdentification>();
srcData = (List<ProjectIdentification>) fromJson(srcMainGrid, srcType);
List<List<ProjectIdentification>> srcSubData = CommonFunction.setOssComponentLicense(srcData);
srcSubData = CommonFunction.mergeGridAndSession(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_SRC, prjId), srcData,
srcSubData,
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC, prjId));
// bin
Type binType = new TypeToken<List<ProjectIdentification>>() {
}.getType();
List<ProjectIdentification> binData = new ArrayList<ProjectIdentification>();
binData = (List<ProjectIdentification>) fromJson(binMainGrid, binType);
List<List<ProjectIdentification>> binSubData = CommonFunction.setOssComponentLicense(binData);
binSubData = CommonFunction.mergeGridAndSession(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_BIN, prjId), binData,
binSubData,
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN, prjId));
// 체크 서비스 호출
String errMsg = projectService.checkChangedIdentification(prjId, partyData, srcData, srcSubData, binData,
binSubData, (String) map.get("applicableParty"), (String) map.get("applicableSrc"),
(String) map.get("applicableBin"));
if (!isEmpty(errMsg)) {
return makeJsonResponseHeader(false, errMsg);
}
if (!isEmpty(status) && CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(status.toUpperCase())){
ProjectIdentification identification = new ProjectIdentification();
identification.setReferenceId(prjId);
identification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BOM);
identification.setMerge(CoConstDef.FLAG_YES);
errMsg = projectService.checkOssNicknameList(identification);
if (!isEmpty(errMsg)) {
return makeJsonResponseHeader(false, errMsg);
}
}
return makeJsonResponseHeader();
}
/**
* Calcel file del src.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.CANCEL_FILE_DEL_SRC)
public @ResponseBody ResponseEntity<Object> cancelFileDelSrc(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String delFileString = (String) map.get("csvDelFileIds");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>();
delFile = (List<T2File>) fromJson(delFileString, collectionType);
if (delFile.size() > 0) {
try {
Project project = new Project();
project.setCsvFile(delFile);
projectService.cancelFileDel(project);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
}
return makeJsonResponseHeader(resMap);
}
/**
* Gets the file info.
*
* @param identification the identification
* @param req the req
* @param res the res
* @param model the model
* @return the file info
*/
@GetMapping(value = PROJECT.FILE_INFO)
public @ResponseBody ResponseEntity<Object> getFileInfo(@ModelAttribute ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> result = projectService.getFileInfo(identification);
return makeJsonResponseHeader(result);
}
/**
* Gets the 3 rd map.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the 3 rd map
*/
@GetMapping(value = PROJECT.TRD_MAP)
public @ResponseBody ResponseEntity<Object> get3rdMap(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = null;
try {
map = projectService.get3rdMapList(project);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
/**
* Adds the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.ADD_WATCHER)
public @ResponseBody ResponseEntity<Object> addWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
// addWatcher로 email을 등록할 경우 ldap search로 존재하는 사용자의 email인지 check가 필요함.
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
if (CoConstDef.FLAG_YES.equals(ldapFlag) && !isEmpty(project.getPrjEmail())) {
Map<String, String> userInfo = new HashMap<>();
userInfo.put("USER_ID", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_ID));
userInfo.put("USER_PW", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_PW));
String filter = project.getPrjEmail();
boolean isAuthenticated = userService.checkAdAccounts(userInfo, "USER_ID", "USER_PW", filter);
if (!isAuthenticated) {
throw new Exception("add Watcher Failure");
}
String email = (String) userInfo.get("EMAIL");
project.setPrjEmail(email);
// 사용자가 입력한 domain과 ldap search를 통해 확인된 domain이 다를 수 있기때문에 ldap search에서 확인된 domain을 우선적으로 처리함.
resultMap.put("email", email);
}
if (!isEmpty(project.getPrjUserId()) || !isEmpty(project.getPrjEmail())) {
String addWatcher = projectService.addWatcher(project);
resultMap.put("isValid", "true");
resultMap.put("addWatcher", addWatcher);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resultMap);
}
/**
* Adds the watchers.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.ADD_WATCHERS)
public @ResponseBody ResponseEntity<Object> addWatchers(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
Project param = new Project();
for (Map<String, String> changeWatcher : project.getChangeWatcherList()) {
String prjEmail = changeWatcher.get("prjEmail");
if (CoConstDef.FLAG_YES.equals(ldapFlag) && !isEmpty(prjEmail)) {
Map<String, String> userInfo = new HashMap<>();
userInfo.put("USER_ID", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_ID));
userInfo.put("USER_PW", CoCodeManager.getCodeExpString(CoConstDef.CD_LDAP_SEARCH_INFO, CoConstDef.CD_DTL_LDAP_SEARCH_PW));
boolean isAuthenticated = userService.checkAdAccounts(userInfo, "USER_ID", "USER_PW", prjEmail);
if (!isAuthenticated) {
throw new Exception("add Watcher Failure");
}
}
param.setPrjUserId(changeWatcher.get("prjUserId"));
param.setPrjDivision(changeWatcher.get("prjDivision"));
param.setPrjEmail(prjEmail);
for (String prjId : project.getPrjIds()) {
if (!isEmpty(param.getPrjUserId()) || !isEmpty(param.getPrjEmail())) {
param.setPrjId(prjId);
projectService.addWatcher(param);
}
}
}
resultMap.put("isValid", "true");
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resultMap);
}
/**
* Removes the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.REMOVE_WATCHER)
public @ResponseBody ResponseEntity<Object> removeWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
if (!isEmpty(project.getPrjUserId()) || !isEmpty(project.getPrjEmail())) {
projectService.removeWatcher(project);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* Removes the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.REMOVE_WATCHERS)
public @ResponseBody ResponseEntity<Object> removeWatchers(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
Project param = new Project();
for (Map<String, String> changeWatcher : project.getChangeWatcherList()) {
String prjUserId = changeWatcher.get("prjUserId");
String prjEmail = changeWatcher.get("prjEmail");
if (!isEmpty(prjUserId) || !isEmpty(prjEmail)) {
param.setPrjUserId(prjUserId);
param.setPrjDivision(changeWatcher.get("prjDivision"));
param.setPrjEmail(prjEmail);
for (String prjId : project.getPrjIds()) {
param.setPrjId(prjId);
projectService.removeWatcher(param);
}
}
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* Copys the watcher.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.COPY_WATCHER)
public @ResponseBody ResponseEntity<Object> copyWatcher(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
HashMap<String, Object> resMap = new HashMap<>();
try {
if (!isEmpty(project.getListKind()) && !isEmpty(project.getListId()) ) {
List<Project> result = projectService.copyWatcher(project);
if (result != null) {
for (Project bean : result) {
if (!isEmpty(bean.getPrjDivision())) {
bean.setPrjDivisionName(CoCodeManager.getCodeString(CoConstDef.CD_USER_DIVISION, bean.getPrjDivision()));
}
}
if (isEmpty(project.getCopyWatcherLocation()) && !isEmpty(project.getPrjId())) {
boolean existProjectWatcher = projectService.existsWatcher(project);
for (Project pm : result) {
pm.setPrjId(project.getPrjId());
if (existProjectWatcher) {
projectService.addWatcher(pm);
}
}
}
}
resMap.put("copyWatcher", result);
} else {
return makeJsonResponseHeader(false, null);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader(resMap);
}
/**
* saveModelAjax
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_MODEL_AJAX)
public @ResponseBody ResponseEntity<Object> saveModelAjax(@ModelAttribute Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
String jsonString = project.getPrjModelJson();
Type collectionType = new TypeToken<List<Project>>() {}.getType();
List<Project> list = (List<Project>) fromJson(jsonString, collectionType);
project.setModelList(list);
projectService.insertProjectModel(project);
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
/**
* updatePublicYn
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.UPDATE_PUBLIC_YN)
public @ResponseBody ResponseEntity<Object> updatePublicYn(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
try {
projectService.updatePublicYn(project);
} catch (Exception e) {
return makeJsonResponseHeader(false, null);
}
return makeJsonResponseHeader();
}
@GetMapping(value = PROJECT.PROJECT_TO_ADD_LIST)
public @ResponseBody ResponseEntity<Object> projectToAddList(@ModelAttribute OssComponents ossComponents, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = projectService.getProjectToAddList(ossComponents);
return makeJsonResponseHeader(map);
}
/**
* Gets the 3 rd map.
*
* @param project the project
* @param req the req
* @param res the res
* @param model the model
* @return the 3 rd map
*/
@GetMapping(value = PROJECT.ADD_LIST)
public @ResponseBody ResponseEntity<Object> getSrcAddList(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = null;
try {
map = projectService.getAddList(project);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
/**
* Gets the partner list.
*
* @param partnerMaster the partner master
* @param req the req
* @param res the res
* @param model the model
* @return the partner list
*/
@GetMapping(value = PROJECT.PARTNER_LIST)
public @ResponseBody ResponseEntity<Object> getPartnerList(PartnerMaster partnerMaster, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = null;
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
partnerMaster.setCurPage(page);
partnerMaster.setPageListSize(rows);
partnerMaster.setSortField(sidx);
partnerMaster.setSortOrder(sord);
try {
map = projectService.getPartnerList(partnerMaster);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
/**
* Csv file.
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@ResponseBody
@PostMapping(value = PROJECT.CSV_FILE)
public String csvFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
ArrayList<Object> resultList = new ArrayList<Object>();
// 파일등록
List<UploadFile> list = new ArrayList<UploadFile>();
String fileId = req.getParameter("registFileId");
file.setTabGubn(req.getParameter("tabNm"));
log.info("tabNm ==> " + req.getParameter("tabNm"));
Map<String, MultipartFile> fileMap = req.getFileMap();
String fileExtension = StringUtils.getFilenameExtension(fileMap.get("myfile").getOriginalFilename());
// 파일 등록
try {
if (req.getContentType() != null
&& req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
if (fileId == null) {
list = fileService.uploadFile(req, file);
} else {
list = fileService.uploadFile(req, file, null, fileId);
}
}
if (fileExtension.equals("csv")) {
resultList = CommonFunction.checkCsvFileLimit(list);
} else {
resultList = CommonFunction.checkXlsxFileLimit(list);
}
if (resultList.size() > 0) {
return toJson(resultList);
}
} catch (Exception e) {
log.error(e.getMessage());
}
if (fileExtension.equals("csv")) {
resultList.add(list);
resultList.add("SRC");
resultList.add("CSV_FILE");
return toJson(resultList);
} else {
// sheet이름
List<Object> sheetNameList = null;
try {
sheetNameList = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} catch (Exception e) {
log.error(e.getMessage());
}
Boolean isSpdxSpreadsheet = false;
for (Object sheet : sheetNameList) {
String sheetName = sheet.toString();
if (sheetName.contains("Package Info") || sheetName.contains("Per File Info")) {
isSpdxSpreadsheet = true;
}
}
if (isSpdxSpreadsheet){
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("SPDX_SPREADSHEET_FILE");
}
else {
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("EXCEL_FILE");
}
// 결과값 resultList에 담기
return toJson(resultList);
}
}
/**
* Bin csv file.
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@ResponseBody
@PostMapping(value = PROJECT.BIN_CSV_FILE)
public String binCsvFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
String fileType = req.getParameter("fileType");
ArrayList<Object> resultList = new ArrayList<Object>();
// 파일등록
List<UploadFile> list = new ArrayList<UploadFile>();
String fileId = req.getParameter("registFileId");
Map<String, MultipartFile> fileMap = req.getFileMap();
String fileExtension = StringUtils.getFilenameExtension(fileMap.get("myfile").getOriginalFilename());
// 파일 등록
try {
if (req.getContentType() != null && req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
if (fileId == null) {
list = fileService.uploadFile(req, file);
} else {
list = fileService.uploadFile(req, file, null, fileId);
}
}
if (fileExtension.equals("csv")) {
resultList = CommonFunction.checkCsvFileLimit(list);
} else {
resultList = CommonFunction.checkXlsxFileLimit(list);
}
if (resultList.size() > 0) {
return toJson(resultList);
}
} catch (Exception e) {
log.error(e.getMessage());
}
if ("text".equals(fileType)) {
resultList.add(list);
resultList.add(fileType);
resultList.add("TEXT_FILE");
return toJson(resultList);
} else if (fileExtension.equals("csv")) {
resultList.add(list);
resultList.add("BIN");
resultList.add("CSV_FILE");
return toJson(resultList);
} else {
// sheet이름
List<Object> sheetNameList = null;
try {
sheetNameList = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} catch (Exception e) {
log.error(e.getMessage());
}
Boolean isSpdxSpreadsheet = false;
for (Object sheet : sheetNameList) {
String sheetName = sheet.toString();
if (sheetName.contains("Package Info") || sheetName.contains("Per File Info")) {
isSpdxSpreadsheet = true;
}
}
if (isSpdxSpreadsheet){
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("SPDX_SPREADSHEET_FILE");
}
else {
resultList.add(list);
resultList.add(sheetNameList);
resultList.add("EXCEL_FILE");
}
return toJson(resultList);
}
}
/**
* Gets the sheet data.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the sheet data
*/
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SHEET_DATA)
public @ResponseBody ResponseEntity<Object> getSheetData(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
log.info("Report Read Start");
try {
String prjId = (String) map.get("prjId");
String fileSeq = (String) map.get("fileSeq");
List<String> sheetNums = (List<String>) map.get("sheetNums");
String mainDataString = (String) map.get("mainData");
String subDataString = (String) map.get("subData");
String readType = (String) map.get("readType");
List<String> sheetList = new ArrayList<>();
for (String s : sheetNums) {
if (!sheetList.contains(s)) {
sheetList.add(s);
}
}
// 편집중인 Data 격납
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {
}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
Type collectionType3 = new TypeToken<List<List<ProjectIdentification>>>() {
}.getType();
List<List<ProjectIdentification>> ossComponentsLicense = new ArrayList<>();
ossComponentsLicense = (List<List<ProjectIdentification>>) fromJson(subDataString, collectionType3);
String errMsg = "";
List<OssComponents> reportData = new ArrayList<OssComponents>();
List<String> errMsgList = new ArrayList<>();
try {
if (!ExcelUtil.readReport(readType, true, sheetList.toArray(new String[sheetList.size()]), fileSeq,
reportData, errMsgList)) {
// error 처리
for (String s : errMsgList) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(errMsg)) {
errMsg += "<br/>";
}
errMsg += s;
}
return makeJsonResponseHeader(isEmpty(errMsg), errMsg);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
for (String s : errMsgList) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(errMsg)) {
errMsg += "<br/>";
}
errMsg += s;
}
Map<String, Object> resultMap = CommonFunction.makeGridDataFromReport(ossComponents, ossComponentsLicense, null, reportData, fileSeq, readType);
String sessionKey = CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC;
if ("bin".equals(readType)) {
sessionKey = CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN;
} else if ("android".equals(readType)) {
sessionKey = CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID;
} else if ("partner".equals(readType)) {
sessionKey = CoConstDef.SESSION_KEY_UPLOAD_REPORT_PARTNER;
} else if ("self".equals(readType)) {
sessionKey = CoConstDef.SESSION_KEY_UPLOAD_REPORT_SELFT_PROJECT;
}
// license name이 변경된 내용이 있을 경우 사용자 표시
String systemChangeHisStr = "";
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, fileSeq)) != null) {
systemChangeHisStr = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, fileSeq));
}
if (resultMap.containsKey("versionChangedList")) {
List<String> versionChangedList = (List<String>) resultMap.get("versionChangedList");
if (!versionChangedList.isEmpty()) {
String versionChangedStr = "<b>The following open source version below has been changed to a registered version</b><br><br>";
for (String s : versionChangedList) {
versionChangedStr += "<br>" + s;
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, fileSeq), versionChangedStr);
if (!isEmpty(systemChangeHisStr)) {
systemChangeHisStr += "<br><br>" + versionChangedStr;
}
}
}
resultMap.put("systemChangeHisStr", systemChangeHisStr);
if (!putSessionObject(CommonFunction.makeSessionKey(loginUserName(), sessionKey, prjId), resultMap)) {
return makeJsonResponseHeader(false, null);
}
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setAppendix("mainList", (List<ProjectIdentification>) resultMap.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) resultMap.get("subData"));
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
resultMap.replace("mainData", CommonFunction.identificationSortByValidInfo(
(List<ProjectIdentification>) resultMap.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false));
return makeJsonResponseHeader(true, errMsg, resultMap, vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap());
}
return makeJsonResponseHeader(true, errMsg, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
}
/**
* Send comment.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value =PROJECT.SEND_COMMENT)
public @ResponseBody ResponseEntity<Object> sendComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
switch (avoidNull(commentsHistory.getReferenceDiv())) {
case CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS:
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_ADDED_COMMENT);
break;
case CoConstDef.CD_DTL_COMMENT_DISTRIBUTION_HIS:
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PROJECT_DISTRIBUTE_ADDED_COMMENT);
break;
case CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS:
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PROJECT_IDENTIFICATION_ADDED_COMMENT);
break;
case CoConstDef.CD_DTL_COMMENT_PROJECT_HIS:
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PROJECT_ADDED_COMMENT);
break;
default:
break;
}
commentService.registComment(commentsHistory);
return makeJsonResponseHeader();
}
/**
* Copy.
*
* @param prjId the prj id
* @param req the req
* @param res the res
* @param model the model
* @return the string
*/
@RequestMapping(value = PROJECT.COPY_ID, method = { RequestMethod.GET,
RequestMethod.POST }, produces = "text/html; charset=utf-8")
public String copy(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(prjId);
project = projectService.getProjectDetail(project);
String comment = "";
String identificationStatus = project.getIdentificationStatus();
String verificationStatus = project.getVerificationStatus();
project.setPrjName(project.getPrjName());
project.setPrjVersion(avoidNull(project.getPrjVersion()) + "_Copied");
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(identificationStatus)) {
T2Users user = new T2Users();
user.setUserId(loginUserName());
project.setIdentificationStatusConfFlag(CoConstDef.FLAG_YES);
project.setPriority(CoConstDef.CD_PRIORITY_P2);
project.setReviewerName("");
project.setPrjUserName(userService.getUser(user).getUserName());
comment = "Copy with confirm status from [PRJ-" + prjId + "] " + project.getPrjName();
if (CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(verificationStatus)) {
project.setVerificationStatusConfFlag(CoConstDef.FLAG_YES);
}
}else {
comment = "Copied from [PRJ-" + prjId + "] " + project.getPrjName();
if (!isEmpty(project.getPrjVersion())) {
comment += "_" + project.getPrjVersion();
}
}
project.setComment(comment);
project.setDistributeDeployTime(null);
project.setDistributeDeployYn(null);
project.setDistributeDeployModelYn(null);
project.setVerificationStatus(null);
project.setDestributionStatus(null);
project.setCopyFlag(CoConstDef.FLAG_YES);
project.setCompleteYn(CoConstDef.FLAG_NO);
T2Users user = userService.getLoginUserInfo();
if (user != null && user.getDivision() != null) {
project.setDivision(user.getDivision());
}
model.addAttribute("project", project);
model.addAttribute("copy", toJson(project));
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
return PROJECT.EDIT_JSP;
}
/**
* Android file.
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@ResponseBody
@PostMapping(value = PROJECT.ANDROID_FILE)
public String androidFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
String fileType = req.getParameter("fileType");
ArrayList<Object> resultList = new ArrayList<Object>();
// 파일등록거
List<UploadFile> list = new ArrayList<UploadFile>();
String fileId = req.getParameter("registFileId");
String prjId = req.getParameter("prjId");
Project prj = new Project();
prj.setPrjId(prjId);
// 파일 이름
int count = 0;
Iterator<String> fileNames = req.getFileNames();
String extType = "";
while (fileNames.hasNext()) {
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String[] ext = StringUtil.split(fileName, ".");
extType = ext[ext.length - 1];
String type = "";
if ("csv".equals(fileType)) {
type = "13";
} else if ("notice".equals(fileType)) {
type = "14";
} else {
type = "19";
}
String codeExt[] = StringUtil.split(codeMapper.selectExtType(type), ",");
for (int i = 0; i < codeExt.length; i++) {
if (codeExt[i].equals(extType)) {
count++;
}
}
}
if (count != 1) {
String codeExt[] = StringUtil.split(codeMapper.selectExtType(CoConstDef.CD_ANDROID_NOTICE_XML), ",");
for (int i = 0; i < codeExt.length; i++) {
if (codeExt[i].equals(extType)) {
count++;
}
}
if (count != 1) {
resultList = null;
} else {
// 파일 등록
if (req.getContentType() != null
&& req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
list = fileService.uploadNoticeXMLFile(req, file, fileId, prjId);
}
prj.setSrcAndroidNoticeFileId(list.get(0).getRegistFileId());
prj.setSrcAndroidNoticeXmlId(list.get(1).getRegistFileId());
resultList.add(list);
resultList.add(fileType);
}
} else {
// 파일 등록
if (req.getContentType() != null
&& req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
file.setCreator(loginUserName());
if (fileId == null) {
list = fileService.uploadFile(req, file);
} else {
list = fileService.uploadFile(req, file, null, fileId);
}
resultList = CommonFunction.checkXlsxFileLimit(list);
if (resultList.size() > 0) {
return toJson(resultList);
}
if ("csv".equals(fileType)) {
prj.setSrcAndroidCsvFileId(list.get(0).getRegistFileId());
} else if ("notice".equals(fileType)) {
prj.setSrcAndroidNoticeFileId(list.get(0).getRegistFileId());
} else {
prj.setSrcAndroidResultFileId(list.get(0).getRegistFileId());
}
}
resultList.add(list);
resultList.add(fileType);
}
projectService.updateFileId(prj);
// 결과값 resultList에 담기
return toJson(resultList);
}
/**
* Android apply.
*
* @param map the map
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@SuppressWarnings({ "unchecked", "deprecation" })
@PostMapping(value = PROJECT.ANDROID_APPLY)
public @ResponseBody ResponseEntity<Object> androidApply(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String prjId = (String) map.get("prjId");
String fileSeq = (String) map.get("androidFileSeq");
String noticeFileSeq = (String) map.get("androidNoticeFileSeq");
String resultFileSeq = (String) map.get("androidResultFileSeq");
List<String> sheetNums = (List<String>) map.get("sheetNums");
String mainDataString = (String) map.get("mainData");
String subDataString = (String) map.get("subData");
try {
List<String> sheetList = new ArrayList<>();
for (String s : sheetNums) {
if (!sheetList.contains(s)) {
sheetList.add(s);
}
}
// 편집중인 Data 격납
Type collectionType2 = new TypeToken<List<ProjectIdentification>>() {
}.getType();
List<ProjectIdentification> ossComponents = new ArrayList<ProjectIdentification>();
ossComponents = (List<ProjectIdentification>) fromJson(mainDataString, collectionType2);
Type collectionType3 = new TypeToken<List<List<ProjectIdentification>>>() {
}.getType();
List<List<ProjectIdentification>> ossComponentsLicense = new ArrayList<>();
ossComponentsLicense = (List<List<ProjectIdentification>>) fromJson(subDataString, collectionType3);
String errMsg = "";
List<OssComponents> reportData = new ArrayList<OssComponents>();
List<String> errMsgList = new ArrayList<>();
Map<String, Object> checkHeaderSheetName = new HashMap<String, Object>();
try {
// 1) build image를 기준으로 oss data mapping (공통)
if (!ExcelUtil.readAndroidBuildImage("", true, sheetList.toArray(new String[sheetList.size()]), fileSeq,
resultFileSeq, reportData, errMsgList, checkHeaderSheetName)) {
// error 처리
for (String s : errMsgList) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(errMsg)) {
errMsg += "<br/>";
}
errMsg += s;
}
return makeJsonResponseHeader(false, errMsg);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
for (String s : errMsgList) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(errMsg)) {
errMsg += "<br/>";
}
errMsg += s;
}
// result.text에 의해 변경된 내용이 있을 경우 사용자 표시
// validator에서 session에 격납한다.
String resultTextChangeHisStr = "";
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileSeq)) != null) {
resultTextChangeHisStr = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileSeq));
}
// license name이 변경된 내용이 있을 경우 사용자 표시
String licenseNameChangeHisStr = "";
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, fileSeq)) != null) {
licenseNameChangeHisStr = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, fileSeq));
}
// notice html과 비교 분석
Map<String, Object> noticeCheckResultMap = null;
List<String> noticeBinaryList = null;
List<String> versionChangedList = null;
try {
T2File noticeFile = fileService.selectFileInfoById(noticeFileSeq);
String noticeFileName = noticeFile.getLogiNm();
String fullName = noticeFile.getLogiPath() + "/" + noticeFileName;
if ("xml".equalsIgnoreCase(FilenameUtils.getExtension(noticeFileName))) {
noticeBinaryList = CommonFunction.getAndroidNoticeBinaryXmlList(fullName);
} else {
noticeBinaryList = CommonFunction.getAndroidNoticeBinaryList(FileUtils.readFileToString(
new File(fullName)));
}
Map<String, Object> convertObj = CommonFunction.convertToProjectIdentificationList(reportData, fileSeq);
noticeCheckResultMap = projectService.applySrcAndroidModel((List<ProjectIdentification>)convertObj.get("resultList"), noticeBinaryList);
if (convertObj.containsKey("versionChangeList")) {
versionChangedList = (List<String>) convertObj.get("versionChangeList");
}
} catch (IOException e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, "Failed to Notice file parsing");
}
// validation
Map<String, Object> resultMap = CommonFunction.mergeGridAndReport(ossComponents, ossComponentsLicense,
(List<ProjectIdentification>) noticeCheckResultMap.get("reportData"), "BINADROID");
String systemChangeHisStr = "";
if (!isEmpty(resultTextChangeHisStr)) {
systemChangeHisStr = resultTextChangeHisStr;
}
if (!isEmpty(licenseNameChangeHisStr)) {
if (!isEmpty(systemChangeHisStr)) {
systemChangeHisStr += "<br><br>";
}
systemChangeHisStr += licenseNameChangeHisStr;
}
if (versionChangedList != null) {
String versionChangedStr = "<b>The following open source version below has been changed to a registered version</b><br><br>";
for (String s : versionChangedList) {
versionChangedStr += "<br>" + s;
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, fileSeq), versionChangedStr);
if (!isEmpty(systemChangeHisStr)) {
systemChangeHisStr += "<br><br>";
}
systemChangeHisStr += versionChangedStr;
}
resultMap.put("changehisLicenseName", systemChangeHisStr);
if (!putSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID, prjId), resultMap)) {
return makeJsonResponseHeader(false, null);
}
{
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setAppendix("mainList", (List<ProjectIdentification>) resultMap.get("mainData"));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) resultMap.get("subData"));
pv.setAppendix("noticeBinaryList", noticeBinaryList);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid() || !vr.isDiff() || vr.hasInfo()) {
resultMap.replace("mainData", CommonFunction.identificationSortByValidInfo(
(List<ProjectIdentification>) resultMap.get("mainData"), vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false));
return makeJsonResponseHeader(true, errMsg, resultMap, vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap());
}
}
return makeJsonResponseHeader(true, errMsg, resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
// session 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID, prjId));
return makeJsonResponseHeader(false, e.getMessage());
}
}
@GetMapping(value = PROJECT.PARTNER_OSS_FROM_PROJECT)
public @ResponseBody ResponseEntity<Object> partnerOssFromProject(OssComponents ossComponents, HttpServletRequest req,
HttpServletResponse res, Model model) {
ossComponents.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER);
Map<String, Object> map = projectService.getPartnerOssList(ossComponents);
return makeJsonResponseHeader(map);
}
/**
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.COMMENTS_SAVE)
public @ResponseBody ResponseEntity<Object> commentsSave(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
String resCd = "";
String resMsg= "";
Project project = new Project();
project.setPrjId(commentsHistory.getReferenceId());
Project projectDetail = projectService.getProjectDetail(project);
if (projectDetail.getCompleteYn().equals(CoConstDef.FLAG_NO)) {
//향후 메세지 처리 확인 할것
return makeJsonResponseHeader(false, "The status is not Complete. Check the status value.", null);
}else {
String commentsMode = commentsHistory.getCommentsMode();
if (commentsMode.equals("reject")) {
project.setCompleteYn(CoConstDef.FLAG_NO);
project.setStatusRequestYn(CoConstDef.FLAG_NO);
project.setCommId(null);
project.setUserComment(commentsHistory.getContents());
project.setIgnoreUserCommentReg(CoConstDef.FLAG_YES);
resMsg = getMessage("msg.distribute.reset");
if ("10".equals(resCd)){
}
else if ("20".equals(resCd)){
resMsg="server error.";
}
else{
resMsg = resCd;
}
if (!resCd.equals("10")) {
return makeJsonResponseHeader(false, resMsg, null);
}
}else{
commentsHistory.setMailType(CoConstDef.CD_MAIL_TYPE_PROJECT_REQUESTTOOPEN_COMMENT);
commentsHistory.setStatus("Request to Open");
commentService.registComment(commentsHistory);
project.setCommId(commentsHistory.getCommId());
project.setStatusRequestYn(CoConstDef.FLAG_YES);
}
projectService.updateProjectMaster(project);
}
return makeJsonResponseHeader();
}
/**
* @param commentsHistory
* @param req
* @param res
* @param model
* @return
*/
@PostMapping(value = PROJECT.COMMENTS_IGNORE)
public @ResponseBody ResponseEntity<Object> commentsIgnore(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
Project project = new Project();
project.setPrjId(commentsHistory.getReferenceId());
Project projectDetail = projectService.getProjectDetail(project);
if (projectDetail.getCompleteYn().equals(CoConstDef.FLAG_NO)) {
//향후 메세지 처리 확인 할것
return makeJsonResponseHeader(false, "The status is not Complete. Check the status value.", null);
}else {
project.setCompleteYn(CoConstDef.FLAG_YES);
project.setStatusRequestYn(CoConstDef.FLAG_NO);
project.setCommId(null);
commentsHistory.setStatus("Request to Open(Ignore)");
commentsHistory.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_HIS);
commentService.registComment(commentsHistory);
projectService.updateProjectMaster(project);
}
return makeJsonResponseHeader();
}
/**
* Save comment.
*
* @param commentsHistory the comments history
* @param req the req
* @param res the res
* @param model the model
* @return the response entity
*/
@PostMapping(value = PROJECT.SAVE_COMMENT)
public @ResponseBody ResponseEntity<Object> saveComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
commentService.registComment(commentsHistory);
return makeJsonResponseHeader();
}
/**
* Model file.
*
* @param file the file
* @param req the req
* @param request the request
* @param res the res
* @param model the model
* @return the string
* @throws Exception the exception
*/
@PostMapping(value = PROJECT.MODEL_FILE)
public @ResponseBody ResponseEntity<Object> modelFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
// 엑셀 분석
Map<String, List<Project>> modelList = ExcelUtil.getModelList(req, CommonFunction.emptyCheckProperty("upload.path", "/upload"),
request.getParameter("distributionTarget"), request.getParameter("prjId"), request.getParameter("modelListAppendFlag"), request.getParameter("modelSeq"));
return makeJsonResponseHeader(modelList);
}
@PostMapping(value = PROJECT.SUPPLEMENT_NOTICE_FILE)
public @ResponseBody ResponseEntity<Object> getSupplementNoticeFile(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String fileId = null;
String prjId = (String) map.get("referenceId");
String zipFlag = (String) map.get("zipFlag");
try {
Project project = new Project();
project.setPrjId(prjId);
Project projectDetail = projectService.getProjectDetail(project);
ProjectIdentification identification = new ProjectIdentification();
identification.setReferenceId(prjId);
identification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
Map<String, Object> result = getOssComponentDataInfo(identification, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
String validMsg = projectService.checkValidData(result);
if (isEmpty(validMsg)) {
if (CoConstDef.FLAG_YES.equals(zipFlag)) {
fileId = projectService.makeZipFileId(result, projectDetail);
} else {
try {
String contents = projectService.makeNoticeFileContents(result);
fileId = projectService.makeSupplementFileId(contents, projectDetail);
} catch(Exception e) {
log.error(e.getMessage());
}
}
} else {
return makeJsonResponseHeader(false, validMsg);
}
if (isEmpty(fileId)){
return makeJsonResponseHeader(false, "overflow");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(fileId);
}
// 20210715_BOM COMPARE FUNC MOVE (LgeProjectController > ProjectController) >>>
@GetMapping(value=PROJECT.BOM_COMPARE, produces = "text/html; charset=utf-8")
public String bomCompare(@PathVariable String beforePrjId,
@PathVariable String afterPrjId,
HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
if (beforePrjId.equals("0000")) {
model.addAttribute("beforePrjId", "");
}else {
model.addAttribute("beforePrjId", beforePrjId);
}
if (afterPrjId.equals("0000")) {
model.addAttribute("afterPrjId", "");
}else {
model.addAttribute("afterPrjId", afterPrjId);
}
return PROJECT.PAGE_JSP;
}
@SuppressWarnings("unchecked")
@GetMapping(value=PROJECT.BOM_COMPARE_LIST_AJAX)
public @ResponseBody ResponseEntity<Object> bomCompareList(
@RequestParam("beforePrjId") String beforePrjId, @RequestParam("afterPrjId") String afterPrjId) throws Exception{
Map<String, Object> resultMap = new HashMap<>();
try {
Project beforePrjInfo = projectService.getProjectBasicInfo(beforePrjId);
String beforeReferenceDiv = "";
ProjectIdentification beforeIdentification = new ProjectIdentification();
beforeIdentification.setReferenceId(beforePrjId);
if(!beforePrjInfo.getNoticeType().equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED)) {
beforeReferenceDiv = CoConstDef.CD_DTL_COMPONENT_ID_BOM;
beforeIdentification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BOM);
beforeIdentification.setMerge("N");
} else {
beforeReferenceDiv = CoConstDef.CD_DTL_COMPONENT_ID_ANDROID;
beforeIdentification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
}
Project afterPrjInfo = projectService.getProjectBasicInfo(afterPrjId);
String afterReferenceDiv = "";
ProjectIdentification AfterIdentification = new ProjectIdentification();
AfterIdentification.setReferenceId(afterPrjId);
if(!afterPrjInfo.getNoticeType().equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED)) {
afterReferenceDiv = CoConstDef.CD_DTL_COMPONENT_ID_BOM;
AfterIdentification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BOM);
AfterIdentification.setMerge("N");
} else {
afterReferenceDiv = CoConstDef.CD_DTL_COMPONENT_ID_ANDROID;
AfterIdentification.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
}
Map<String, Object> beforeBom = new HashMap<String, Object>();
Map<String, Object> afterBom = new HashMap<String, Object>();
List<ProjectIdentification> beforeBomList = null;
List<ProjectIdentification> afterBomList = null;
boolean beforeDataFlag = false;
boolean afterDataFlag = false;
beforeBom = getOssComponentDataInfo(beforeIdentification, beforeReferenceDiv);
if (beforeReferenceDiv.equals(CoConstDef.CD_DTL_COMPONENT_ID_BOM)) {
if (!beforeBom.containsKey("rows") || (List<ProjectIdentification>) beforeBom.get("rows") == null) {
beforeDataFlag = true;
} else {
beforeBomList = (List<ProjectIdentification>) beforeBom.get("rows");
}
} else {
if (!beforeBom.containsKey("mainData") || (List<ProjectIdentification>) beforeBom.get("mainData") == null) {
beforeDataFlag = true;
} else {
beforeBomList = projectService.setMergeGridDataByAndroid((List<ProjectIdentification>) beforeBom.get("mainData"));
}
}
if (beforeDataFlag || beforeBomList == null) return makeJsonResponseHeader(false, "1");
afterBom = getOssComponentDataInfo(AfterIdentification, afterReferenceDiv);
if (afterReferenceDiv.equals(CoConstDef.CD_DTL_COMPONENT_ID_BOM)) {
if (!afterBom.containsKey("rows") || (List<ProjectIdentification>) afterBom.get("rows") == null) {
afterDataFlag = true;
} else {
afterBomList = (List<ProjectIdentification>) afterBom.get("rows");
}
} else {
if (!afterBom.containsKey("mainData") || (List<ProjectIdentification>) afterBom.get("mainData") == null) {
afterDataFlag = true;
} else {
afterBomList = projectService.setMergeGridDataByAndroid((List<ProjectIdentification>) afterBom.get("mainData"));
}
}
if (afterDataFlag || afterBomList == null) return makeJsonResponseHeader(false, "1");
resultMap.put("contents", projectService.getBomCompare(beforeBomList, afterBomList, "list"));
return makeJsonResponseHeader(true, "0" , resultMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, "1");
}
}
@PostMapping(value=PROJECT.PROJECT_STATUS)
public @ResponseBody ResponseEntity<Object> getProjectStatus(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, String> map = new HashMap<String, String>();
Project prjBean = projectService.getProjectDetail(project);
map.put("projectStatus", prjBean.getStatus());
map.put("identificationStatus", prjBean.getIdentificationStatus());
map.put("verificationStatus", prjBean.getVerificationStatus());
map.put("distributionStatus", prjBean.getDestributionStatus());
map.put("distributeDeployYn", prjBean.getDistributeDeployYn());
map.put("distributeDeployTime", prjBean.getDistributeDeployTime());
map.put("completeFlag", avoidNull(prjBean.getCompleteYn(), CoConstDef.FLAG_NO));
map.put("dropFlag", avoidNull(prjBean.getDropYn(), CoConstDef.FLAG_NO));
map.put("commId", avoidNull(prjBean.getCommId(), ""));
map.put("viewOnlyFlag", avoidNull(prjBean.getViewOnlyFlag(), CoConstDef.FLAG_NO));
return makeJsonResponseHeader(map);
}
@PostMapping(value=PROJECT.MAKE_YAML)
public @ResponseBody ResponseEntity<Object> makeYaml(
@RequestBody Project project
, @PathVariable String code
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String yamlFileId = "";
try {
// identification Tab Code / partnerName 필수 값.
yamlFileId = YamlUtil.makeYaml(code, toJson(project));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(yamlFileId);
}
@PostMapping(value=PROJECT.PROJECT_DIVISION)
public @ResponseBody ResponseEntity<Object> updateProjectDivision(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
List<String> permissionCheckList = null;
if (!CommonFunction.isAdmin()) {
CommonFunction.setProjectService(projectService);
permissionCheckList = CommonFunction.checkUserPermissions(loginUserName(), project.getPrjIds(), "project");
}
if (permissionCheckList == null || permissionCheckList.isEmpty()){
Map<String, List<Project>> updatePrjDivision = projectService.updateProjectDivision(project);
if (updatePrjDivision.containsKey("before") && updatePrjDivision.containsKey("after")) {
List<Project> beforePrjList = (List<Project>) updatePrjDivision.get("before");
List<Project> afterPrjList = (List<Project>) updatePrjDivision.get("after");
if ((beforePrjList != null && !beforePrjList.isEmpty())
&& (afterPrjList != null && !afterPrjList.isEmpty())
&& beforePrjList.size() == afterPrjList.size()) {
for (int i=0; i<beforePrjList.size(); i++) {
try {
String mailType = CoConstDef.CD_MAIL_TYPE_PROJECT_CHANGED;
CoMail mailBean = new CoMail(mailType);
mailBean.setParamPrjId(afterPrjList.get(i).getPrjId());
mailBean.setCompareDataBefore(beforePrjList.get(i));
mailBean.setCompareDataAfter(afterPrjList.get(i));
mailBean.setToIdsCheckDivision(true);
CoMailManager.getInstance().sendMail(mailBean);
try {
CommentsHistory commentsHistory = new CommentsHistory();
commentsHistory.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_HIS);
commentsHistory.setReferenceId(afterPrjList.get(i).getPrjId());
commentsHistory.setContents(afterPrjList.get(i).getUserComment());
commentsHistory.setStatus("Changed");
commentService.registComment(commentsHistory, false);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} catch(Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
} else {
return makeJsonResponseHeader(false, null, permissionCheckList);
}
return makeJsonResponseHeader();
}
public void updateProjectNotification(Project project, Map<String, Object> resultMap) {
if (resultMap != null){
String mailType = (String) resultMap.get("mailType");
String userComment = (String) resultMap.get("userComment");
String commentDiv = (String) resultMap.get("commentDiv");
String status = (String) resultMap.get("status");
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (!isEmpty(mailType)) {
try {
CoMail mailBean = new CoMail(mailType);
mailBean.setParamPrjId(project.getPrjId());
mailBean.setComment(userComment);
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if (!isEmpty(avoidNull(userComment).trim())) {
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(commentDiv);
commHisBean.setReferenceId(project.getPrjId());
commHisBean.setContents(userComment);
commHisBean.setStatus(status);
log.info(status + " 상태 comment 저장!!");
commentService.registComment(commHisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if (!isEmpty(status)) {
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(commentDiv);
commHisBean.setReferenceId(project.getPrjId());
commHisBean.setContents(userComment);
commHisBean.setStatus(status);
log.info("comment empty, " + status + " 상태 comment 저장!!");
commentService.registComment(commHisBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.PROJECT_BINARY_DB_SAVE)
public @ResponseBody ResponseEntity<Object> binaryDBSave(@RequestBody Project project,
HttpServletRequest req, HttpServletResponse res, Model model) {
Project prjInfo = projectService.getProjectDetail(project);
boolean booleanFlag = false;
if(project.getReferenceDiv().equals(CoConstDef.CD_DTL_COMPONENT_ID_BOM)) {
if(prjInfo != null && !isEmpty(prjInfo.getBinBinaryFileId()) && prjInfo.getIdentificationSubStatusBin() != null && !(CoConstDef.FLAG_NO.equals(prjInfo.getIdentificationSubStatusBin()))
&& !(CoConstDef.FLAG_YES.equals(project.getIgnoreBinaryDbFlag()))) {
try {
ProjectIdentification parambin = new ProjectIdentification();
parambin.setReferenceId(prjInfo.getPrjId());
parambin.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BIN);
Map<String, Object> mapbin = projectService.getIdentificationGridList(parambin);
// platform 정보
String platformName = "";
String platformVer = "";
if(CoConstDef.COMMON_SELECTED_ETC.equals(prjInfo.getOsType()) && !isEmpty(prjInfo.getOsTypeEtc())) {
platformName = CommonFunction.getPlatformName(prjInfo.getOsTypeEtc());
platformVer = CommonFunction.getPlatformVersion(prjInfo.getOsTypeEtc());
} else {
String _temp = CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, prjInfo.getOsType());
platformName = CommonFunction.getPlatformName(_temp);
platformVer = CommonFunction.getPlatformVersion(_temp);
}
String _prjName = "[" + prjInfo.getPrjId() + "]" + prjInfo.getPrjName();
if(!isEmpty(prjInfo.getPrjVersion())) {
_prjName += "_" + prjInfo.getPrjVersion();
}
binaryDataService.insertBatConfirmBinOssWithChecksum(_prjName, platformName, platformVer, prjInfo.getBinBinaryFileId(), (List<ProjectIdentification>) mapbin.get("mainData"));
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
booleanFlag = true;
}
}else {
booleanFlag = false;
}
}
if(project.getReferenceDiv().equals(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID)) {
if(prjInfo != null && !isEmpty(prjInfo.getSrcAndroidResultFileId()) && prjInfo.getIdentificationSubStatusAndroid() != null && !(CoConstDef.FLAG_NO.equals(prjInfo.getIdentificationSubStatusAndroid()))
&& !(CoConstDef.FLAG_YES.equals(project.getIgnoreBinaryDbFlag()))) {
try {
ProjectIdentification paramandroid = new ProjectIdentification();
paramandroid.setReferenceId(prjInfo.getPrjId());
paramandroid.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
Map<String, Object> mapandroid = projectService.getIdentificationGridList(paramandroid);
// platform 정보
String platformName = "";
String platformVer = "";
if(CoConstDef.COMMON_SELECTED_ETC.equals(prjInfo.getOsType()) && !isEmpty(prjInfo.getOsTypeEtc())) {
platformName = CommonFunction.getPlatformName(prjInfo.getOsTypeEtc());
platformVer = CommonFunction.getPlatformVersion(prjInfo.getOsTypeEtc());
} else {
String _temp = CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, prjInfo.getOsType());
platformName = CommonFunction.getPlatformName(_temp);
platformVer = CommonFunction.getPlatformVersion(_temp);
}
String _prjName = "[" + prjInfo.getPrjId() + "]" + prjInfo.getPrjName();
if(!isEmpty(prjInfo.getPrjVersion())) {
_prjName += "_" + prjInfo.getPrjVersion();
}
binaryDataService.insertBatConfirmAndroidBinOssWithChecksum(_prjName, platformName, platformVer, prjInfo.getSrcAndroidResultFileId(), (List<ProjectIdentification>) mapandroid.get("mainData"));
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
booleanFlag = true;
}
}else {
booleanFlag = false;
}
}
return makeJsonResponseHeader(booleanFlag, null);
}
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.DELETE_FILES)
public @ResponseBody ResponseEntity<Object> deleteFiles (@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
// default validation
boolean isValid = true;
// last response map
Map<String, String> resMap = new HashMap<>();
// default 00:java error check code, 10:success code
String resCd = "00";
String delFileString = (String) map.get("csvDelFileIds");
String prjId = (String) map.get("prjId");
String referenceDiv = (String) map.get("referenceDiv");
Type collectionType = new TypeToken<List<T2File>>() {}.getType();
List<T2File> delFile = new ArrayList<T2File>();
delFile = (List<T2File>) fromJson(delFileString, collectionType);
if (delFile.size() > 0) {
try {
Project project = new Project();
project.setCsvFile(delFile);
project.setPrjId(prjId);
project.setReferenceDiv(referenceDiv);
projectService.deleteUploadFile(project);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// success code set 10
resCd = "10";
resMap.put("isValid", String.valueOf(isValid));
resMap.put("resCd", resCd);
}
return makeJsonResponseHeader(resMap);
}
@PostMapping(value = PROJECT.CHECK_REQ_ENTRY_SECURITY)
public @ResponseBody ResponseEntity<Object> checkReqEntrySecurity(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String prjId = (String)map.get("prjId");
String tabMenu = (String)map.get("tabMenu");
Project param = new Project();
param.setPrjId(prjId);
boolean reqEntryFlag = projectService.checkReqEntrySecurity(param, tabMenu);
if (!reqEntryFlag) {
return makeJsonResponseHeader();
} else {
return makeJsonResponseHeader(false, "checkReqEntry");
}
}
@PostMapping(value=PROJECT.SEC_BULK_EDIT_POPUP)
public String securityBulkEditPopup(HttpServletRequest req, HttpServletResponse res,
@RequestParam(value="rowId", required=true)String rowId,
@RequestParam(value="gridId", required=true)String gridId,
@RequestParam(value="target", required=true)String target,
Model model){
model.addAttribute("rowId", rowId);
model.addAttribute("gridId", gridId);
model.addAttribute("target", target);
return PROJECT.SEC_BULK_EDIT_POPUP_JSP;
}
@GetMapping(value = PROJECT.SECURITY)
public String security(@ModelAttribute ProjectIdentification identification, HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId) {
Project project = new Project();
project.setPrjId(prjId);
Project projectMaster = projectService.getProjectDetail(project);
if (!StringUtil.isEmpty(projectMaster.getCreator())){
projectMaster.setPrjDivision(projectService.getDivision(projectMaster));
}
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_USER);
comHisBean.setReferenceId(projectMaster.getPrjId());
projectMaster.setUserComment(commentService.getUserComment(comHisBean));
model.addAttribute("project", projectMaster);
return PROJECT.SECURITY_JSP;
}
@SuppressWarnings("unchecked")
@GetMapping(value = PROJECT.SECURITY_GRID)
public @ResponseBody ResponseEntity<Object> srcSecurityGridAjax(@ModelAttribute ProjectIdentification identification,
HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String prjId, @PathVariable String code) {
Map<String, Object> rtnMap = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();
Project project = new Project();
project.setPrjId(prjId);
try {
result = projectService.getSecurityGridList(project);
rtnMap.put("totalGridData", (List<OssComponents>) result.get("totalList"));
rtnMap.put("fixedGridData", (List<OssComponents>) result.get("fixedList"));
rtnMap.put("notFixedGridData", (List<OssComponents>) result.get("notFixedList"));
if (result.containsKey("msg")) {
rtnMap.put("msg", result.get("msg"));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(rtnMap);
}
@SuppressWarnings("unchecked")
@PostMapping(value = PROJECT.SAVE_SECURITY)
public @ResponseBody ResponseEntity<Object> saveSecurity(@RequestBody Map<String, Object> map, HttpServletRequest req,
HttpServletResponse res, Model model) {
String prjId = (String) map.get("referenceId");
String tabName = (String) map.get("targetName");
String gridString = (String) map.get("gridData");
Type collectionType = new TypeToken<List<OssComponents>>() {}.getType();
List<OssComponents> ossComponents = new ArrayList<>();
ossComponents = (List<OssComponents>) fromJson(gridString, collectionType);
Map<String, String> resMap = new HashMap<>();
try {
projectService.registSecurity(prjId, tabName, ossComponents);
Project param = new Project();
param.setPrjId(prjId);
Project pDat = projectService.getProjectDetail(param);
resMap.put("identificationStatus", pDat.getIdentificationStatus());
History h = projectService.work(pDat);
h.sethAction(CoConstDef.ACTION_CODE_NEEDED);
historyService.storeData(h); // 메일로 보낼 데이터를 History에 저장합니다. -> h.gethData()로 확인 가능
} catch (Exception e) {
log.error(e.getMessage(), e);
resMap.put("isValid", "false");
} finally {
resMap.put("isValid", "true");
}
return makeJsonResponseHeader(resMap);
}
@PostMapping(value = PROJECT.CHECK_SELECT_DOWNLOAD_FILE)
public @ResponseBody ResponseEntity<Object> checkSelectDownloadFile(@RequestBody HashMap<String, Object> map, @PathVariable String code, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> resMap = new HashMap<>();
String prjId = (String) map.get("prjId");
Project project = new Project();
project.setPrjId(prjId);
project.setReferenceDiv(code);
resMap = projectService.checkSelectDownloadFile(project);
return makeJsonResponseHeader(resMap);
}
}
| 193,180 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
AdviceController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/AdviceController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import oss.fosslight.CoTopComponent;
import oss.fosslight.config.AppConstBean;
import oss.fosslight.domain.T2Users;
@ControllerAdvice
public class AdviceController extends CoTopComponent{
@ModelAttribute("req")
public HttpServletRequest getRequest(HttpServletRequest req){
return req;
}
@ModelAttribute("sessUserId")
public String getSessUserId(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
return auth.getName();
}
return "";
}
@SuppressWarnings("unchecked")
@ModelAttribute("sessUserInfo")
public T2Users getSessUserInfo(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
HashMap<String, Object> sessDetailInfo = null;
T2Users sessUserInfo = null;
if (auth != null) {
try{
sessDetailInfo = (HashMap<String, Object>) auth.getDetails();
}catch(Exception e){
}
if (sessDetailInfo != null){
sessUserInfo = (T2Users)sessDetailInfo.get("sessUserInfo");
}
}
return sessUserInfo;
}
@ModelAttribute("isMobile")
public boolean checkMobile(HttpServletRequest req) {
return req.getHeader("User-Agent").indexOf("Mobile") != -1;
}
@ModelAttribute("pageTitle") public String pageTitle(){return "";}
@ModelAttribute("pageTitlePrefix") public String pageTitlePrefix(){return AppConstBean.APP_NAME;}
}
| 1,890 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/VulnerabilityController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.SESSION;
import oss.fosslight.common.Url.VULNERABILITY;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Vulnerability;
import oss.fosslight.service.VulnerabilityService;
@Controller
public class VulnerabilityController extends CoTopComponent {
@Autowired VulnerabilityService vulnerabilityService;
@GetMapping(value=VULNERABILITY.LIST, produces = "text/html; charset=utf-8")
public String list(HttpServletRequest req, HttpServletResponse res, Model model){
Object _param = getSessionObject(CoConstDef.SESSION_KEY_PREFIX_DEFAULT_SEARCHVALUE + "VULNOSSNAME", true);
if (_param != null) {
String defaultSearchOssName = (String) _param;
if (!isEmpty(defaultSearchOssName)) {
if (defaultSearchOssName.indexOf("|") > -1) {
String[] params = defaultSearchOssName.split("\\|");
model.addAttribute("defaultOssName", params[0]);
model.addAttribute("defaultOssVersion", params[1]);
} else {
model.addAttribute("defaultOssName", defaultSearchOssName);
}
}
model.addAttribute("exactMatchFlag", !isEmpty(defaultSearchOssName) ? CoConstDef.FLAG_YES : CoConstDef.FLAG_NO);
}
return VULNERABILITY.LIST_JSP;
}
@GetMapping(value=VULNERABILITY.LIST_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> listajax(@ModelAttribute Vulnerability vulnerability,
HttpServletRequest req, HttpServletResponse res) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
vulnerability.setCurPage(page);
vulnerability.setPageListSize(rows);
HashMap<String, Object> map = vulnerabilityService.getVulnerabilityList(vulnerability, false);
return makeJsonResponseHeader(map);
}
@GetMapping(value=VULNERABILITY.CHECK_CVE_ID, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> checkCveId(@RequestParam(name = "cveId") String cveId) {
return makeJsonResponseHeader(vulnerabilityService.getCveInfo(cveId));
}
@GetMapping(value=VULNERABILITY.AUTOCOMPLETE_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> AutoCompleteAjax(HttpServletRequest req, HttpServletResponse res){
HashMap<String, Object> map = vulnerabilityService.getVulnerabilityAutoComplete();
return makeJsonResponseHeader(map);
}
@GetMapping(value=VULNERABILITY.VERSION_AUTOCOMPLETE_AJAX, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> VersionAutoCompleteAjax(HttpServletRequest req, HttpServletResponse res){
String name = avoidNull(req.getParameter("product"));
List<String> list = vulnerabilityService.getVulnerabilityVersionAutoComplete(name);
return makeJsonResponseHeader(list);
}
@GetMapping(value=VULNERABILITY.VULN_POPUP, produces = "text/html; charset=utf-8")
public String vulnpopup(HttpServletRequest req, HttpServletResponse res, @ModelAttribute OssMaster bean, Model model) throws IOException{
if (!isLogin()) {
return SESSION.LOGIN_JSP;
}
model.addAttribute("ossInfo", bean);
return VULNERABILITY.VULN_POPUP_JSP;
}
@GetMapping(value=VULNERABILITY.VULN_LIST)
public @ResponseBody ResponseEntity<Object> getVulnList(
HttpServletRequest req,
HttpServletResponse res,
@ModelAttribute OssMaster bean,
Model model){
Map<String, Object> resultMap = new HashMap<>();
if (!isEmpty(bean.getOssName())) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
Map<String, String> exceptionMap = new HashMap<>();
exceptionMap.put("product", "product");
exceptionMap.put("version", "version");
exceptionMap.put("cvssScore", "cvssScore");
exceptionMap.put("cveId", "cveId");
exceptionMap.put("modiDate", "modiDate");
String filters = "";
if (!isEmpty(bean.getFilters())) {
filters = bean.getFilters().replaceAll("\"op\":\"cn\"", "\"op\":\"eq\""); // popup에서는 equals만 지원함.
}
String filterCondition = CommonFunction.getFilterToString(filters, null, exceptionMap);
if (!isEmpty(filterCondition)) {
bean.setFilterCondition(filterCondition);
}
bean.setSord(sord);
bean.setSidx(sidx);
bean.setCurPage(page);
bean.setPageListSize(rows);
if (avoidNull(bean.getVulnerabilityCheckFlag(), "").equals(CoConstDef.FLAG_NO)) {
bean.setVulnerabilityCheckFlag(null);
} else {
bean.setVulnerabilityCheckFlag(CoConstDef.FLAG_YES);
}
resultMap = vulnerabilityService.getVulnListByOssName(bean);
}
return makeJsonResponseHeader(resultMap);
}
}
| 5,811 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ImageUploadProcController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ImageUploadProcController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.IMAGE_UPLOAD;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.service.FileService;
@Controller
public class ImageUploadProcController extends CoTopComponent {
@Autowired FileService fileService;
@PostMapping(value=IMAGE_UPLOAD.UPLOAD)
public void imageUpload (
HttpServletRequest req, HttpServletResponse res) throws IOException{
PrintWriter printWriter = null;
String callback = req.getParameter("CKEditorFuncNum");
T2File fileInfo = new T2File();
fileInfo.setGubn(CoConstDef.FILE_GUBUN_EDITOR_IMAGE);
List<UploadFile> fList = fileService.uploadFile(req, fileInfo);
if (fList != null && !fList.isEmpty()) {
for (UploadFile f : fList) {
if (f.isUploadSucc()) {
res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
printWriter = res.getWriter();
String _host = req.getScheme() + "://" + req.getServerName();
if (req.getServerPort() > 0) {
int _port = req.getServerPort();
if (80 != _port && 443 != _port) {
_host += ":" + String.valueOf(_port);
}
}
String fileUrl = _host + "/download/" + f.getRegistSeq() + "/" + f.getFileName();
printWriter.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("
+ callback + ",'" + fileUrl + "','Success'" + ")</script>");
printWriter.flush();
break;
}
}
}
}
@PostMapping(value=IMAGE_UPLOAD.UPLOAD2)
public ResponseEntity<Object> imageUpload2 (
HttpServletRequest req, HttpServletResponse res) throws IOException{
T2File fileInfo = new T2File();
fileInfo.setGubn(CoConstDef.FILE_GUBUN_EDITOR_IMAGE);
List<UploadFile> fList = fileService.uploadFile(req, fileInfo);
Map<String, Object> resultMap = new HashMap<>();
if (fList != null && !fList.isEmpty()) {
for (UploadFile f : fList) {
if (f.isUploadSucc()) {
resultMap.put("uploaded", 1);
resultMap.put("fileName", f.getOriginalFilename());
String _host = req.getScheme() + "://" + req.getServerName();
if (req.getServerPort() > 0) {
int _port = req.getServerPort();
if (80 != _port && 443 != _port) {
_host += ":" + String.valueOf(_port);
}
}
resultMap.put("url", _host + "/imageView/" + f.getFileName());
break;
}
}
}
if (resultMap.isEmpty()) {
resultMap.put("uploaded", 0);
}
return makeJsonResponseHeader(resultMap);
}
} | 3,286 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SystemConfigurationController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SystemConfigurationController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.SYSTEM_CONFIGURATION;
import oss.fosslight.service.SystemConfigurationService;
@Controller
@Slf4j
public class SystemConfigurationController extends CoTopComponent {
@Autowired SystemConfigurationService configurationService;
@GetMapping(value=SYSTEM_CONFIGURATION.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
model.addAttribute("rootPath", CommonFunction.getProperty("root.dir"));
model.addAttribute("dashboardFlag", CommonFunction.propertyFlagCheck("menu.dashboard.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("statisticsFlag", CommonFunction.propertyFlagCheck("menu.statistics.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("binarydbFlag", CommonFunction.propertyFlagCheck("menu.binarydb.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("complianceStatusFlag", CommonFunction.propertyFlagCheck("menu.compliancestatus.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("externalLinkFlag", CommonFunction.propertyFlagCheck("menu.externallink.use.flag", CoConstDef.FLAG_YES));
return SYSTEM_CONFIGURATION.PAGE_JSP;
}
@SuppressWarnings("unchecked")
@PostMapping(value=SYSTEM_CONFIGURATION.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@RequestBody HashMap<String, Object> map,
HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
Map<String, Object> result = new HashMap<String, Object>();
String config = (String) map.get("config");
Type collectionType = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> configMap = new HashMap<String, Object>();
configMap = (Map<String, Object>) fromJson(config, collectionType);
try {
result = configurationService.saveConfiguration(configMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
result.put("resCd", "00");
result.put("resMsg", "Error");
}
return makeJsonResponseHeader(result);
}
}
| 3,384 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ScannerController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ScannerController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url;
import oss.fosslight.domain.T2Users;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.RequestUtil;
import oss.fosslight.util.StringUtil;
@RestController
@Slf4j
public class ScannerController {
@Autowired ResponseService responseService;
@Autowired T2UserService userService;
@PostMapping(value = {Url.EXTERNAL.REQUEST_FL_SCAN})
public CommonResult requestFlScanService(
@RequestParam(name = "prjId", required = true) String prjId,
@RequestParam(name = "wgetUrl", required = true) String wgetUrl){
try {
log.info("fl scanner start pid : " + prjId + ", url:" + wgetUrl);
String scanServiceUrl = CoCodeManager.getCodeExpString(CoConstDef.CD_EXTERNAL_ANALYSIS_SETTING, CoConstDef.CD_DTL_FL_SCANNER_URL);
String adminToken = CoCodeManager.getCodeExpString(CoConstDef.CD_EXTERNAL_ANALYSIS_SETTING, CoConstDef.CD_DTL_ADMIN_TOKEN);
if (StringUtil.isEmpty(scanServiceUrl) || StringUtil.isEmpty(adminToken)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE, "FL Scanner Url or Admin token is not configured");
}
T2Users user = userService.getLoginUserInfo();
if (user == null || StringUtil.isEmpty(user.getEmail())) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE, "Login User Email is not configured");
}
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("pid", prjId);
parts.add("link", wgetUrl);
parts.add("email", user.getEmail());
parts.add("admin", adminToken);
String resBody = RequestUtil.post(scanServiceUrl, parts);
log.info("fl scanner response : " + resBody);
return responseService.getSuccessResult();
} catch (Exception e) {
log.error("failed request fl scan, pid:" + prjId + ", url:" + wgetUrl, e);
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE, e.getMessage());
}
}
}
| 2,725 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SearchController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SearchController.java | /*
* Copyright (c) 2021 Suram Kim
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.domain.*;
import oss.fosslight.common.Url.SEARCH;
import oss.fosslight.service.SearchService;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
@Controller
@Slf4j
public class SearchController extends CoTopComponent {
@Autowired SearchService searchService;
@GetMapping(value=SEARCH.LICENSE)
public @ResponseBody ResponseEntity<Object> saveLicenseSearchFilter(LicenseMaster licenseMaster
, HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = getSidx(req);
String sord = req.getParameter("sord");
licenseMaster.setCurPage(page);
licenseMaster.setPageListSize(rows);
licenseMaster.setSortField(sidx);
licenseMaster.setSortOrder(sord);
searchService.saveLicenseSearchFilter(licenseMaster, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.OSS)
public @ResponseBody ResponseEntity<Object> saveOssSearchFilter(OssMaster ossMaster,
HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = getSidx(req);
ossMaster.setSidx(sidx);
ossMaster.setCurPage(page);
ossMaster.setPageListSize(rows);
ossMaster.setHomepage(getHttpPrefix(req.getParameter("homepage")));
ossMaster.setSearchFlag(CoConstDef.FLAG_YES);
ossMaster.setSearchFlag(CoConstDef.FLAG_YES);
searchService.saveOssSearchFilter(ossMaster, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.PARTNER)
public @ResponseBody ResponseEntity<Object> savePartnerSearchFilter(PartnerMaster partnerMaster,
HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = getSidx(req);
String sord = req.getParameter("sord");
partnerMaster.setCurPage(page);
partnerMaster.setPageListSize(rows);
partnerMaster.setSortField(sidx);
partnerMaster.setSortOrder(sord);
searchService.savePartnerSearchFilter(partnerMaster, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.PROJECT)
public @ResponseBody ResponseEntity<Object> saveProjectSearchFilter(Project project,
HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = getSidx(req);
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
project.setPublicYn(isEmpty(project.getPublicYn()) ? CoConstDef.FLAG_YES:project.getPublicYn());
searchService.saveProjectSearchFilter(project, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.SELFCHECK)
public @ResponseBody ResponseEntity<Object> saveSelfCheckSearchFilter(Project project,
HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = getSidx(req);
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
searchService.saveSelfCheckSearchFilter(project, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.VULNERABILITY)
public @ResponseBody ResponseEntity<Object> saveVulnerabilitySearchFilter(Vulnerability vulnerability, HttpServletRequest req){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
vulnerability.setCurPage(page);
vulnerability.setPageListSize(rows);
searchService.saveVulnerabilitySearchFilter(vulnerability, loginUserName());
return makeJsonResponseHeader("saved");
}
@GetMapping(value=SEARCH.PATH)
public @ResponseBody ResponseEntity<?> getSearchInfo(@RequestParam("type") String type){
Object searchFilter = searchService.getSearchFilter(type, loginUserName());
if (Objects.isNull(searchFilter)){
return makeJsonResponseHeader(false, "Not Found");
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("type", type);
result.put("searchFilter", searchFilter);
return makeJsonResponseHeader(result);
}
public String getSidx(HttpServletRequest req){
String sidx = req.getParameter("sidx");
if (sidx != null) {
sidx = sidx.split("[,]")[1].trim();
}
return sidx;
}
public String getHttpPrefix(String homepage){
List<String> httpPrefixs = Arrays.asList("https://", "http://", "www.");
if (!httpPrefixs.contains(homepage)){
homepage = homepage.replaceFirst("^((http|https)://)?(www.)*", "");
}
return homepage;
}
}
| 6,119 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
LicenseController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/LicenseController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.*;
import oss.fosslight.common.Url.LICENSE;
import oss.fosslight.domain.*;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.LicenseService;
import oss.fosslight.service.SearchService;
import oss.fosslight.util.DateUtil;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoLicenseValidator;
import static oss.fosslight.common.CoConstDef.*;
@Controller
@Slf4j
public class LicenseController extends CoTopComponent{
@Autowired LicenseService licenseService;
@Autowired HistoryService historyService;
@Autowired CommentService commentService;
@Autowired SearchService searchService;
private final String SESSION_KEY_SEARCH = "SESSION_KEY_LICENSE_LIST";
@GetMapping(value=LICENSE.LIST)
public String list(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
LicenseMaster searchBean = null;
if (!CoConstDef.FLAG_YES.equals(req.getParameter("gnbF"))) {
deleteSession(SESSION_KEY_SEARCH);
searchBean = searchService.getLicenseSearchFilter(loginUserName());
if (searchBean == null) {
searchBean = new LicenseMaster();
}
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
searchBean = (LicenseMaster) getSessionObject(SESSION_KEY_SEARCH);
}
if (getSessionObject("defaultLoadYn") != null) {
model.addAttribute("defaultLoadYn", CoConstDef.FLAG_YES);
deleteSession("defaultLoadYn");
}
model.addAttribute("searchBean", searchBean);
return LICENSE.LIST_JSP;
}
@GetMapping(value=LICENSE.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
if ("Y".equals(req.getParameter("ignoreSearchFlag"))) {
return makeJsonResponseHeader(new HashMap<String, Object>());
}
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
licenseMaster.setCurPage(page);
licenseMaster.setPageListSize(rows);
licenseMaster.setSortField(sidx);
licenseMaster.setSortOrder(sord);
if ("search".equals(req.getParameter("act"))) {
// 검색 조건 저장
putSessionObject(SESSION_KEY_SEARCH, licenseMaster);
} else if (getSessionObject(SESSION_KEY_SEARCH) != null) {
licenseMaster = (LicenseMaster) getSessionObject(SESSION_KEY_SEARCH);
}
Map<String, Object> map = null;
try {
if (isEmpty(licenseMaster.getLicenseNameAllSearchFlag())) {
licenseMaster.setLicenseNameAllSearchFlag(CoConstDef.FLAG_NO);
}
licenseMaster.setTotListSize(licenseService.selectLicenseMasterTotalCount(licenseMaster));
map = licenseService.getLicenseMasterList(licenseMaster);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
CustomXssFilter.licenseMasterFilter((List<LicenseMaster>) map.get("rows"));
return makeJsonResponseHeader(map);
}
@GetMapping(value=LICENSE.EDIT)
public String edit(HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
return LICENSE.EDIT_JSP;
}
@GetMapping(value=LICENSE.EDIT_ID)
public String edit(@PathVariable String licenseId, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
LicenseMaster licenseMaster = new LicenseMaster(licenseId);
licenseMaster = licenseService.getLicenseMasterOne(licenseMaster);
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
if (licenseMaster != null) {
licenseMaster.setDomain(CommonFunction.getDomain(req));
licenseMaster.setInternalUrl(CommonFunction.makeLicenseInternalUrl(licenseMaster, distributionFlag));
if (!"ROLE_ADMIN".equals(loginUserRole())) {
// html link 형식으로 변환
licenseMaster.setDescription(CommonFunction.makeHtmlLinkTagWithText(licenseMaster.getDescription()));
}
model.addAttribute("licenseInfo", licenseMaster);
}
model.addAttribute("detail", toJson(licenseMaster));
if ("ROLE_ADMIN".equals(loginUserRole())) {
return LICENSE.EDIT_JSP;
} else {
return LICENSE.LICENSE_VIEW_JSP;
}
}
@PostMapping(value=LICENSE.VALIDATION)
public @ResponseBody ResponseEntity<Object> validation(
@ModelAttribute LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
// validation check
T2CoLicenseValidator lv = new T2CoLicenseValidator();
T2CoValidationResult vResult = lv.validateRequest(req);
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
@PostMapping(value=LICENSE.DEL_AJAX)
public @ResponseBody ResponseEntity<Object> delAjax(
@ModelAttribute LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
T2CoLicenseValidator lv = new T2CoLicenseValidator();
lv.setProcType(lv.PROC_TYPE_DELETE);
lv.setAppendix("licenseId", licenseMaster.getLicenseId());
T2CoValidationResult vr = lv.validate(new HashMap<>());
if (!vr.isValid()) {
return makeJsonResponseHeader(false, vr.getValidMessage("LICENSE_NAME"));
}
LicenseMaster beforeBean = licenseService.getLicenseMasterOne(licenseMaster);
try {
History h = licenseService.work(licenseMaster);
h.sethAction(CoConstDef.ACTION_CODE_DELETE);
historyService.storeData(h);
} catch(Exception e) {
log.error(e.getMessage(), e);
}
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_LICENSE_DELETE);
mailBean.setParamLicenseId(licenseMaster.getLicenseId());
mailBean.setComment(licenseMaster.getComment());
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
licenseService.deleteLicenseMaster(licenseMaster);
putSessionObject("defaultLoadYn", true); // 화면 로드 시 default로 리스트 조회 여부 flag
CoCodeManager.getInstance().refreshLicenseInfo();
try {
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
licenseService.deleteDistributeLicense(beforeBean, distributionFlag);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader();
}
@PostMapping(value=LICENSE.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@ModelAttribute LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
//License Save
Map<String, Object> resMap = licenseService.saveLicense(licenseMaster);
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=LICENSE.DELETE_COMMENT)
public @ResponseBody ResponseEntity<Object> deleteComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
T2CoValidationResult vResult = null;
try{
//validation check
vResult = validate(req);
}catch(Exception e){
log.error(e.getMessage());
}
if (!vResult.isValid()){
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
try{
commentService.deleteComment(commentsHistory);
} catch (Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
@PostMapping(value=LICENSE.SAVE_COMMENT)
public @ResponseBody ResponseEntity<Object> saveComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
T2CoValidationResult vResult = null;
try {
// validation check
vResult = validate(req);
} catch (Exception e) {
log.error(e.getMessage());
}
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
CommentsHistory result = null;
try {
result = commentService.registComment(commentsHistory);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(result);
}
@GetMapping(value=LICENSE.LICENSE_TEXT)
public @ResponseBody ResponseEntity<Object> getLicenseText(
LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
try{
if (!isEmpty(licenseMaster.getLicenseName()) && CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseMaster.getLicenseName().trim().toUpperCase())) {
return makeJsonResponseHeader(true, CommonFunction.lineReplaceToBR(avoidNull(CoCodeManager.LICENSE_INFO_UPPER.get(licenseMaster.getLicenseName().trim().toUpperCase()).getLicenseText())));
}
}catch(Exception e){
log.error(e.getMessage(), e);
}
return makeJsonResponseHeader(false, null);
}
@GetMapping(value=LICENSE.AUTOCOMPLETE_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteAjax(
LicenseMaster licenseMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
List<LicenseMaster> list = licenseService.getLicenseNameList();
CustomXssFilter.licenseMasterFilter(list);
return makeJsonResponseHeader(list);
}
@PostMapping(value=LICENSE.LICENSE_ID)
public @ResponseBody ResponseEntity<Object> getLicenseId(HttpServletRequest req, HttpServletResponse res,
@RequestParam(value="licenseName", required=true)String licenseName) {
Map<String, String> map = new HashMap<String, String>();
LicenseMaster lm = new LicenseMaster();
lm.setLicenseName(licenseName.trim());
lm = licenseService.getLicenseId(lm);
map.put("licenseId", lm.getLicenseId());
return makeJsonResponseHeader(map);
}
/**LicenseBulkReg UI*/
@GetMapping(value = LICENSE.LICENSE_BULK_REG, produces = "text/html; charset=utf-8")
public String LicenseBulkRegPage(HttpServletRequest req, HttpServletResponse res, Model model) {
return LICENSE.LICENSE_BULK_REG_JSP;
}
/**
* LicenseBulkReg Save Post
* */
@PostMapping(value = Url.LICENSE.BULK_REG_AJAX)
public @ResponseBody
ResponseEntity<Object> saveAjaxJson(
@RequestBody List<LicenseMaster> licenseMasters
, HttpServletRequest req
, HttpServletResponse res
, Model model) {
List<Map<String, Object>> licenseDataMapList = new ArrayList<>();
Map<String, Object> resMap = new HashMap<>();
if (licenseMasters.isEmpty()) {
//When the licenseMaster List delivered from the client is empty (if the upload button is pressed without uploading the file)
resMap.put("res", false);
return makeJsonResponseHeader(resMap);
}
for (LicenseMaster license : licenseMasters) {
Map<String, Object> licenseDataMap = new HashMap<>();
if (license.getLicenseType().equalsIgnoreCase("Permissive")) {
license.setLicenseType(CD_LICENSE_TYPE_PMS);
} else if (license.getLicenseType().equalsIgnoreCase("Weak Copyleft")) {
license.setLicenseType(CD_LICENSE_TYPE_WCP);
} else if (license.getLicenseType().equalsIgnoreCase("Copyleft")) {
license.setLicenseType(CD_LICENSE_TYPE_CP);
} else if (license.getLicenseType().equalsIgnoreCase("Proprietary")) {
license.setLicenseType(CD_LICENSE_TYPE_NA);
} else if (license.getLicenseType().equalsIgnoreCase("Proprietary Free")) {
license.setLicenseType(CD_LICENSE_TYPE_PF);
} else {
license.setLicenseType("");
}
/**
* Set
* HotYn, notice, source
* */
license.setRestriction("");
license.setHotYn(CoConstDef.FLAG_NO);
if (license.getObligationNotificationYn().equalsIgnoreCase("o")) {
license.setObligationNotificationYn(CoConstDef.FLAG_YES);
} else {
license.setObligationNotificationYn(null);
}
if (license.getObligationDisclosingSrcYn().equalsIgnoreCase("o")) {
license.setObligationDisclosingSrcYn(CoConstDef.FLAG_YES);
} else {
license.setObligationDisclosingSrcYn(null);
}
/**
* Check
* LicenseName NPE
* LicenseName COMMA
* LicenseName DB Check
* */
if (Objects.isNull(license.getLicenseName()) || StringUtil.isBlank(license.getLicenseName())) {
log.debug("License name is required.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (Required missing)");
licenseDataMapList.add(licenseDataMap);
continue;
} else if (license.getLicenseName().contains(CoConstDef.CD_COMMA_CHAR)) {
log.debug("License name contains COMMA.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (License name contains COMMA)");
licenseDataMapList.add(licenseDataMap);
continue;
} else {
LicenseMaster licenseForCheckName = new LicenseMaster();
licenseForCheckName.setLicenseName(license.getLicenseName());
LicenseMaster resultByName = licenseService.checkExistsLicense(licenseForCheckName);
if (resultByName != null) {
log.debug("Same License already exists.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (license already exist)");
licenseDataMapList.add(licenseDataMap);
continue;
}
}
/**
* Check
* LicenseText NPE
* */
String licenseText = license.getLicenseText();
if (licenseText == null || licenseText.isEmpty()) {
log.debug("licenseText is null:" + license.getLicenseName());
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (Required missing)");
licenseDataMapList.add(licenseDataMap);
continue;
}
/**
* Check
* LicenseType NPE
* */
String licenseType = license.getLicenseType();
if (licenseType == null || licenseType.isEmpty()) {
log.debug("licenseType is null:" + license.getLicenseName());
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (Required missing)");
licenseDataMapList.add(licenseDataMap);
continue;
}
/**
* Check
* SHORT_IDENTIFIER COMMA
* SHORT_IDENTIFIER LicenseName
*/
if (license.getShortIdentifier().contains(CoConstDef.CD_COMMA_CHAR)) {
log.debug("SPDX contains COMMA.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (SPDX contains COMMA)");
licenseDataMapList.add(licenseDataMap);
continue;
} else if (license.getShortIdentifier().equalsIgnoreCase(avoidNull(license.getLicenseName()))) {
log.debug("SPDX equals with LicenseName.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (SPDX sames with LicenseName.)");
licenseDataMapList.add(licenseDataMap);
continue;
} else if(!license.getShortIdentifier().equals("")) {
LicenseMaster licenseForCheckSPDX = new LicenseMaster(license.getLicenseId());
licenseForCheckSPDX.setLicenseName(license.getShortIdentifier());
LicenseMaster resultBySPDX = licenseService.checkExistsLicense(licenseForCheckSPDX);
if (resultBySPDX != null) {
log.debug("SPDX already exits");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (SPDX already exits)");
licenseDataMapList.add(licenseDataMap);
continue;
}
}
/**
* Check
* LicenseNickname Input Duplication
* LicenseNickname contains COMMA
* LicenseNickname DB Check
*/
List<String> nickNameList = new ArrayList<>();
Boolean checkLicenseNickname = true;
for (String nickname : license.getLicenseNicknames()) {
if (nickNameList.contains(nickname.toUpperCase())) {
log.debug("Input nickname is overlapped.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (Input nickname is overlapped.)");
licenseDataMapList.add(licenseDataMap);
checkLicenseNickname = false;
break;
} else {
nickNameList.add(nickname.toUpperCase());
if (nickname.contains(CoConstDef.CD_COMMA_CHAR)) {
log.debug("LicenseNickname contains COMMA.");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (LicenseNickname contains COMMA)");
licenseDataMapList.add(licenseDataMap);
checkLicenseNickname = false;
break;
} else if (nickname.equalsIgnoreCase(avoidNull(license.getLicenseName()))
|| nickname.equalsIgnoreCase(avoidNull(license.getShortIdentifier()))) {
log.debug("Nickname equals with LicenseName or SPDX");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (Nickname equals with LicenseName or SPDX)");
licenseDataMapList.add(licenseDataMap);
checkLicenseNickname = false;
break;
} else {
LicenseMaster licenseForCheckNickname = new LicenseMaster(license.getLicenseId());
licenseForCheckNickname.setLicenseName(nickname);
LicenseMaster resultByNickname = licenseService.checkExistsLicense(licenseForCheckNickname);
if (resultByNickname != null) {
log.debug("LicenseNickname already exits");
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), false, "X (LicenseNickname already exits)");
licenseDataMapList.add(licenseDataMap);
checkLicenseNickname = false;
break;
}
}
}
}
if (checkLicenseNickname == false) {
continue;
}
Map<String, Object> result = licenseService.saveLicense(license);
if (result.get("resCd").equals("10")) {
licenseDataMap = licenseService.getLicenseDataMap(license.getGridId(), true, "O");
licenseDataMapList.add(licenseDataMap);
}
}
resMap.put("res", true);
resMap.put("value", licenseDataMapList);
return makeJsonResponseHeader(resMap);
}
/**
* Validate Bulk Reg
* */
@PostMapping(value=Url.LICENSE.BULK_VALIDATION)
public @ResponseBody ResponseEntity<Object> bulkValidation(
@RequestBody List<LicenseMaster> licenseMasters){
Map<String, Object> resMap = new HashMap<>();
T2CoLicenseValidator validator = new T2CoLicenseValidator();
validator.setAppendix("licenseList", licenseMasters);
validator.setVALIDATION_TYPE(validator.VALID_LICNESELIST_BULK);
T2CoValidationResult vr = validator.validate(new HashMap<>());
resMap.put("validData", vr.getValidMessageMap());
return makeJsonResponseHeader(resMap);
}
/**LicenseBulkReg Upload Post*/
@ResponseBody
@PostMapping(value = Url.LICENSE.CSV_FILE)
public ResponseEntity<Object> csvFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
List<Object> limitCheckFiles = new ArrayList<>();
List<UploadFile> list = new ArrayList<UploadFile>();
List<LicenseMaster> licenseList = new ArrayList<>();
Iterator<String> fileNames = req.getFileNames();
List<Map<String, Object>> licenseWithStatusList = new ArrayList<>();
Map<String, Object> resMap = new HashMap<>();
while (fileNames.hasNext()) {
UploadFile uploadFile = new UploadFile();
MultipartFile multipart = req.getFile(fileNames.next());
uploadFile.setSize(multipart.getSize());
list.add(uploadFile);
}
limitCheckFiles = CommonFunction.checkXlsxFileLimit(list);
resMap.put("limitCheck", limitCheckFiles);
licenseList = ExcelUtil.readLicenseList(req, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
if (licenseList != null) {
Map<String, Object> ossWithStatus;
for (int i = 0; i < licenseList.size(); i++) {
ossWithStatus = new HashMap<>();
ossWithStatus.put("license", licenseList.get(i));
ossWithStatus.put("status", "Ready");
licenseWithStatusList.add(ossWithStatus);
}
} else {
resMap.put("res", false);
return makeJsonResponseHeader(resMap);
}
resMap.put("res", true);
resMap.put("value", licenseWithStatusList);
return makeJsonResponseHeader(resMap);
}
}
| 20,981 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ComplianceController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ComplianceController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.COMPLIANCE;
import oss.fosslight.domain.File;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.service.ComplianceService;
import oss.fosslight.service.PartnerService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.util.ExcelUtil;
@Controller
@Slf4j
public class ComplianceController extends CoTopComponent {
@Autowired PartnerService partnerService;
@Autowired ProjectService projectService;
@Autowired ComplianceService complianceService;
@Resource private Environment env;
@GetMapping(value=COMPLIANCE.MODEL_STATUS, produces = "text/html; charset=utf-8")
public String getModelStatus(HttpServletRequest req, HttpServletResponse res, Model model){
return COMPLIANCE.MODEL_STATUS_JSP;
}
@GetMapping(value=COMPLIANCE.PARTNER_LIST_STATUS, produces = "text/html; charset=utf-8")
public String get3rdStatus(HttpServletRequest req, HttpServletResponse res, Model model){
return COMPLIANCE.PARTNER_LIST_STATUS_JSP;
}
@RequestMapping(value=COMPLIANCE.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
PartnerMaster partnerMaster
, HttpServletRequest req
, HttpServletResponse res
, Model model){
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
partnerMaster.setCurPage(page);
partnerMaster.setPageListSize(rows);
partnerMaster.setSortField(sidx);
partnerMaster.setSortOrder(sord);
if (partnerMaster.getStatus() != null) {
String statuses = partnerMaster.getStatus();
if (!isEmpty(statuses)) {
String[] arrStatuses = statuses.split(",");
partnerMaster.setArrStatuses(arrStatuses);
}
}
Map<String, Object> map = null;
try{
partnerMaster.setModelFlag(CoConstDef.FLAG_YES);
map = partnerService.getPartnerStatusList(partnerMaster);
}catch(Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(map);
}
@PostMapping(value = COMPLIANCE.MODEL_LIST_AJAX)
public @ResponseBody ResponseEntity<Object> modelListAjax(@RequestBody Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
if (!isEmpty(project.getModelName())){
String[] modelNames = project.getModelName().split(",");
List<String> modelListInfo = new ArrayList<String>();
for (String modelName : modelNames){
if (modelListInfo.indexOf(modelName) == -1){
modelListInfo.add(modelName);
}
}
project.setModelListInfo(modelListInfo);
Map<String, Object> map = complianceService.getModelList(project);
return makeJsonResponseHeader(map);
} else {
return makeJsonResponseHeader(false, "");
}
}
@PostMapping(value=COMPLIANCE.READ_MODEL_LIST)
public @ResponseBody ResponseEntity<Object> readModelList(File file, MultipartHttpServletRequest req, HttpServletRequest request, HttpServletResponse res, Model model) throws Exception{
//엑셀 분석
List<Project> modelList = ExcelUtil.getModelList(req, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
if (modelList == null) {
return makeJsonResponseHeader(false, "");
}
return makeJsonResponseHeader(true, "", modelList);
}
}
| 4,570 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
UserController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/UserController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.USER;
import oss.fosslight.domain.CoMail;
import oss.fosslight.domain.CoMailManager;
import oss.fosslight.domain.T2CodeDtl;
import oss.fosslight.domain.T2Users;
import oss.fosslight.service.CodeService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoAdminValidator;
@Controller
@Slf4j
public class UserController extends CoTopComponent {
@Autowired T2UserService userService;
@Autowired CodeService codeService;
@GetMapping(value=USER.LIST, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return USER.LIST_JSP;
}
@GetMapping(value=USER.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> userList(
HttpServletRequest req
, HttpServletResponse res
, @ModelAttribute T2Users t2User
, Model model){
return makeJsonResponseHeader(userService.getUserList(t2User));
}
/**
* [API] 유저 저장
*/
@PostMapping(value=USER.SAVE_AJAX, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public @ResponseBody ResponseEntity<Object> userSave(
@ModelAttribute T2Users vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
// validation check
T2CoValidationResult vResult = validate(req);
if (!vResult.isValid()) {
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
Map<String, String> dataMap = vResult.getDataMap();
Map<String, String> validResultMap = vResult.getValidDataMap();
vo.setCreatedDateCurrentTime();
vo.setCreator(vo.getUserId());
vo.setModifier(vo.getUserId());
vo.setEmail((String) dataMap.get("EMAIL"));
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
if (!CoConstDef.FLAG_YES.equals(ldapFlag)) {
vo.setPassword(encodePassword((String) validResultMap.get("USER_PW")));
}
// 선택된 division이 없을경우 N/A로 선택됨.
if (isEmpty(vo.getDivision())){
vo.setDivision(CoConstDef.CD_USER_DIVISION_EMPTY);
}
userService.addNewUsers(vo);
return makeJsonResponseHeader();
}
/**
* [API] 유저 수정
*/
@PostMapping(value=USER.MOD_AJAX, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public @ResponseBody ResponseEntity<Object> userMod(
@RequestBody List<T2Users> vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
HashMap<String, Object> map = new HashMap<String, Object>();
userService.modUser(vo);
return makeJsonResponseHeader(map);
}
@PostMapping(value = USER.DIVISION_LIST)
public @ResponseBody ResponseEntity<Object> getDivisionList(@RequestBody T2CodeDtl t2CodeDtl, HttpServletRequest req,
HttpServletResponse res, Model model) {
List<T2CodeDtl> list = null;
try {
list = codeService.getCodeDetailList(t2CodeDtl);
} catch (Exception e) {
log.error(e.getMessage());
}
return makeJsonResponseHeader(list);
}
@GetMapping(value = USER.CHECK_EMAIL)
public @ResponseBody ResponseEntity<Object> checkEmail(HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, String> resMap = new HashMap<>();
String email = req.getParameter("email");
List<T2Users> list = userService.checkEmail(email);
if (list.size() > 0){
resMap.put("isValid", "true");
resMap.put("userId", list.get(0).getUserId());
resMap.put("division", list.get(0).getDivision());
resMap.put("divisionName", list.get(0).getDivisionName());
}else{
resMap.put("isValid", "false");
}
return makeJsonResponseHeader(resMap);
}
@GetMapping(value = USER.AUTOCOMPLETE_CREATOR_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteCreatorAjax(T2Users t2Users, HttpServletRequest req,
HttpServletResponse res, Model model) {
t2Users.setSortField("userName");
t2Users.setSortOrder("asc");
List<T2Users> list = userService.getAllUsers(t2Users);
return makeJsonResponseHeader(list);
}
@GetMapping(value=USER.AUTOCOMPLETE_REVIEWER_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteReviewerAjax(T2Users t2Users, HttpServletRequest req,
HttpServletResponse res, Model model) {
List<T2Users> list = userService.getReviwer();
return makeJsonResponseHeader(list);
}
@GetMapping(value=USER.AUTOCOMPLETE_CREATOR_DIVISION_AJAX)
public @ResponseBody ResponseEntity<Object> autoCompleteCreatorDivisionAjax(T2Users t2Users, HttpServletRequest req,
HttpServletResponse res, Model model) {
List<T2Users> list = userService.getAllUsersDivision();
return makeJsonResponseHeader(list);
}
@PostMapping(value=USER.CHANGE_PASSWORD)
public @ResponseBody ResponseEntity<Object> changePassword(
@RequestBody T2Users bean
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
Map<String, Object> resMap = new HashMap<String, Object>();
String userId = avoidNull(bean.getUserId(), loginUserName());
String userPw = avoidNull(bean.getPassword(), bean.getUserId());
T2Users userInfo = new T2Users();
try {
userInfo.setUserId(userId);
userInfo = userService.getUser(userInfo);
userInfo.setPassword(encodePassword(userPw)); // password encoding
userInfo.setModifier(loginUserName());
int updateCnt = userService.updateUsers(userInfo);
if (updateCnt == 1) {
resMap.put("resCd", "10");
} else {
resMap.put("resCd", "20");
resMap.put("resCd", "password change Failure.");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
resMap.put("resCd", "20");
resMap.put("resCd", "password change Failure.");
}
return makeJsonResponseHeader(resMap);
}
@PostMapping(value = USER.RESET_PASSWORD)
public @ResponseBody ResponseEntity<Object> resetPassword(
@RequestBody Map<String, String> params,
HttpServletRequest httpServletRequest) {
Map<String, Object> resMap = new HashMap<>();
T2Users targetUser = new T2Users();
String userId = params.getOrDefault("userId", "");
String email = params.getOrDefault("email", "");
targetUser.setUserId(userId);
T2Users foundUser = userService.getUser(targetUser);
if (foundUser == null || !foundUser.getEmail().equals(email)) {
resMap.put("resCd", 21);
resMap.put("resMsg", "Can't find matching user");
return makeJsonResponseHeader(resMap);
}
String generatedPassword = RandomStringUtils.randomAlphanumeric(10);
foundUser.setPassword(encodePassword(generatedPassword));
foundUser.setModifier(userId);
int updateCnt = userService.updateUsers(foundUser);
if (updateCnt != 1) {
resMap.put("resCd", "20");
resMap.put("resMsg", "fail to reset password");
return makeJsonResponseHeader(resMap);
}
String emailType = CoConstDef.CD_MAIL_TYPE_RESET_USER_PASSWORD;
CoMail mailBean = new CoMail(emailType);
List<Map<String, Object>> paramList = new ArrayList<>();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("userId", userId);
userInfo.put("afterPassword", generatedPassword);
userInfo.put("modifiedTime", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
userInfo.put("requestedIP", httpServletRequest.getRemoteAddr());
paramList.add(userInfo);
mailBean.setParamList(paramList);
mailBean.setParamUserId(userId);
mailBean.setToIds(new String[] { foundUser.getUserId() });
boolean isMailSendingSuccessful = CoMailManager.getInstance().sendMail(mailBean);
if (!isMailSendingSuccessful) {
resMap.put("resCd", "20");
resMap.put("resMsg", "fail to send email");
return makeJsonResponseHeader(resMap);
}
resMap.put("resCd", "10");
return makeJsonResponseHeader(resMap);
}
@PostMapping(value=USER.UPDATE_USERNAME_DIVISION)
public @ResponseBody ResponseEntity<Object> updateUserNameDivision(
@RequestBody Map<String, String> params
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
T2Users userInfo = new T2Users();
try {
params.put("USER_NAME", params.get("userName").trim());
params.put("DIVISION", params.get("division").trim());
if (params.get("password") != null) {
params.put("PASSWORD", params.get("password").trim());
}
T2CoAdminValidator validator = new T2CoAdminValidator();
T2CoValidationResult vr = validator.validate(params);
if (!vr.isValid()) {
return makeJsonResponseHeader(false, CommonFunction.makeValidMsgTohtml(vr.getValidMessageMap()), vr.getValidMessageMap());
}
userInfo.setUserId(loginUserName());
userInfo.setModifier(loginUserName());
userInfo.setUserName(params.get("USER_NAME"));
userInfo.setDivision(params.get("DIVISION"));
String passwd = params.get("PASSWORD");
if (!StringUtil.isEmpty(passwd)) {
userInfo.setPassword(encodePassword(passwd)); // password encoding
}
userService.updateUserNameDivision(userInfo);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, getMessage("msg.common.valid2"));
}
return makeJsonResponseHeader();
}
@PostMapping(value=USER.TOKEN_PROC)
public @ResponseBody ResponseEntity<Object> tokenProc(
@RequestBody HashMap<String, Object> map
, HttpServletRequest req
, HttpServletResponse res
, Model model
, @PathVariable String procType) throws Exception{
String mainData = (String) map.get("mainData");
boolean isSuccess = false;
// Proc token Data
Type collectionType = new TypeToken<T2Users>() {}.getType();
T2Users userData = new T2Users();
userData = (T2Users) fromJson(mainData, collectionType);
userData.setTokenType(procType);
isSuccess = userService.procToken(userData);
if (isSuccess) {
// email 발송
try {
String emailType = null;
switch(procType.toUpperCase()) {
case CoConstDef.CD_TOKEN_CREATE_TYPE:
emailType = CoConstDef.CD_MAIL_TOKEN_CREATE_TYPE;
break;
case CoConstDef.CD_TOKEN_DELETE_TYPE:
emailType = CoConstDef.CD_MAIL_TOKEN_DELETE_TYPE;
break;
default:
break;
}
if (!isEmpty(emailType)) {
CoMail mailBean = new CoMail(emailType);
mailBean.setParamUserId(userData.getUserId());
mailBean.setToIds(new String[] { userData.getUserId() });
mailBean.setCcIds(new String[] { loginUserName() });
CoMailManager.getInstance().sendMail(mailBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Map<String, Object> resMap = new HashMap<>();
resMap.put("isValid", isSuccess);
return makeJsonResponseHeader(resMap);
}
}
| 12,555 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
DownloadProcController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/DownloadProcController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.DOWNLOAD;
import oss.fosslight.domain.T2File;
import oss.fosslight.repository.FileMapper;
import oss.fosslight.service.FileService;
@Controller
public class DownloadProcController extends CoTopComponent {
@Autowired FileService fileService;
@Autowired FileMapper fileMapper;
@GetMapping(value=DOWNLOAD.SEQ_FNAME)
public ResponseEntity<FileSystemResource> downloadComponent (
@PathVariable("seq") final String seq,
@PathVariable("fName") final String fName,
HttpServletRequest req, HttpServletResponse res, Model model) throws IOException{
ResponseEntity<FileSystemResource> responseEntity = null;
T2File fileVo = new T2File();
fileVo.setFileSeq(seq);
fileVo = fileMapper.getFileInfo(fileVo);
if (fileVo == null){
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, Long.toString(0));
responseEntity = new ResponseEntity<FileSystemResource>(null, responseHeaders, HttpStatus.NOT_FOUND);
} else {
String origNm = fileVo.getOrigNm();
String logiNm = fileVo.getLogiNm();
String downName = "";
// 파일명이 같을 경우만 다운로드되도록 한다.
if (logiNm.equals(fName)){
//파일 인코딩
String browser = req.getHeader("User-Agent");
if (browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")){
downName = URLEncoder.encode(origNm,"UTF-8").replaceAll("\\+", "%20");
} else {
downName = new String(origNm.getBytes("UTF-8"), "ISO-8859-1");
}
String logiPath = fileVo.getLogiPath();
String fullLogiPath = null;
if (logiPath.substring(logiPath.length()-1).equals("/")){
fullLogiPath = fileVo.getLogiPath() + fileVo.getLogiNm();
} else {
fullLogiPath = fileVo.getLogiPath() + "/" + fileVo.getLogiNm();
}
java.io.File file = new java.io.File(fullLogiPath);
FileSystemResource fileSystemResource = new FileSystemResource(file);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + downName + ";filename*= UTF-8''" + downName);
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, Long.toString(fileSystemResource.contentLength()));
responseEntity = new ResponseEntity<FileSystemResource>(fileSystemResource, responseHeaders, HttpStatus.OK);
} else { // 파일명이 다를 경우 404를 리턴한다.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, Long.toString(0));
responseEntity = new ResponseEntity<FileSystemResource>(null, responseHeaders, HttpStatus.NOT_FOUND);
}
}
return responseEntity;
}
@GetMapping(value={DOWNLOAD.BATGUIREPORT_ID_CHECKSUM})
public ResponseEntity<FileSystemResource> downloadBatGuiReport (
@PathVariable("batId") final String batId,
@PathVariable("checkSum") final String checkSum,
HttpServletRequest req, HttpServletResponse res, Model model) throws IOException{
ResponseEntity<FileSystemResource> responseEntity = null;
String baseImageUrl = "http://" + req.getServerName();
if (req.getServerPort() != 80) {
baseImageUrl += ":" + Integer.toString(req.getServerPort());
}
baseImageUrl += "/imageView/guiReport/" + batId + "/";
// bat reposrt path
String fileName = checkSum + "-guireport";
String filePath = CommonFunction.emptyCheckProperty("vat.root.path", CommonFunction.getProperty("root.dir") + "/batsystem/");
filePath = filePath + "out/" + batId + "_dir" + "/reports/" + fileName + ".html";
File file = new File(filePath);
// 파일명이 같을 경우만 다운로드되도록 한다.
if (file.exists() && file.isFile()){
fileName+=".html";
String encodedFilename = URLEncoder.encode(fileName,"UTF-8").replace("+", "%20");
File tempFile = Paths.get(CommonFunction.emptyCheckProperty("image.temp.path", "/imagetemp")).resolve("BAT").resolve(batId).resolve(file.getName()).toFile();
try {
if (!tempFile.exists()) {
String content = FileUtils.readFileToString(file, "UTF-8");
content = content.replaceAll("img src=\"../images/", "img src=\""+baseImageUrl+"");
FileUtils.writeStringToFile(tempFile, content, "UTF-8");
}
} catch (IOException e) {
}
FileSystemResource fileSystemResource = new FileSystemResource(tempFile);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + encodedFilename + ";filename*= UTF-8''" + encodedFilename);
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, Long.toString(fileSystemResource.contentLength()));
responseEntity = new ResponseEntity<FileSystemResource>(fileSystemResource, responseHeaders, HttpStatus.OK);
} else { // 파일명이 다를 경우 404를 리턴한다.
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_LENGTH, Long.toString(0));
responseEntity = new ResponseEntity<FileSystemResource>(null, responseHeaders, HttpStatus.NOT_FOUND);
}
return responseEntity;
}
}
| 6,538 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
BinaryDataController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/BinaryDataController.java | package oss.fosslight.controller;
import java.lang.reflect.Type;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.common.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url;
import oss.fosslight.domain.BinaryData;
import oss.fosslight.service.BinaryDataService;
@RequestMapping("/binary")
@Controller
@Slf4j
public class BinaryDataController extends CoTopComponent {
// Service
@Autowired BinaryDataService binaryDataService;
/**
* Bianry DB
*/
@GetMapping(value="", produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
log.debug(" :: Start bat");
return Url.TILES_ROOT + "/binary/list";
}
/**
* Select Binary DB list
*/
@GetMapping(value="/listAjax")
public @ResponseBody ResponseEntity<Object> listAjax(
@ModelAttribute BinaryData vo
, HttpServletRequest req
, HttpServletResponse res
, Model model){
String page = req.getParameter("page");
String rows = req.getParameter("rows");
return makeJsonResponseHeader(binaryDataService.getBinaryList(page, rows , vo));
}
/**
* Change Binary DB data
* @param vo
* @param req
* @param res
* @param model
* @return
* @throws Exception
*/
@PostMapping(value="/modAjax")
public @ResponseBody ResponseEntity<Object> binaryMod (
@ModelAttribute BinaryData vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
boolean multiFlag = !isEmpty(vo.getParameter());
if(multiFlag) {
Type batType = new TypeToken<List<BinaryData>>(){}.getType();
List<BinaryData> batList = (List<BinaryData>) fromJson(vo.getParameter(), batType);
binaryDataService.setBinaryDataListModify(batList); // multi row 선택시 동작한 신규 service
}else {
binaryDataService.setBinaryDataModify(vo); // 기존 service
}
return makeJsonResponseHeader();
}
@GetMapping(value="/existBinaryName")
public @ResponseBody ResponseEntity<Object> existBinaryName (
@ModelAttribute BinaryData vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
return makeJsonResponseHeader(binaryDataService.getExistBinaryName(vo));
}
@GetMapping(value="/binarypopup")
public String binarypopup (
@ModelAttribute BinaryData vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
model.addAttribute("batInfo", vo);
return Url.TILES_ROOT + "/binary/binarypopup";
}
}
| 3,146 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ImageViewController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ImageViewController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.IMAGE_VIEW;
import oss.fosslight.domain.ImageView;
import oss.fosslight.domain.T2File;
import oss.fosslight.service.FileService;
@Controller
@Slf4j
public class ImageViewController extends CoTopComponent {
@Autowired FileService fileService;
@Resource(name="imageView") ImageView imageView;
@RequestMapping(value=IMAGE_VIEW.IMAGE)
private ImageView getImage(@PathVariable String imageName, ModelMap modelMap) {
T2File param = new T2File();
param.setLogiNm(imageName);
param.setGubn(CoConstDef.FILE_GUBUN_EDITOR_IMAGE);
modelMap.put("imageFile", fileService.selectFileInfoByLogiName(param));
return imageView;
}
@RequestMapping(value=IMAGE_VIEW.GUI_REPORT_ID_NM)
private ImageView getGuiReportImage(@PathVariable String batId, @PathVariable String imageName, ModelMap modelMap) {
String batPath = CommonFunction.emptyCheckProperty("vat.root.path", CommonFunction.getProperty("root.dir") + "/batsystem/");
String dirPath = Paths.get(batPath).resolve("out").resolve(batId+"_dir").resolve("images").toString();
Path reportImagePath = Paths.get(dirPath).resolve(imageName);
File reportImageFile = reportImagePath.toFile();
if (reportImageFile.exists()) {
T2File f = new T2File();
try {
f.setContentType(Files.probeContentType(reportImagePath));
f.setSize(Long.toString(reportImageFile.length()));
f.setLogiPath(dirPath);
f.setLogiNm(imageName);
modelMap.put("imageFile", f);
} catch (IOException e) {
log.error(e.getMessage());
return null;
}
} else {
return null;
}
return imageView;
}
}
| 2,427 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
HistoryController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/HistoryController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.HISTORY;
import oss.fosslight.domain.History;
import oss.fosslight.service.HistoryService;
@Controller
public class HistoryController extends CoTopComponent {
@Autowired HistoryService historyService;
@GetMapping(value=HISTORY.LIST, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return HISTORY.LIST_JSP;
}
@GetMapping(value=HISTORY.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
History history
, HttpServletRequest req
, HttpServletResponse res
, Model model){
history.setSortField(req.getParameter("sidx"));
history.setSortOrder(req.getParameter("sord"));
return makeJsonResponseHeader(historyService.getList(history));
}
@GetMapping(value=HISTORY.EDIT_IDX, produces = "text/html; charset=utf-8")
public String edit(@PathVariable String idx, HttpServletRequest req, HttpServletResponse res, Model model) throws Exception{
History history = new History(idx);
Map<String, Object> map = historyService.getAsToBeHistoryDataByGrid(history);
model.addAttribute("basicInfo", historyService.getData(history));
model.addAttribute("history", map);
model.addAttribute("historyJson", toJson(map));
return HISTORY.EDIT_JSP;
}
}
| 2,011 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
MainController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/MainController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.MAIN;
@Controller
public class MainController{
@GetMapping(value={MAIN.INDEX_EMPTY, MAIN.INDEX})
public String index(HttpServletRequest req, HttpServletResponse res, Model model, Principal principal, HttpSession session) {
model.addAttribute("dashboardFlag", CommonFunction.propertyFlagCheck("menu.dashboard.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("statisticsFlag", CommonFunction.propertyFlagCheck("menu.statistics.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("projectFlag", CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("partnerFlag", CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("batFlag", CommonFunction.propertyFlagCheck("menu.bat.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("binarydbFlag", CommonFunction.propertyFlagCheck("menu.binarydb.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("complianceStatusFlag", CommonFunction.propertyFlagCheck("menu.compliancestatus.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("externalLinkFlag", CommonFunction.propertyFlagCheck("menu.externallink.use.flag", CoConstDef.FLAG_YES));
model.addAttribute("checkFlag", CommonFunction.propertyFlagCheck("checkFlag", CoConstDef.FLAG_YES));
return MAIN.INDEX_JSP;
}
@RequestMapping(value= { CoConstDef.HEALTH_CHECK_URL }, produces=MediaType.TEXT_HTML_VALUE)
public void healthCheck( HttpServletRequest req, HttpServletResponse res ) throws IOException {
String ip = req.getHeader("X-FORWARDED-FOR");
if (ip == null) {
ip = req.getRemoteAddr();
}
PrintWriter pw = res.getWriter();
pw.write(" - Client IP : " + ip);
pw.close();
}
}
| 2,436 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VerificationController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/VerificationController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.VERIFICATION;
import oss.fosslight.domain.CoMail;
import oss.fosslight.domain.CoMailManager;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.File;
import oss.fosslight.domain.History;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.repository.CodeMapper;
import oss.fosslight.repository.VerificationMapper;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.VerificationService;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Controller
@Slf4j
public class VerificationController extends CoTopComponent {
@Autowired ProjectService projectService;
@Autowired CommentService commentService;
@Autowired VerificationService verificationService;
@Autowired FileService fileService;
@Autowired HistoryService historyService;
@Autowired VerificationMapper verificationMapper;
@Autowired CodeMapper codeMapper;
@GetMapping(value = VERIFICATION.PAGE_ID, produces = "text/html; charset=utf-8")
public String list(@PathVariable String prjId, HttpServletRequest req, HttpServletResponse res, Model model) {
log.info("URI: "+ "/project/verification/"+prjId);
Project project = new Project();
project.setPrjId(prjId);
Project projectMaster = projectService.getProjectDetail(project);
projectMaster.setVulDocInfo(CommonFunction.getMessageForVulDOC(req, "info"));
projectMaster.setVulDocInst(CommonFunction.getMessageForVulDOC(req, "inst").replace("<br />", " "));
if (!StringUtil.isEmpty(projectMaster.getCreator())){
projectMaster.setPrjDivision(projectService.getDivision(projectMaster));
}
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_USER);
comHisBean.setReferenceId(projectMaster.getPrjId());
projectMaster.setUserComment(commentService.getUserComment(comHisBean));
//프로젝트 정보
model.addAttribute("project", projectMaster);
OssNotice _noticeInfo = projectService.setCheckNotice(projectMaster);
if (_noticeInfo != null) {
// Notice Type: Accompanied with source code인 경우 Default Company Name, Email 세팅
model.addAttribute("ossNotice", _noticeInfo);
}
List<OssComponents> list = verificationService.getVerifyOssList(projectMaster);
list = verificationService.setMergeGridData(list);
List<LicenseMaster> userGuideLicenseList = new ArrayList<>();
List<String> duplLicenseCheckList = new ArrayList<>(); // 중목제거용
// 사용중인 라이선스에 user guide가 설정되어 있는 경우 체크
if (list != null && !list.isEmpty()) {
for (OssComponents bean : list) {
// multi license의 경우 콤마 구분으로 반환됨
if (!isEmpty(bean.getLicenseName())) {
LicenseMaster licenseBean;
for (String license : bean.getLicenseName().split(",", -1)) {
licenseBean = CoCodeManager.LICENSE_INFO_UPPER.get(license.toUpperCase());
if (licenseBean != null && !isEmptyWithLineSeparator(licenseBean.getDescription())
&& !duplLicenseCheckList.contains(licenseBean.getLicenseId())
&& CoConstDef.FLAG_YES.equals(avoidNull(licenseBean.getObligationDisclosingSrcYn()))) {
userGuideLicenseList.add(licenseBean);
duplLicenseCheckList.add(licenseBean.getLicenseId());
}
}
}
}
}
List<File> files = new ArrayList<File>();
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId()));
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId2()));
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId3()));
if (!isEmpty(projectMaster.getPackageVulDocFileId())) {
File file = verificationMapper.selectVerificationVulDocFile(projectMaster.getPackageVulDocFileId());
model.addAttribute("vulDocFile", file);
}
model.addAttribute("verify", toJson(verificationService.getVerificationOne(project)));
model.addAttribute("ossList", toJson(list));
model.addAttribute("files", files);
model.addAttribute("userGuideLicenseList", userGuideLicenseList);
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
return VERIFICATION.PAGE_JSP;
}
@GetMapping(value = VERIFICATION.PAGE_DIV_ID, produces = "text/html; charset=utf-8")
public String list2(@PathVariable String prjId, @PathVariable String initDiv, HttpServletRequest req, HttpServletResponse res, Model model) {
log.info("URI: "+ "/project/verification/"+prjId);
Project project = new Project();
project.setPrjId(prjId);
Project projectMaster = projectService.getProjectDetail(project);
projectMaster.setVulDocInfo(CommonFunction.getMessageForVulDOC(req, "info"));
projectMaster.setVulDocInst(CommonFunction.getMessageForVulDOC(req, "inst"));
if (!StringUtil.isEmpty(projectMaster.getCreator())){
projectMaster.setPrjDivision(projectService.getDivision(projectMaster));
}
CommentsHistory comHisBean = new CommentsHistory();
comHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_USER);
comHisBean.setReferenceId(projectMaster.getPrjId());
projectMaster.setUserComment(commentService.getUserComment(comHisBean));
//프로젝트 정보
model.addAttribute("project", projectMaster);
OssNotice _noticeInfo = projectService.setCheckNotice(projectMaster);
if (_noticeInfo != null && CoConstDef.FLAG_NO.equals(projectMaster.getUseCustomNoticeYn())) {
// Notice Type: Accompanied with source code인 경우 Default Company Name, Email 세팅
model.addAttribute("ossNotice", _noticeInfo);
}
List<OssComponents> list = verificationService.getVerifyOssList(projectMaster);
list = verificationService.setMergeGridData(list);
List<LicenseMaster> userGuideLicenseList = new ArrayList<>();
// 중목제거용
List<String> duplLicenseCheckList = new ArrayList<>();
// 사용중인 라이선스에 user guide가 설정되어 있는 경우 체크
if (list != null && !list.isEmpty()) {
for (OssComponents bean : list) {
// multi license의 경우 콤마 구분으로 반환됨
if (!isEmpty(bean.getLicenseName())) {
LicenseMaster licenseBean;
for (String license : bean.getLicenseName().split(",", -1)) {
licenseBean = CoCodeManager.LICENSE_INFO_UPPER.get(license.toUpperCase());
if (licenseBean != null && !isEmptyWithLineSeparator(licenseBean.getDescription())
&& !duplLicenseCheckList.contains(licenseBean.getLicenseId())) {
userGuideLicenseList.add(licenseBean);
duplLicenseCheckList.add(licenseBean.getLicenseId());
}
}
}
}
}
List<File> files = new ArrayList<File>();
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId()));
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId2()));
files.add(verificationMapper.selectVerificationFile(projectMaster.getPackageFileId3()));
if (!isEmpty(projectMaster.getPackageVulDocFileId())) {
File file = verificationMapper.selectVerificationVulDocFile(projectMaster.getPackageVulDocFileId());
model.addAttribute("vulDocFile", file);
}
model.addAttribute("verify", toJson(verificationService.getVerificationOne(project)));
model.addAttribute("ossList", toJson(list));
model.addAttribute("files", files);
model.addAttribute("initDiv", initDiv);
model.addAttribute("userGuideLicenseList", userGuideLicenseList);
model.addAttribute("distributionFlag", CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES));
return VERIFICATION.PAGE_JSP;
}
@ResponseBody
@PostMapping(value=VERIFICATION.REGIST_FILE)
public String registFile(T2File file, MultipartHttpServletRequest req, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
log.info("URI: "+ "/project/verification/registFile");
//파일 등록
List<UploadFile> list = new ArrayList<UploadFile>();
ArrayList<Object> resultList = new ArrayList<Object>();
String fileId = StringUtil.isEmpty(req.getParameter("fileId")) ? null : req.getParameter("fileId");
String prjId = req.getParameter("prjId");
String filePath = CommonFunction.emptyCheckProperty("packaging.path", "/upload/packaging") + "/" + prjId;
Map<String, MultipartFile> fileMap = req.getFileMap();
String fileExtension = StringUtils.getFilenameExtension(fileMap.get("myfile").getOriginalFilename());
String fileSeq = StringUtil.isEmpty(req.getParameter("fileSeq")) ? null : req.getParameter("fileSeq");
//파일 등록
if (req.getContentType() != null && req.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
file.setCreator(loginUserName());
//파일 확장자 체크
String codeExp = !fileSeq.equals("4") ? codeMapper.getCodeDetail("120", "16").getCdDtlExp() : codeMapper.getCodeDetail("120", "40").getCdDtlExp();
String[] exts = codeExp.split(",");
boolean fileExtCheck = false;
for (String s : exts) {
if (s.equals(fileExtension)) {
fileExtCheck = true;
}
}
if(!fileExtCheck) {
resultList.add("UNSUPPORTED_FILE");
String msg = getMessage("msg.project.packaging.upload.fileextension" , new String[]{codeExp});
resultList.add(msg);
return toJson(resultList);
}
list = fileService.uploadFile(req, file, null, fileId, true, filePath);
}
//결과값 resultList에 담기
resultList.add(list);
// 20210625_fileUpload 시 projectMaster table save_START
String registFileId = list.get(0).getRegistSeq();
verificationService.setUploadFileSave(prjId, fileSeq, registFileId);
// 20210625_fileUpload 시 projectMaster table save_END
return toJson(resultList);
}
@PostMapping(value=VERIFICATION.UPLOAD_VERIFICATION, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public @ResponseBody ResponseEntity<Object> uploadVerification(File file, MultipartHttpServletRequest req, HttpServletRequest request, HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/uploadVerification");
Project projectMaster = new Project();
projectMaster.setPrjId(req.getParameter("prjId"));
List<OssComponents> list = verificationService.getVerifyOssList(projectMaster);
list = verificationService.setMergeGridData(list);
//엑셀 분석
List<OssComponents> verificationList = ExcelUtil.getVerificationList(req, list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
if (verificationList == null) {
return makeJsonResponseHeader(false, "");
}
return makeJsonResponseHeader(true, "", verificationList);
}
@SuppressWarnings("unchecked")
@ResponseBody
@PostMapping(value=VERIFICATION.VERIFY)
public String procVerify(@RequestBody Map<Object, Object> map, T2File file, Project project,
HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
log.info("URI: "+ "/project/verification/verify");
Map<String, Object> resMap = null;
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
List<String> fileSeqs = (List<String>) map.get("fileSeqs");
String prjId = (String) map.get("prjId");
try {
log.info("start verify prjId:" + prjId + ", fileSeqs:" + fileSeqs.toString());
String packagingComment = fileService.setClearFiles(map);
map.put("packagingComment", packagingComment);
boolean isChangedPackageFile = verificationService.getChangedPackageFile(prjId, fileSeqs);
int seq = 1;
for (String fileSeq : fileSeqs){
map.put("fileSeq", fileSeq);
map.put("packagingFileIdx", seq++);
map.put("isChangedPackageFile", isChangedPackageFile);
result.add(verificationService.processVerification(map, file, project));
}
resMap = result.get(0);
if (fileSeqs.size() > 1){
Map<String, Object> fileCountsMap = new HashMap<>();
List<String> verifyValidChkList = new ArrayList<>();
for (Map<String, Object> resultMap : result) {
if (resultMap.containsKey("fileCounts")) {
Map<String, Object> fileCountMap = (Map<String, Object>) resultMap.get("fileCounts");
for (String key : fileCountMap.keySet()) {
if (fileCountsMap.containsKey(key)) {
fileCountsMap.replace(key, fileCountMap.get(key));
} else {
fileCountsMap.put(key, fileCountMap.get(key));
}
}
}
}
for (Map<String, Object> resultMap : result) {
if (resultMap.containsKey("verifyValid")) {
List<String> verifyValidList = (List<String>) resultMap.get("verifyValid");
for (String verifyValid : verifyValidList) {
if (!fileCountsMap.containsKey(verifyValid)) {
verifyValidChkList.add(verifyValid);
}
}
}
}
verifyValidChkList = verifyValidChkList.stream().distinct().collect(Collectors.toList());
resMap.put("verifyValid", verifyValidChkList);
resMap.put("fileCounts", fileCountsMap);
}
verificationService.updateVerifyFileCount((ArrayList<String>) resMap.get("verifyValid"));
verificationService.updateVerifyFileCount((HashMap<String,Object>) resMap.get("fileCounts"));
} catch (Exception e) {
log.error("failed to verify project id:" + prjId, e);
resMap = new HashMap<String, Object>();
resMap.put("resCd", "99");
resMap.put("resMsg", "Error : " + ( (StringUtil.isEmpty(e.getMessage()) || "null".equalsIgnoreCase(e.getMessage())) ? getMessage("msg.common.valid2") : e.getMessage()));
}
return toJson(resMap);
}
@PostMapping(value=VERIFICATION.SAVE_PATH, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public @ResponseBody ResponseEntity<Object> savePath(@RequestBody Map<Object, Object> map, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
log.info("URI: "+ "/project/verification/savePath");
try {
verificationService.savePath(map);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader();
}
@PostMapping(value = VERIFICATION.NOTICE_AJAX)
public @ResponseBody ResponseEntity<Object> getNoticeHtml(HttpServletRequest req,HttpServletResponse res, Model model, //
@RequestParam(value="confirm", defaultValue="")String confirm, //
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
@RequestParam(value="allowDownloadNoticeHTMLYn", defaultValue="")String allowDownloadNoticeHTMLYn, //
@RequestParam(value="allowDownloadNoticeTextYn", defaultValue="")String allowDownloadNoticeTextYn, //
@RequestParam(value="allowDownloadSimpleHTMLYn", defaultValue="")String allowDownloadSimpleHTMLYn, //
@RequestParam(value="allowDownloadSimpleTextYn", defaultValue="")String allowDownloadSimpleTextYn, //
@RequestParam(value="allowDownloadSPDXSheetYn", defaultValue="")String allowDownloadSPDXSheetYn, //
@RequestParam(value="allowDownloadSPDXRdfYn", defaultValue="")String allowDownloadSPDXRdfYn, //
@RequestParam(value="allowDownloadSPDXTagYn", defaultValue="")String allowDownloadSPDXTagYn, //
@RequestParam(value="allowDownloadSPDXJsonYn", defaultValue="")String allowDownloadSPDXJsonYn, //
@RequestParam(value="allowDownloadSPDXYamlYn", defaultValue="")String allowDownloadSPDXYamlYn, //
@RequestParam(value="allowDownloadCDXJsonYn", defaultValue="")String allowDownloadCDXJsonYn, //
@RequestParam(value="allowDownloadCDXXmlYn", defaultValue="")String allowDownloadCDXXmlYn, //
OssNotice ossNotice //
) throws IOException {
log.info("URI: "+ "/project/verification/noticeAjax");
log.debug("PARAM: "+ "confirm="+confirm);
log.debug("PARAM: "+ "prjId="+ossNotice.getPrjId());
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
String resultHtml = "";
try {
ossNotice.setDomain(CommonFunction.getDomain(req)); // domain Setting
Project prjMasterInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String noticeFileId = prjMasterInfo.getNoticeFileId();
log.debug("PARAM: "+ "noticeFileId="+noticeFileId);
if ("conf".equals(confirm)){
boolean ignoreMailSend = false;
String userComment = ossNotice.getUserComment();
//파일 만들기
if (isEmpty(noticeFileId) || !CoConstDef.FLAG_YES.equals(useCustomNoticeYn)) {
if (!verificationService.getNoticeHtmlFile(ossNotice)) {
return makeJsonResponseHeader(false, getMessage("msg.common.valid2"));
}
}
// reject 이후에 다시 confirm 하는 경우 이전의 package 파일 삭제 처리 필요 여부를 위해
// source code obligation 체크를 한다.
boolean needResetPackageFile = false;
{
Project projectMaster = projectService.getProjectBasicInfo(ossNotice.getPrjId());
if (!isEmpty(projectMaster.getPackageFileId())) {
List<OssComponents> list = verificationService.getVerifyOssList(projectMaster);
needResetPackageFile = list.isEmpty();
}
}
Project prjInfo = null;
//프로젝트 상태 변경
Project project = new Project();
project.setPrjId(ossNotice.getPrjId());
//다운로드 허용 플래그
project.setAllowDownloadNoticeHTMLYn(allowDownloadNoticeHTMLYn);
project.setAllowDownloadNoticeTextYn(allowDownloadNoticeTextYn);
project.setAllowDownloadSimpleHTMLYn(allowDownloadSimpleHTMLYn);
project.setAllowDownloadSimpleTextYn(allowDownloadSimpleTextYn);
project.setAllowDownloadSPDXSheetYn(allowDownloadSPDXSheetYn);
project.setAllowDownloadSPDXRdfYn(allowDownloadSPDXRdfYn);
project.setAllowDownloadSPDXTagYn(allowDownloadSPDXTagYn);
project.setAllowDownloadSPDXJsonYn(allowDownloadSPDXJsonYn);
project.setAllowDownloadSPDXYamlYn(allowDownloadSPDXYamlYn);
project.setAllowDownloadCDXJsonYn(allowDownloadCDXJsonYn);
project.setAllowDownloadCDXXmlYn(allowDownloadCDXXmlYn);
project.setVerificationStatus(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM);
// 프로젝트 기본정보의 distribution type이 verify까지만인 경우, distribute status를 N/A 처리한다.
{
prjInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String distributionType = codeMapper.getCodeDetail(CoConstDef.CD_DISTRIBUTION_TYPE, prjInfo.getDistributionType()).getCdDtlExp();
if ("T".equalsIgnoreCase(avoidNull(distributionType))
|| (CoConstDef.FLAG_NO.equalsIgnoreCase(avoidNull(distributionType)) && verificationService.checkNetworkServer(ossNotice.getPrjId()))
|| CoConstDef.CD_DTL_DISTRIBUTE_NA.equals(prjInfo.getDistributeTarget()) // 배포사이트 사용안함으로 설정한 경우
) {
project.setDestributionStatus(CoConstDef.CD_DTL_DISTRIBUTE_STATUS_NA);
ignoreMailSend = true;
} else if (!CoConstDef.CD_DTL_DISTRIBUTE_NA.equals(prjInfo.getDistributeTarget())
&& CoConstDef.CD_DTL_DISTRIBUTE_STATUS_NA.equals(prjInfo.getDestributionStatus())) {
project.setResetDistributionStatus(CoConstDef.FLAG_YES);
}
if (!isEmpty(prjInfo.getDestributionStatus())
&& CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM.equals(confirm.toUpperCase())) {
project.setChangedNoticeYn(CoConstDef.FLAG_YES);
}
}
project.setModifier(project.getLoginUserName());
// 기존에 등록한 package file의 삭제
if (needResetPackageFile) {
project.setNeedPackageFileReset(CoConstDef.FLAG_YES);
}
verificationService.updateStatusWithConfirm(project, ossNotice, false);
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
userComment += verificationService.changePackageFileNameCombine(ossNotice.getPrjId());
try {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(project.getPrjId());
commHisBean.setContents(userComment);
commHisBean.setStatus(CoCodeManager.getCodeExpString(CoConstDef.CD_IDENTIFICATION_STATUS, CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM));
commentService.registComment(commHisBean, false);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (prjInfo != null) {
try {
String mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_CONF;
String mailContentCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_CONF;
if (ignoreMailSend) {
mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_COMFIRMED_ONLY;
mailContentCode = mailTemplateCode;
} else if (CoConstDef.FLAG_YES.equals(prjInfo.getAndroidFlag())) {
mailTemplateCode = CoConstDef.CD_MAIL_TYPE_PROJECT_PACKAGING_COMFIRMED_ONLY;
}
CoMail mailBean = new CoMail(mailTemplateCode);
mailBean.setParamPrjId(ossNotice.getPrjId());
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, mailContentCode));
userComment = avoidNull(userComment) + "<br />" + _tempComment;
if (!isEmpty(userComment)) {
mailBean.setComment(userComment);
}
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else { // preview 인 경우
// 저장된 고지문구가 없을 경우
if (isEmpty(noticeFileId) || !CoConstDef.FLAG_YES.equals(useCustomNoticeYn)) {
resultHtml = verificationService.getNoticeHtml(ossNotice);
} else { // 저장된 고지문구가 있을 경우
T2File fileInfo = fileService.selectFileInfo(noticeFileId);
resultHtml = CommonFunction.getStringFromFile(fileInfo.getLogiPath() + "/" + fileInfo.getLogiNm());
// 파일을 못찾을 경우 예외처리
if (isEmpty(resultHtml)) {
resultHtml = verificationService.getNoticeHtml(ossNotice);
}
}
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(true, null, resultHtml);
}
@PostMapping(value = VERIFICATION.REVIEW_REPORT_AJAX)
public @ResponseBody ResponseEntity<Object> getReviewReportPdf(HttpServletRequest req,HttpServletResponse res, Model model,
@RequestParam(value="prjId") String prjId
) throws IOException {
log.info("URI: "+ "/project/verification/reportAjax");
log.debug("PARAM: "+ "prjId="+prjId);
String resultHtml = "";
try {
// create review file
if (!verificationService.getReviewReportPdfFile(prjId)) {
return makeJsonResponseHeader(false, getMessage("msg.common.valid2"));
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(true, null, resultHtml);
}
@ResponseBody
@GetMapping(value = VERIFICATION.DOWNLOAD_FILE, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> downloadFile (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/downloadFile");
String prjId = req.getParameter("prjId");
String fileName = req.getParameter("fileNm");
String filePath = CommonFunction.emptyCheckProperty("verify.output.path", "/verify")+"/"+prjId+"/"+fileName;
return noticeToResponseEntity(filePath, fileName);
}
@ResponseBody
@PostMapping(value=VERIFICATION.WGET_URL, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public String wgetUrl(@RequestBody Map<Object, Object> map, T2File file, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
log.info("URI: "+ "/project/verification/wgetUrl");
//파일 등록
List<UploadFile> list = new ArrayList<UploadFile>();
ArrayList<Object> resultList = new ArrayList<Object>();
String fileId = "";
file.setCreator(loginUserName());
map.put("filePath", "");
if (StringUtil.isEmpty(fileId)){
list = fileService.uploadWgetFile(request, file, map, false);
}
log.debug("WgetResult ==>"+list.get(0).getWgetResult());
//결과값 resultList에 담기
resultList.add(list);
return toJson(resultList);
}
@SuppressWarnings("unchecked")
@PostMapping(value=VERIFICATION.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> registVerify(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
@RequestParam(value="allowDownloadNoticeHTMLYn", defaultValue="")String allowDownloadNoticeHTMLYn, //
@RequestParam(value="allowDownloadNoticeTextYn", defaultValue="")String allowDownloadNoticeTextYn, //
@RequestParam(value="allowDownloadSimpleHTMLYn", defaultValue="")String allowDownloadSimpleHTMLYn, //
@RequestParam(value="allowDownloadSimpleTextYn", defaultValue="")String allowDownloadSimpleTextYn, //
@RequestParam(value="allowDownloadSPDXSheetYn", defaultValue="")String allowDownloadSPDXSheetYn, //
@RequestParam(value="allowDownloadSPDXRdfYn", defaultValue="")String allowDownloadSPDXRdfYn, //
@RequestParam(value="allowDownloadSPDXTagYn", defaultValue="")String allowDownloadSPDXTagYn, //
@RequestParam(value="allowDownloadSPDXJsonYn", defaultValue="")String allowDownloadSPDXJsonYn, //
@RequestParam(value="allowDownloadSPDXYamlYn", defaultValue="")String allowDownloadSPDXYamlYn, //
@RequestParam(value="allowDownloadCDXJsonYn", defaultValue="")String allowDownloadCDXJsonYn, //
@RequestParam(value="allowDownloadCDXXmlYn", defaultValue="")String allowDownloadCDXXmlYn, //
HttpServletResponse res, Model model) throws Exception {
log.info("URI: "+ "/project/verification/saveAjax");
T2CoValidationResult vResult = null;
/*Json String -> Json Object*/
String jsonString = ossNotice.getPackageJson();
Type collectionType = new TypeToken<List<OssComponents>>(){}.getType();
List<OssComponents> list = (List<OssComponents>) fromJson(jsonString, collectionType);
ossNotice.setOssComponents(list);
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_VERIFIY);
Map<String, String> reqMap = new HashMap<>();
Map<String, String> keyPreMap = new HashMap<>();
keyPreMap.put("COMPANY_NAME_FULL" , "PACKAGING");
keyPreMap.put("COMPANY_NAME_SHORT" , "PACKAGING");
keyPreMap.put("DISTRIBUTION_SITE_URL" , "PACKAGING");
keyPreMap.put("EMAIL" , "PACKAGING");
keyPreMap.put("USE_COMPANY_NAME_TITLE" , "PACKAGING");
keyPreMap.put("DISTRIBUTED_OTHER_COMPANY" , "PACKAGING");
keyPreMap.put("MERGED_OTHER_OSS_NOTICE" , "PACKAGING");
keyPreMap.put("ACCOMPANIED_SOURCE_CODE" , "PACKAGING");
vResult = pv.validateRequest(reqMap, req, keyPreMap);
if (!vResult.isValid()){
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
verificationService.registOssNotice(ossNotice);
Project project = new Project();
project.setPrjId(ossNotice.getPrjId());
//다운로드 허용 플래그
project.setAllowDownloadNoticeHTMLYn(allowDownloadNoticeHTMLYn); // default
// notice 수정시에만 변경값을 저장, 수정안한 defualt에는 allowDownloadNoticeHTMLYn만 값 입력
project.setAllowDownloadNoticeTextYn(CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadNoticeTextYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSimpleHTMLYn(CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSimpleHTMLYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSimpleTextYn(CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSimpleTextYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSPDXSheetYn( CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSPDXSheetYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSPDXRdfYn( CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSPDXRdfYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSPDXTagYn( CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSPDXTagYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSPDXJsonYn( CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSPDXJsonYn : CoConstDef.FLAG_NO);
project.setAllowDownloadSPDXYamlYn( CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadSPDXYamlYn : CoConstDef.FLAG_NO);
project.setAllowDownloadCDXJsonYn(CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadCDXJsonYn : CoConstDef.FLAG_NO);
project.setAllowDownloadCDXXmlYn(CoConstDef.FLAG_YES.equals(ossNotice.getEditNoticeYn()) ? allowDownloadCDXXmlYn : CoConstDef.FLAG_NO);
verificationService.updateProjectAllowDownloadBitFlag(project);
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
@PostMapping(value = VERIFICATION.SAVE_NOTICE_AJAX)
public @ResponseBody ResponseEntity<Object> saveNoticeHtml(HttpServletRequest req,HttpServletResponse res, Model model, //
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
@RequestParam(value="noticeHtml", defaultValue="")String noticeHtml, //
OssNotice ossNotice //
) throws IOException {
log.info("URI: "+ "/project/verification/saveNoticeAjax");
log.debug("PARAM: "+ "prjId="+ossNotice.getPrjId());
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
if (!verificationService.getNoticeHtmlFile(ossNotice, noticeHtml) || !CoConstDef.FLAG_YES.equals(useCustomNoticeYn)) {
return makeJsonResponseHeader(false, "Notice Registration Failed");
}
return makeJsonResponseHeader();
}
@PostMapping(value = VERIFICATION.MAKE_NOTICE_PREVIEW)
public @ResponseBody ResponseEntity<Object> makeNoticePreview(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
log.info("URI: "+ "/project/verification/makeNoticePreview");
String downloadId = null;
ossNotice.setFileType("html");
try {
Project prjMasterInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String noticeFileId = prjMasterInfo.getNoticeFileId();
log.debug("PARAM: "+ "noticeFileId="+noticeFileId);
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
if (isEmpty(noticeFileId)) {
downloadId = verificationService.getNoticeHtmlFileForPreview(ossNotice);
} else {
downloadId = noticeFileId;
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@ResponseBody
@GetMapping(value = VERIFICATION.DOWNLOAD_NOTICE_PREVIEW, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> downloadNoticePreview (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/downloadNoticePreview");
T2File fileInfo = fileService.selectFileInfo(req.getParameter("id"));
return noticeToResponseEntity(fileInfo.getLogiPath() + "/" + fileInfo.getLogiNm(), fileInfo.getOrigNm());
}
@PostMapping(value = VERIFICATION.MAKE_NOTICE_TEXT)
public @ResponseBody ResponseEntity<Object> makeNoticeText(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
log.info("URI: "+ "/project/verification/makeNoticeText");
String downloadId = null;
ossNotice.setFileType("text");
try {
Project prjMasterInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String noticeFileId = prjMasterInfo.getNoticeFileId();
log.debug("PARAM: "+ "noticeFileId="+noticeFileId);
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
if (!isEmpty(prjMasterInfo.getNoticeTextFileId())) {
downloadId = prjMasterInfo.getNoticeTextFileId();
} else {
downloadId = verificationService.getNoticeTextFileForPreview(ossNotice);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value = VERIFICATION.MAKE_NOTICE_SIMPLE)
public @ResponseBody ResponseEntity<Object> makeNoticeSimple(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
log.info("URI: "+ "/project/verification/makeNoticeSimple");
String downloadId = null;
ossNotice.setFileType("html");
ossNotice.setSimpleNoticeFlag(CoConstDef.FLAG_YES); // simple templete
ossNotice.setDomain(CommonFunction.getDomain(req)); // domain Setting
try {
Project prjMasterInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String noticeFileId = prjMasterInfo.getNoticeFileId();
log.debug("PARAM: "+ "noticeFileId="+noticeFileId);
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
if (!isEmpty(prjMasterInfo.getSimpleHtmlFileId())) {
downloadId = prjMasterInfo.getSimpleHtmlFileId();
} else {
downloadId = verificationService.getNoticeTextFileForPreview(ossNotice);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@PostMapping(value = VERIFICATION.MAKE_NOTICE_TEXT_SIMPLE)
public @ResponseBody ResponseEntity<Object> makeNoticeTextSimple(OssNotice ossNotice, HttpServletRequest req,
@RequestParam(value="useCustomNoticeYn", defaultValue="")String useCustomNoticeYn, //
HttpServletResponse res, Model model) throws IOException {
log.info("URI: "+ "/project/verification/makeNoticeTextSimple");
String downloadId = null;
ossNotice.setFileType("text");
ossNotice.setSimpleNoticeFlag(CoConstDef.FLAG_YES); // simple templete
try {
Project prjMasterInfo = projectService.getProjectBasicInfo(ossNotice.getPrjId());
String noticeFileId = prjMasterInfo.getNoticeFileId();
log.debug("PARAM: "+ "noticeFileId="+noticeFileId);
log.debug("PARAM: "+ "useCustomNoticeYn="+useCustomNoticeYn);
if (!isEmpty(prjMasterInfo.getSimpleTextFileId())) {
downloadId = prjMasterInfo.getSimpleTextFileId();
} else {
downloadId = verificationService.getNoticeTextFileForPreview(ossNotice);
}
} catch (Exception e) {
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@GetMapping(value = VERIFICATION.REUSE_PROJECT_SEARCH)
public @ResponseBody ResponseEntity<Object> reuseProjectSearch(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
project.setCurPage(page);
project.setPageListSize(rows);
project.setSortField(sidx);
project.setSortOrder(sord);
Map<String, Object> map = verificationService.getReuseProject(project);
return makeJsonResponseHeader(map);
}
@GetMapping(value = VERIFICATION.REUSE_PROJECT_PACKAGING_SEARCH)
public @ResponseBody ResponseEntity<Object> reuseProjectPackagingSearch(Project project, HttpServletRequest req,
HttpServletResponse res, Model model) {
Map<String, Object> map = verificationService.getReuseProjectPackagingFile(project);
return makeJsonResponseHeader(map);
}
@PostMapping(value=VERIFICATION.REUSE_PACKAGING_FILE, produces = "text/html; charset=utf-8")
public @ResponseBody ResponseEntity<Object> reusePackagingFile(@RequestBody HashMap<String, Object> map, HttpServletRequest request,
HttpServletResponse res, Model model) throws Exception {
log.info("URI: "+ "/project/verification/reusePackagingFile");
Map<String, Object> resultMap = new HashMap<String, Object>();
String refFileSeq = (String) map.get("refFileSeq");
List<UploadFile> file = fileService.setReusePackagingFile(refFileSeq);
map.put("fileSeq", file.get(0).getRegistSeq());
boolean result = verificationService.setReusePackagingFile(map);
if (result) {
resultMap.put("file", file);
return makeJsonResponseHeader(resultMap);
} else {
resultMap.put("file", "false");
return makeJsonResponseHeader(map);
}
}
@ResponseBody
@GetMapping(value = VERIFICATION.DOWNLOAD_PACKAGE, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> downloadPackage(
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/downloadPackage");
ResponseEntity<FileSystemResource> result = null;
String prjId = req.getParameter("prjId");
try {
result = verificationService.getPackage(prjId, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}
@ResponseBody
@GetMapping(value = {VERIFICATION.DOWNLOAD_PACKAGING_MULTI})
public ResponseEntity<FileSystemResource> downloadPackageMulti(
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/downloadPackage");
ResponseEntity<FileSystemResource> result = null;
String prjId = req.getParameter("prjId");
String fileIdx = req.getParameter("fileIdx");
try {
result = verificationService.getPackageMulti(prjId, CommonFunction.emptyCheckProperty("upload.path", "/upload"), fileIdx);
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}
@ResponseBody
@GetMapping(value = VERIFICATION.DOWNLOAD_NOTICE, produces = {
MimeTypeUtils.TEXT_HTML_VALUE+"; charset=utf-8",
MimeTypeUtils.APPLICATION_JSON_VALUE+"; charset=utf-8"})
public ResponseEntity<FileSystemResource> downloadNotice(
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
log.info("URI: "+ "/project/verification/downloadNotice");
ResponseEntity<FileSystemResource> result = null;
String prjId = req.getParameter("prjId");
result = verificationService.getNotice(prjId, CommonFunction.emptyCheckProperty("notice.path", "/notice"));
return result;
}
@ResponseBody
@GetMapping(value = VERIFICATION.DOWNLOAD_REVIEW_REPORT)
public ResponseEntity<FileSystemResource> downloadReviewReport(
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception {
log.info("URI: " + "/project/verification/downloadReviewReport");
ResponseEntity<FileSystemResource> result = null;
String prjId = req.getParameter("prjId");
result = verificationService.getReviewReport(prjId, CommonFunction.emptyCheckProperty("reviewReport.path", "/reviewReport"));
return result;
}
@PostMapping(value=VERIFICATION.SEND_COMMENT)
public @ResponseBody ResponseEntity<Object> sendComment(
@ModelAttribute CommentsHistory commentsHistory
, HttpServletRequest req
, HttpServletResponse res
, Model model){
log.info("URI: "+ "/project/verification/sendComment");
T2CoValidationResult vResult = null;
try{
//validation check
vResult = validate(req);
}catch(Exception e){
log.error(e.getMessage());
}
if (!vResult.isValid()){
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
try{
commentService.deleteComment(commentsHistory);
commentsHistory.setCommId("");
commentService.registComment(commentsHistory);
verificationMapper.deleteComment(commentsHistory);
} catch (Exception e){
log.error(e.getMessage());
}
return makeJsonResponseHeader(vResult.getValidMessageMap());
}
@PostMapping(value=VERIFICATION.DELETE_FILE)
public @ResponseBody ResponseEntity<Object> deleteFile (@RequestBody Map<Object, Object> map, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
log.info("URI: "+ "/project/verification/deleteFile");
try {
verificationService.deleteFile(map);
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader();
}
}
| 44,036 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
BinaryDataHistoryController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/BinaryDataHistoryController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.BINARY_DATA_HISTORY;
import oss.fosslight.domain.BinaryAnalysisResult;
import oss.fosslight.service.BinaryDataHistoryService;
@Controller
public class BinaryDataHistoryController extends CoTopComponent {
@Autowired BinaryDataHistoryService binaryDataHistoryService;
@GetMapping(value=BINARY_DATA_HISTORY.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return BINARY_DATA_HISTORY.PAGE_JSP;
}
@GetMapping(value=BINARY_DATA_HISTORY.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> codeList(
@ModelAttribute BinaryAnalysisResult bean
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
bean.setCurPage(page);
bean.setPageListSize(rows);
bean.setSortField(sidx);
bean.setSortOrder(sord);
Map<String, Object> map = binaryDataHistoryService.getBinaryDataHistoryList(bean);
return makeJsonResponseHeader(map);
}
}
| 1,928 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CommentController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/CommentController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.COMMENT;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.PartnerService;
import oss.fosslight.service.ProjectService;
@Controller
public class CommentController extends CoTopComponent {
@Autowired CommentService commentService;
@Autowired ProjectService projectService;
@Autowired PartnerService partnerService;
@GetMapping(value={COMMENT.COMMENT_LIST}, produces = "text/html; charset=utf-8")
public String getCommentList(CommentsHistory commentsHistory, HttpServletRequest req, HttpServletResponse res, Model model){
model.addAttribute("commentList", commentService.getCommentListHis(commentsHistory));
model.addAttribute("commentListCnt", commentService.getCommentListHisCnt(commentsHistory));
model.addAttribute("moreYn", false);
return COMMENT.COMMENT_LIST_JSP;
}
@GetMapping(value=COMMENT.MORE_COMMENT_LIST, produces = "text/html; charset=utf-8")
public String getMoreCommentList(CommentsHistory commentsHistory, HttpServletRequest req, HttpServletResponse res, Model model){
model.addAttribute("commentList", commentService.getMoreCommentListHis(commentsHistory));
model.addAttribute("commentListCnt", 0);
model.addAttribute("moreYn", true);
return COMMENT.COMMENT_LIST_JSP;
}
@RequestMapping(value=COMMENT.POPUP)
public String index(HttpServletRequest req, HttpServletResponse res, Model model
, @PathVariable String rDiv, @PathVariable String rId){
CommentsHistory commentsHistory = new CommentsHistory();
commentsHistory.setReferenceDiv(rDiv);
commentsHistory.setReferenceId(rId);
model.addAttribute("basicInfo", commentsHistory);
if ("prj".equalsIgnoreCase(rDiv) || rDiv.equalsIgnoreCase("security")) {
model.addAttribute("project", projectService.getProjectBasicInfo(rId));
} else if ("3rd".equalsIgnoreCase(rDiv)) {
PartnerMaster partnerMaster = new PartnerMaster();
partnerMaster.setPartnerId(rId);
model.addAttribute("partner", partnerService.getPartnerMasterOne(partnerMaster));
}
return COMMENT.POPUP_JSP;
}
@PostMapping(value = COMMENT.UPDATE_COMMENT)
public @ResponseBody ResponseEntity<Object> updateComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
commentService.updateComment(commentsHistory);
return makeJsonResponseHeader(true);
}
@PostMapping(value = COMMENT.DELETE_COMMENT)
public @ResponseBody ResponseEntity<Object> deleteComment(@ModelAttribute CommentsHistory commentsHistory,
HttpServletRequest req, HttpServletResponse res, Model model) {
commentService.deleteComment(commentsHistory);
return makeJsonResponseHeader(true);
}
@GetMapping(value=COMMENT.COMMENT_INFO_ID)
public @ResponseBody ResponseEntity<Object> getCommentInfo(HttpServletRequest req, HttpServletResponse res, Model model, @PathVariable String commId) {
Map<String, Object> map = commentService.getCommnetInfo(commId);
return makeJsonResponseHeader(map);
}
@GetMapping(value=COMMENT.DIV_COMMENT_LIST)
public @ResponseBody ResponseEntity<Object> getDivCommentList(CommentsHistory commentsHistory, HttpServletRequest req, HttpServletResponse res, Model model) {
List<CommentsHistory> result = commentService.getCommentList(commentsHistory);
return makeJsonResponseHeader(result);
}
}
| 4,430 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ProcessGuideController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/ProcessGuideController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.Url.PROCESSGUIDE;
import oss.fosslight.domain.ProcessGuide;
import oss.fosslight.service.ProcessGuideService;
@Controller
public class ProcessGuideController extends CoTopComponent {
@Autowired ProcessGuideService processGuideService;
/**
* [화면] Code
*/
@GetMapping(value=PROCESSGUIDE.PAGE, produces = "text/html; charset=utf-8")
public String index(HttpServletRequest req, HttpServletResponse res, Model model){
return PROCESSGUIDE.PAGE_JSP;
}
/**
* [API] 코드 목록 조회
*/
@GetMapping(value=PROCESSGUIDE.LIST_AJAX)
public @ResponseBody ResponseEntity<Object> listAjax(
@ModelAttribute ProcessGuide vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
int page = Integer.parseInt(req.getParameter("page"));
int rows = Integer.parseInt(req.getParameter("rows"));
String sidx = req.getParameter("sidx");
String sord = req.getParameter("sord");
vo.setCurPage(page);
vo.setPageListSize(rows);
vo.setSortField(sidx);
vo.setSortOrder(sord);
Map<String, Object> map = processGuideService.getProcessGuideList(vo);
return makeJsonResponseHeader(map);
}
@PostMapping(value=PROCESSGUIDE.SAVE_AJAX)
public @ResponseBody ResponseEntity<Object> saveAjax(
@ModelAttribute ProcessGuide vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
processGuideService.setProcessGuide(vo);
return makeJsonResponseHeader();
}
@RequestMapping(value={PROCESSGUIDE.PROCESS_GUIDE}, method = {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody ResponseEntity<Object> getPublishedProcessGuide(
@ModelAttribute ProcessGuide vo
, HttpServletRequest req
, HttpServletResponse res
, Model model) throws Exception{
return makeJsonResponseHeader(processGuideService.getProcessGuide(vo));
}
}
| 2,821 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SPDXDownloadController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/controller/SPDXDownloadController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.controller;
import java.io.File;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.SPDXDOWNLOAD;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.T2File;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.util.ExcelDownLoadUtil;
import oss.fosslight.util.SPDXUtil2;
@Controller
@Slf4j
public class SPDXDownloadController extends CoTopComponent {
@Resource private Environment env;
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
@Autowired ProjectService projectService;
@Autowired FileService fileService;
@Autowired CommentService commentService;
@PostMapping(value =SPDXDOWNLOAD.SPDX_POST)
public @ResponseBody ResponseEntity<Object> getExcelPost(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String downloadId = null;
try {
String spdxType = (String)map.get("type");
String dataStr = (String)map.get("dataStr");
String prjId = (String)map.get("prjId");
Project prjBean = null;
boolean partnerIdCheckFlag = prjId.startsWith("3rd_") ? true : false;
if (!partnerIdCheckFlag) {
prjBean = projectService.getProjectBasicInfo(prjId);
}
if ("spdxRdf".equals(spdxType)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getSpdxRdfFileId()))) {
downloadId = prjBean.getSpdxRdfFileId();
} else {
String sheetFileId = "";
if (dataStr.equals("spdx_sbom")) {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_sbom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String rdfFullPath = sheetFile.getLogiPath();
if (!rdfFullPath.endsWith("/")) {
rdfFullPath += "/";
}
rdfFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm())+".rdf";
SPDXUtil2.convert(prjId, sheetFullPath, rdfFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm())+".rdf",
FilenameUtils.getBaseName(sheetFile.getLogiNm())+".rdf");
try {
File spdxRdfFile = new File(rdfFullPath);
if (spdxRdfFile.exists() && spdxRdfFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.rdf.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("spdxTag".equals(spdxType)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getSpdxTagFileId()))) {
downloadId = prjBean.getSpdxTagFileId();
} else {
String sheetFileId = "";
if (dataStr.equals("spdx_sbom")) {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_sbom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String tagFullPath = sheetFile.getLogiPath();
if (!tagFullPath.endsWith("/")) {
tagFullPath += "/";
}
tagFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm())+".tag";
SPDXUtil2.convert(prjId, sheetFullPath, tagFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm())+".tag",
FilenameUtils.getBaseName(sheetFile.getLogiNm())+".tag");
try {
File spdxTafFile = new File(tagFullPath);
if (spdxTafFile.exists() && spdxTafFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.tag.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("spdxJson".equals(spdxType)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getSpdxJsonFileId()))) {
downloadId = prjBean.getSpdxJsonFileId();
} else {
String sheetFileId = "";
if (dataStr.equals("spdx_sbom")) {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_sbom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String jsonFullPath = sheetFile.getLogiPath();
if (!jsonFullPath.endsWith("/")) {
jsonFullPath += "/";
}
jsonFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".json";
SPDXUtil2.convert(prjId, sheetFullPath, jsonFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm()) + ".json",
FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".json");
try {
File spdxJsonFile = new File(jsonFullPath);
if (spdxJsonFile.exists() && spdxJsonFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.json.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("spdxYaml".equals(spdxType)) {
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getSpdxYamlFileId()))) {
downloadId = prjBean.getSpdxYamlFileId();
} else {
String sheetFileId = "";
if (dataStr.equals("spdx_sbom")) {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_sbom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String yamlFullPath = sheetFile.getLogiPath();
if (!yamlFullPath.endsWith("/")) {
yamlFullPath += "/";
}
yamlFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".yaml";
SPDXUtil2.convert(prjId, sheetFullPath, yamlFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm()) + ".yaml",
FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".yaml");
try {
File spdxYamlFile = new File(yamlFullPath);
if (spdxYamlFile.exists() && spdxYamlFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.yaml.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("spdx".equals(spdxType)){
if (!partnerIdCheckFlag && (prjBean != null && !isEmpty(prjBean.getSpdxSheetFileId()))) {
downloadId = prjBean.getSpdxSheetFileId();
} else {
if (dataStr.equals("spdx_sbom")) {
downloadId = ExcelDownLoadUtil.getExcelDownloadId("spdx_sbom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
downloadId = ExcelDownLoadUtil.getExcelDownloadId("spdx", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
}
}
} else {
log.error("not match type...");
return makeJsonResponseHeader(false, "not match type...");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
@ResponseBody
@GetMapping(value = SPDXDOWNLOAD.FILE)
public ResponseEntity<FileSystemResource> getFile (
HttpServletRequest req,
HttpServletResponse res, Model model) throws Exception{
T2File fileInfo = fileService.selectFileInfo(req.getParameter("id"));
String filePath = fileInfo.getLogiPath();
if (!filePath.endsWith("/")) {
filePath += "/";
}
filePath += fileInfo.getLogiNm();
return excelToResponseEntity(filePath, fileInfo.getOrigNm());
}
@PostMapping(value =SPDXDOWNLOAD.SELFCHECK_SPDX_POST)
public @ResponseBody ResponseEntity<Object> getSelfcheckSpdxPost(@RequestBody HashMap<String, Object> map,
HttpServletRequest req, HttpServletResponse res, Model model) {
String downloadId = null;
try {
String spdxType = (String)map.get("type");
String dataStr = (String)map.get("dataStr");
String prjId = (String)map.get("prjId");
if ("spdxRdf".equals(spdxType)) {
String sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_self", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String rdfFullPath = sheetFile.getLogiPath();
if (!rdfFullPath.endsWith("/")) {
rdfFullPath += "/";
}
rdfFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm())+".rdf";
SPDXUtil2.convert(prjId, sheetFullPath, rdfFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm())+".rdf",
FilenameUtils.getBaseName(sheetFile.getLogiNm())+".rdf");
try {
File spdxRdfFile = new File(rdfFullPath);
if (spdxRdfFile.exists() && spdxRdfFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.rdf.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if ("spdxTag".equals(spdxType)) {
String sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_self", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String tagFullPath = sheetFile.getLogiPath();
if (!tagFullPath.endsWith("/")) {
tagFullPath += "/";
}
tagFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm())+".tag";
SPDXUtil2.convert(prjId, sheetFullPath, tagFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm())+".tag",
FilenameUtils.getBaseName(sheetFile.getLogiNm())+".tag");
try {
File spdxTafFile = new File(tagFullPath);
if (spdxTafFile.exists() && spdxTafFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.tag.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if ("spdxJson".equals(spdxType)) {
String sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_self", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String jsonFullPath = sheetFile.getLogiPath();
if (!jsonFullPath.endsWith("/")) {
jsonFullPath += "/";
}
jsonFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".json";
SPDXUtil2.convert(prjId, sheetFullPath, jsonFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm()) + ".json",
FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".json");
try {
File spdxJsonFile = new File(jsonFullPath);
if (spdxJsonFile.exists() && spdxJsonFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.json.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if ("spdxYaml".equals(spdxType)) {
String sheetFileId = ExcelDownLoadUtil.getExcelDownloadId("spdx_self", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
T2File sheetFile = fileService.selectFileInfo(sheetFileId);
String sheetFullPath = sheetFile.getLogiPath();
if (!sheetFullPath.endsWith("/")) {
sheetFullPath += "/";
}
sheetFullPath += sheetFile.getLogiNm();
String yamlFullPath = sheetFile.getLogiPath();
if (!yamlFullPath.endsWith("/")) {
yamlFullPath += "/";
}
yamlFullPath += FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".yaml";
SPDXUtil2.convert(prjId, sheetFullPath, yamlFullPath);
downloadId = fileService.registFileDownload(sheetFile.getLogiPath(), FilenameUtils.getBaseName(sheetFile.getOrigNm()) + ".yaml",
FilenameUtils.getBaseName(sheetFile.getLogiNm()) + ".yaml");
try {
File spdxYamlFile = new File(yamlFullPath);
if (spdxYamlFile.exists() && spdxYamlFile.length() <= 0) {
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(getMessage("spdx.yaml.failure"));
commHisBean.setStatus(null); // 일반적인 comment에는 status를 넣지 않음.
commentService.registComment(commHisBean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} else if ("spdx".equals(spdxType)){
downloadId = ExcelDownLoadUtil.getExcelDownloadId("spdx_self", dataStr, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
} else {
log.error("not match type...");
return makeJsonResponseHeader(false, "not match type...");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return makeJsonResponseHeader(false, e.getMessage());
}
return makeJsonResponseHeader(downloadId);
}
}
| 17,952 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
AjaxInterceptor.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/interceptor/AjaxInterceptor.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class AjaxInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(AjaxInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean result = true;
try {
SecurityContext sc = SecurityContextHolder.getContext();
Authentication auth = sc.getAuthentication();
if (auth == null) {
//Ajax 콜인지 아닌지 판단
if (isAjaxRequest(request)){
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
} catch (Exception e) {
log.error(e.getMessage());
log.debug(e.getMessage());
return false;
}
return result;
}
private boolean isAjaxRequest(HttpServletRequest req) {
String ajaxHeader = "AJAX";
return req.getHeader(ajaxHeader) != null && req.getHeader(ajaxHeader).equals(Boolean.TRUE.toString());
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
| 2,051 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiCodeController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiCodeController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.API;
import oss.fosslight.service.ApiCodeService;
import oss.fosslight.service.T2UserService;
@Api(tags = {"6. Code"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
public class ApiCodeController extends CoTopComponent {
private final ResponseService responseService;
private final T2UserService userService;
private final ApiCodeService apiCodeService;
@ApiOperation(value = "Search Code Info", notes = "code 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_CODE_SEARCH})
public CommonResult getVulnerabilityData(
@RequestHeader String _token,
@ApiParam(value = "code Type (DIV:Division, OS:Os Type, DSTT:Distribution Type, DSTS:Distribution Site, NOTI:NOTICE TYPE, NP:NOTICE PLATFORM, PRI:PRIORITY)", required = true, allowableValues = "DIV,OS,DSTT,DSTS,NOTI,NP,PRI") @RequestParam(required = true) String codeType,
@ApiParam(value = "detail Value", required = false) @RequestParam(required = false) String detailValue){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> result = new HashMap<String, Object>();
try {
List<Map<String, Object>> contents = apiCodeService.getCodeList(codeType, detailValue);
if (contents.size() > 0) {
result.put("content", contents);
}
return responseService.getSingleResult(result);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
}
| 2,756 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiBatController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiBatController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.API;
import oss.fosslight.service.ApiBatService;
import oss.fosslight.service.T2UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
@Api(tags = {"7. Binary"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
@Profile(value = {"stage","prod"})
public class ApiBatController extends CoTopComponent {
private final ResponseService responseService;
private final T2UserService userService;
private final ApiBatService apibatService;
@ApiOperation(value = "Search Binary List", notes = "Binary Info 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_BINARY_SEARCH})
public CommonResult getBinaryInfo(
@RequestHeader String _token,
@ApiParam(value = "Binary Name", required = false) @RequestParam(required = false) String fileName,
@ApiParam(value = "Tlsh", required = false) @RequestParam(required = false) String tlsh,
@ApiParam(value = "checksum", required = false) @RequestParam(required = false) String checksum,
@ApiParam(value = "Platform Name", required = false) @RequestParam(required = false) String platformName,
@ApiParam(value = "PlatForm Version", required = false) @RequestParam(required = false) String platformVersion,
@ApiParam(value = "Source Path", required = false) @RequestParam(required = false) String sourcePath){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
// 전부 null이면 parameter error return
if (!isEmpty(fileName)
|| !isEmpty(tlsh)
|| !isEmpty(checksum)) {
paramMap.put("fileName", fileName);
paramMap.put("tlsh", tlsh);
paramMap.put("checksum", checksum);
paramMap.put("platformName", platformName);
paramMap.put("platformVersion", platformVersion);
paramMap.put("sourcePath", sourcePath);
List<Map<String, Object>> contents = apibatService.getBatList(paramMap);
if (contents != null) {
resultMap.put("content", contents);
}
return responseService.getSingleResult(resultMap);
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
}
| 3,533 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiProjectController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiProjectController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url;
import oss.fosslight.common.Url.API;
import oss.fosslight.domain.CoMail;
import oss.fosslight.domain.CoMailManager;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.History;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.T2Users;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.repository.CodeMapper;
import oss.fosslight.service.ApiFileService;
import oss.fosslight.service.ApiProjectService;
import oss.fosslight.service.CommentService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.HistoryService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.ExcelDownLoadUtil;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Api(tags = {"3. Project"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
public class ApiProjectController extends CoTopComponent {
@Resource private Environment env;
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
private boolean ldapCheckFlag = CoConstDef.FLAG_YES.equals(avoidNull(CommonFunction.getProperty("ldap.check.flag"))) ? true : false;
private final ResponseService responseService;
private final T2UserService userService;
private final ApiProjectService apiProjectService;
private final FileService fileService;
private final ApiFileService apiFileService;
private final CommentService commentService;
private final ProjectService projectService;
private final HistoryService historyService;
private final CodeMapper codeMapper;
protected static final Logger log = LoggerFactory.getLogger("DEFAULT_LOG");
@ApiOperation(value = "Search Project List", notes = "Project 정보 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_PROJECT_SEARCH})
public CommonResult selectProjectList(
@RequestHeader String _token,
@ApiParam(value = "project ID List", required = false) @RequestParam(required = false) String[] prjIdList,
@ApiParam(value = "Division (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String division,
@ApiParam(value = "Model Name", required = false) @RequestParam(required = false) String modelName,
@ApiParam(value = "Create Date (Format: fromDate-toDate > yyyymmdd-yyyymmdd)", required = false) @RequestParam(required = false) String createDate,
@ApiParam(value = "Status (PROG:progress, REQ:Request, REV:Review, COMP:Complete, DROP:Drop)", required = false, allowableValues = "PROG,REQ,REV,COMP,DROP") @RequestParam(required = false) String status,
@ApiParam(value = "Update Date (Format: fromDate-toDate > yyyymmdd-yyyymmdd)", required = false) @RequestParam(required = false) String updateDate,
@ApiParam(value = "Creator", required = false) @RequestParam(required = false) String creator){
// 사용자 인증
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
try {
CommonFunction.splitDate(createDate, paramMap, "-", "createDate");
CommonFunction.splitDate(updateDate, paramMap, "-", "updateDate");
// paramMap.put("userRole", userInfo.getAuthority());
paramMap.put("creator", creator);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("division", division);
paramMap.put("modelName", modelName);
paramMap.put("status", status);
paramMap.put("prjIdList", prjIdList);
try {
resultMap = apiProjectService.selectProjectList(paramMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Search Project List", notes = "Project 정보 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_MODEL_SEARCH})
public CommonResult selectModelList(
@RequestHeader String _token,
@ApiParam(value = "project ID List", required = true) @RequestParam(required = true) String[] prjIdList){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
try {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("prjIdList", prjIdList);
resultMap = apiProjectService.selectModelList(paramMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Update model list of project", notes = "Basic Information > Model list")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {API.FOSSLIGHT_API_MODEL_UPDATE})
public CommonResult updateModelList(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Model List (ex. MODEL_NAME|ETC > Etc|20220428)", required = true) @RequestParam(required = true) String[] modelListToUpdate) {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, List<Project>> modelList = null;
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_NO);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
Project project = projectService.getProjectBasicInfo(prjId);
if (modelListToUpdate != null) {
List<String[]> models = new ArrayList<>();
for (String strModel : modelListToUpdate) {
String[] model = strModel.replaceAll("\"", "").split("\\|");
if (model.length > 2) {
models.add(model);
}
}
if (models.size() > 0) {
modelList = ExcelUtil.readModelFromList(models, prjId, CoConstDef.FLAG_YES, "0", project.getDistributeTarget());
}
}
if (modelList != null) {
project.setModelList(modelList.get("currentModelList"));
projectService.insertProjectModel(project);
return responseService.getSingleResult(resultMap);
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
log.error(e.getMessage());
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
return responseService.getFailResult(errorCode
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
@ApiOperation(value = "Update model list of project with file", notes = "Basic Information > Model list with file")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {API.FOSSLIGHT_API_MODEL_UPDATE_UPLOAD_FILE})
public CommonResult updateModelListUploadFile(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Model List (Spread sheet)", required = false) @RequestPart(required = false) MultipartFile modelReport) {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, List<Project>> modelList = null;
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
if (modelReport == null) {
errorCode = CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE;
} else {
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_NO);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
Project project = projectService.getProjectBasicInfo(prjId);
if (modelReport != null) {
if (modelReport.getOriginalFilename().contains("xls") // Allowed file extension: xls, xlsx, xlsm
&& CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT > modelReport.getSize()) { // Max file size :5MB
modelList = ExcelUtil.getModelList(modelReport, CommonFunction.emptyCheckProperty("upload.path", "/upload"),
project.getDistributeTarget(), prjId, CoConstDef.FLAG_YES, "0");
} else {
errorCode = CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE;
}
}
if (modelList != null) {
project.setModelList(modelList.get("currentModelList"));
projectService.insertProjectModel(project);
return responseService.getSingleResult(resultMap);
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
log.error(e.getMessage());
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
}
return responseService.getFailResult(errorCode
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
@ApiOperation(value = "Create Project", notes = "project 생성")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_PROJECT_CREATE})
public CommonResult createProject(
@RequestHeader String _token,
@ApiParam(value = "Project Name", required = true) @RequestParam(required = true) String prjName,
@ApiParam(value = "Project Version", required = false) @RequestParam(required = false) String prjVersion,
@ApiParam(value = "OS Type (\"Check the input value with /api/v1/code_search\")", required = true) @RequestParam(required = true) String osType,
@ApiParam(value = "OS Type etc", required = false) @RequestParam(required = false) String osTypeEtc,
@ApiParam(value = "Distribution Type (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String distributionType,
@ApiParam(value = "Distribution Site (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String distributionSite,
@ApiParam(value = "Network Service (YES : Y, NO : N)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String networkServerType,
@ApiParam(value = "OSS Notice (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String noticeType,
@ApiParam(value = "Notice Platform (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String noticeTypeEtc,
@ApiParam(value = "Priority (\"Check the input value with /api/v1/code_search\")", required = false) @RequestParam(required = false) String priority,
@ApiParam(value = "Additional information", required = false) @RequestParam(required = false) String additionalInformation,
@ApiParam(value = "comment", required = false) @RequestParam(required = false) String comment){
// 사용자 인증
T2Users userInfo = userService.checkApiUserAuth(_token);
int createCnt = apiProjectService.getCreateProjectCnt(userInfo.getUserId());
Map<String, Object> result = new HashMap<String, Object>();
try {
if (CoConstDef.CD_OPEN_API_CREATE_PROJECT_LIMIT > createCnt) {
Map<String, Object> paramMap = new HashMap<String, Object>();
String osTypeStr = CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, osType);
if (isEmpty(osTypeStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
if (!isEmpty(distributionType)) {
String distributionTypeStr = CoCodeManager.getCodeString(CoConstDef.CD_DISTRIBUTION_TYPE, distributionType);
if (isEmpty(distributionTypeStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} else {
distributionType = CoConstDef.CD_DTL_NOTICE_TYPE_GENERAL;
}
if (!isEmpty(distributionSite)) {
String distributionSiteStr = CoCodeManager.getCodeString(CoConstDef.CD_DISTRIBUTE_CODE, distributionSite);
if (isEmpty(distributionSiteStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} else {
distributionSite = CoConstDef.CD_DTL_DISTRIBUTE_LGE;
}
if (!isEmpty(networkServerType)) {
if (!CoConstDef.FLAG_YES.equals(networkServerType)
&& !CoConstDef.FLAG_NO.equals(networkServerType)) { // NETWORK Service Only는 Y / N만 선택 가능함.
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} else {
networkServerType = CoConstDef.FLAG_NO;
}
if (isEmpty(noticeType)) {
if (!isEmpty(noticeTypeEtc)) {
String noticeTypeEtcStr = CoCodeManager.getCodeString(CoConstDef.CD_PLATFORM_GENERATED, noticeTypeEtc);
if (!isEmpty(noticeTypeEtcStr)) {
noticeType = CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED;
} else if (isEmpty(noticeTypeEtcStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} else {
noticeType = CoConstDef.CD_DTL_NOTICE_TYPE_GENERAL;
}
} else if (!isEmpty(noticeType)) {
String noticeTypeStr = CoCodeManager.getCodeString(CoConstDef.CD_NOTICE_TYPE, noticeType);
if (isEmpty(noticeTypeStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
if (!CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED.equals(noticeType)) {
noticeTypeEtc = "";
} else if (CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED.equals(noticeType) && isEmpty(noticeTypeEtc)) {
noticeTypeEtc = CoConstDef.CD_DTL_DEFAULT_PLATFORM;
} else if (!isEmpty(noticeTypeEtc)) {
String noticeTypeEtcStr = CoCodeManager.getCodeString(CoConstDef.CD_PLATFORM_GENERATED, noticeTypeEtc);
if (!isEmpty(noticeTypeEtcStr)) {
noticeTypeEtc = noticeTypeEtcStr;
} else if (isEmpty(noticeTypeEtcStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
if (!isEmpty(priority)) {
String priorityStr = CoCodeManager.getCodeString(CoConstDef.CD_PROJECT_PRIORITY, priority);
if (isEmpty(priorityStr)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} else {
priority = CoConstDef.CD_PRIORITY_P2;
}
paramMap.put("prjName", prjName);
paramMap.put("prjVersion", avoidNull(prjVersion, ""));
paramMap.put("osType", osType);
paramMap.put("osTypeEtc", osTypeEtc);
paramMap.put("distributionType", distributionType);
paramMap.put("distributionSite", distributionSite);
paramMap.put("networkServerType", networkServerType);
paramMap.put("priority", priority);
paramMap.put("loginUserName", userInfo.getUserId());
paramMap.put("comment", avoidNull(additionalInformation, ""));
result = apiProjectService.createProject(paramMap);
String resultPrjId = (String) result.get("prjId");
Map<String, Object> noticeParamMap = new HashMap<String, Object>();
noticeParamMap.put("prjId", resultPrjId);
noticeParamMap.put("noticeType", noticeType);
noticeParamMap.put("noticeTypeEtc", noticeTypeEtc);
int resultCnt = apiProjectService.makeOssNotice(noticeParamMap);
if (!isEmpty(resultPrjId) && resultCnt > 0) {
try {
History h = new History();
Project project = new Project();
project.setPrjId(resultPrjId);
h = projectService.work(project);
h.setModifier(userInfo.getUserId());
h.sethAction(CoConstDef.ACTION_CODE_INSERT);
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (comment != null) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PROJECT_HIS);
commentHisBean.setReferenceId(resultPrjId);
commentHisBean.setContents(comment);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
try {
CoMail mailBean = new CoMail(CoConstDef.CD_MAIL_TYPE_PROJECT_CREATED);
mailBean.setParamPrjId(resultPrjId);
String _tempComment = avoidNull(CoCodeManager.getCodeExpString(CoConstDef.CD_MAIL_DEFAULT_CONTENTS, CoConstDef.CD_MAIL_TYPE_PROJECT_CREATED));
comment = avoidNull(comment) + "<br />" + _tempComment;
mailBean.setComment(comment);
mailBean.setLoginUserName(userInfo.getUserId());
mailBean.setLoginUserRole(userInfo.getAuthority());
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return responseService.getSingleResult(result);
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_CREATE_PROJECT_DUPLICATE_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_CREATE_PROJECT_DUPLICATE_MESSAGE));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_CREATE_OVERFLOW_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_CREATE_OVERFLOW_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Project Bom Tab Export", notes = "Project > Bom tab Export")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_PROJECT_BOM_EXPORT})
public ResponseEntity<FileSystemResource> getPrjBomExport(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Merge & Save Flag (YES : Y, NO : N)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String mergeSaveFlag){
// 사용자 인증
String downloadId = "";
T2File fileInfo = new T2File();
try {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_NO);
paramMap.put("distributionType", "normal");
boolean searchFlag = apiProjectService.existProjectCnt(paramMap);
if (searchFlag) {
if ("Y".equals(mergeSaveFlag)) {
// apiProjectService.registBom(prjId, mergeSaveFlag);
projectService.registBom(prjId, mergeSaveFlag, new ArrayList<>(), new ArrayList<>());
}
downloadId = ExcelDownLoadUtil.getExcelDownloadId("bom", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
fileInfo = fileService.selectFileInfo(downloadId);
}
return excelToResponseEntity(fileInfo.getLogiPath() + fileInfo.getLogiNm(), fileInfo.getOrigNm());
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
@ApiOperation(value = "Project Bom Tab Export Json", notes = "Project > Bom tab Export Json")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_PROJECT_BOM_EXPORT_JSON})
public CommonResult getPrjBomExportJson(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId) {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("distributionType", "normal");
boolean searchFlag = apiProjectService.existProjectCnt(paramMap);
if (searchFlag) {
resultMap = apiProjectService.getBomExportJson(prjId);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Project Bom Compare", notes = "Project > Bom tab Compare")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_PROJECT_BOM_COMPARE})
public CommonResult getPrjBomCompare(
@RequestHeader String _token,
@ApiParam(value = "Before Project id", required = true) @RequestParam(required = true) String beforePrjId,
@ApiParam(value = "After Project id", required = true) @RequestParam(required = true) String afterPrjId){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<>();
try {
Map<String, Object> paramMap = new HashMap<>();
if (!isEmpty(beforePrjId) && beforePrjId.equals(afterPrjId)) {
paramMap.put("status", "same");
resultMap.put("contents", paramMap);
return responseService.getSingleResult(resultMap);
}
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(beforePrjId);
prjIdList.add(afterPrjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("distributionType", "normal");
int records = apiProjectService.existProjectCntBomCompare(paramMap);
if (records > 0) {
List<Map<String, Object>> beforeBomList = new ArrayList<>();
List<Map<String, Object>> afterBomList = new ArrayList<>();
Map<String, Object> beforePrjInfo = apiProjectService.getProjectBasicInfo(beforePrjId);
if (!((String) beforePrjInfo.get("noticeType")).equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED)) {
beforeBomList = apiProjectService.getBomList(beforePrjId);
} else {
apiProjectService.getIdentificationGridList(beforePrjId, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID, null, null, beforeBomList);
beforeBomList = apiProjectService.setMergeGridData(beforeBomList);
}
Map<String, Object> afterPrjInfo = apiProjectService.getProjectBasicInfo(afterPrjId);
if (!((String) afterPrjInfo.get("noticeType")).equals(CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED)) {
afterBomList = apiProjectService.getBomList(afterPrjId);
} else {
apiProjectService.getIdentificationGridList(afterPrjId, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID, null, null, afterBomList);
afterBomList = apiProjectService.setMergeGridData(afterBomList);
}
if (beforeBomList.isEmpty() || afterBomList.isEmpty()) {
throw new Exception();
}
resultMap.put("contents", apiProjectService.getBomCompare(beforeBomList, afterBomList));
return responseService.getSingleResult(resultMap);
} else {
paramMap.clear();
paramMap.put("status", "not exist project");
resultMap.put("contents", paramMap);
return responseService.getSingleResult(resultMap);
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "Identification OSS Report", notes = "Identification > dep > oss report")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {Url.API.FOSSLIGHT_API_OSS_REPORT_DEP})
public CommonResult ossReportDep(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "OSS Report > sheetName : all sheets starting with 'DEP'", required = false) @RequestPart(required = false) MultipartFile ossReport,
@ApiParam(value = "Comment", required = false) @RequestParam(required = false) String comment,
@ApiParam(value = "Reset Flag (YES : Y, NO : N, Default : Y)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String resetFlag,
@ApiParam(value = "Sheet Names", required = false) @RequestParam(required = false) String sheetNames){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>(); // 성공, 실패에 대한 정보를 return하기 위한 map;
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_YES);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
paramMap.put("distributionType", "normal");
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
String oldFileId = "";
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
Map<String, Object> prjInfo = apiProjectService.selectProjectMaster(prjId);
if (prjInfo.get("depCsvFileId") != null) {
oldFileId = String.valueOf((int) prjInfo.get("depCsvFileId"));
}
}
if (ossReport != null) {
if (ossReport.getOriginalFilename().contains("xls") // 확장자 xls, xlsx, xlsm 허용
&& CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT > ossReport.getSize()) { // file size 5MB 이하만 허용.
boolean checkDistributionTypeFlag = apiProjectService.checkDistributionType(paramMap);
if (!checkDistributionTypeFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE));
}
UploadFile bean = null;
if (!isEmpty(oldFileId)) {
bean = apiFileService.uploadFile(ossReport, null, oldFileId);
} else {
bean = apiFileService.uploadFile(ossReport); // file 등록 처리 이후 upload된 file정보를 return함.
}
// get Excel Sheet name starts with DEP
List<String> sheet = null;
boolean sheetNamesEmptyFlag = isEmpty(sheetNames) ? true : false;
try {
if (sheetNamesEmptyFlag) {
sheet = ExcelUtil.getSheetNoStartsWith("DEP", Arrays.asList(bean), CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} else {
List<UploadFile> list = new ArrayList<UploadFile>();
list.add(bean);
List<Object> sheets = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
boolean createListFlag = false;
for (Object obj : sheets) {
Map<String, Object> sheetMap = (Map<String, Object>) obj;
if (sheetMap.containsKey("name")) {
if (!createListFlag) {
sheet = new ArrayList<>();
createListFlag = true;
}
sheet.add((String) sheetMap.get("name"));
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Map<String, Object> result = null;
if (sheetNamesEmptyFlag) {
result = apiProjectService.getSheetData(bean, prjId, "DEP", sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY);
resultMap = apiProjectService.getProcessSheetData(result, prjId, resetFlag, bean.getRegistFileId(), userInfo.getUserId(), comment, "DEP", "DEP", sheetNamesEmptyFlag, false, 0);
} else {
int sheetLength = sheetNames.split(",").length;
int sheetIdx = 0;
for (String sheetNm : sheetNames.split(",")) {
if (isEmpty(sheetNm.trim())) continue;
result = apiProjectService.getSheetData(bean, prjId, sheetNm.trim(), sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY, true);
resultMap = apiProjectService.getProcessSheetData(result, prjId, resetFlag, bean.getRegistFileId(), userInfo.getUserId(), comment, "DEP", sheetNm.trim(), sheetNamesEmptyFlag, sheetLength > 1 ? true : false, sheetIdx);
sheetIdx++;
if (!resultMap.isEmpty()) {
break;
}
}
}
if (resultMap.isEmpty()) {
// 정상처리된 경우 세션 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_DEP, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_DEP, prjId));
return responseService.getSingleResult(resultMap);
} else {
if (resultMap.containsKey(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, (String) resultMap.get(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE));
} else if (resultMap.containsKey("validError")) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE));
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "Identification OSS Report", notes = "Identification > src > oss report")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {Url.API.FOSSLIGHT_API_OSS_REPORT_SRC})
public CommonResult ossReportSrc(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "OSS Report > sheetName : all sheets starting with 'SRC'", required = false) @RequestPart(required = false) MultipartFile ossReport,
@ApiParam(value = "Comment", required = false) @RequestParam(required = false) String comment,
@ApiParam(value = "Reset Flag (YES : Y, NO : N, Default : Y)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String resetFlag,
@ApiParam(value = "Sheet Names", required = false) @RequestParam(required = false) String sheetNames){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>(); // 성공, 실패에 대한 정보를 return하기 위한 map;
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_YES);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
paramMap.put("distributionType", "normal");
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
String oldFileId = "";
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
Map<String, Object> prjInfo = apiProjectService.selectProjectMaster(prjId);
if (prjInfo.get("srcCsvFileId") != null) {
oldFileId = String.valueOf((int) prjInfo.get("srcCsvFileId"));
}
}
if (ossReport != null) {
if (ossReport.getOriginalFilename().contains("xls") // 확장자 xls, xlsx, xlsm 허용
&& CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT > ossReport.getSize()) { // file size 5MB 이하만 허용.
boolean checkDistributionTypeFlag = apiProjectService.checkDistributionType(paramMap); // 잘못된 project에 oss report를 upload하려고 할 경우 ex) src -> bin Android
if (!checkDistributionTypeFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE));
}
UploadFile bean = null;
if (!isEmpty(oldFileId)) {
bean = apiFileService.uploadFile(ossReport, null, oldFileId);
} else {
bean = apiFileService.uploadFile(ossReport); // file 등록 처리 이후 upload된 file정보를 return함.
}
// get Excel Sheet name starts with SRC
List<String> sheet = null;
boolean sheetNamesEmptyFlag = isEmpty(sheetNames) ? true : false;
try {
if (sheetNamesEmptyFlag) {
sheet = ExcelUtil.getSheetNoStartsWith("SRC", Arrays.asList(bean), CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} else {
List<UploadFile> list = new ArrayList<UploadFile>();
list.add(bean);
List<Object> sheets = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
boolean createListFlag = false;
for (Object obj : sheets) {
Map<String, Object> sheetMap = (Map<String, Object>) obj;
if (sheetMap.containsKey("name")) {
if (!createListFlag) {
sheet = new ArrayList<>();
createListFlag = true;
}
sheet.add((String) sheetMap.get("name"));
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Map<String, Object> result = null;
if (sheetNamesEmptyFlag) {
result = apiProjectService.getSheetData(bean, prjId, "SRC", sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY);
resultMap = apiProjectService.getProcessSheetData(result, prjId, resetFlag, bean.getRegistFileId(), userInfo.getUserId(), comment, "SRC", "SRC", sheetNamesEmptyFlag, false, 0);
} else {
int sheetLength = sheetNames.split(",").length;
int sheetIdx = 0;
for (String sheetNm : sheetNames.split(",")) {
if (isEmpty(sheetNm.trim())) continue;
result = apiProjectService.getSheetData(bean, prjId, sheetNm.trim(), sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY, true);
resultMap = apiProjectService.getProcessSheetData(result, prjId, resetFlag, bean.getRegistFileId(), userInfo.getUserId(), comment, "SRC", sheetNm.trim(), sheetNamesEmptyFlag, sheetLength > 1 ? true : false, sheetIdx);
sheetIdx++;
if (!resultMap.isEmpty()) {
break;
}
}
}
if (resultMap.isEmpty()) {
// 정상처리된 경우 세션 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_DEP, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_DEP, prjId));
return responseService.getSingleResult(resultMap);
} else {
if (resultMap.containsKey(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, (String) resultMap.get(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE));
} else if (resultMap.containsKey("validError")) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE));
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "Identification OSS Report", notes = "Identification > bin > oss report")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {Url.API.FOSSLIGHT_API_OSS_REPORT_BIN})
public CommonResult ossReportBin(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "OSS Report > sheetName : 'BIN'", required = false) @RequestPart(required = false) MultipartFile ossReport,
@ApiParam(value = "Binary.txt", required = false) @RequestPart(required = false) MultipartFile binartTxt,
@ApiParam(value = "Comment", required = false) @RequestParam(required = false) String comment,
@ApiParam(value = "Reset Flag (YES : Y, NO : N, Default : Y)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String resetFlag,
@ApiParam(value = "Sheet Names", required = false) @RequestParam(required = false) String sheetNames){
T2Users userInfo = userService.checkApiUserAuth(_token); // token이 정상적인 값인지 확인
Map<String, Object> resultMap = new HashMap<String, Object>(); // 성공, 실패에 대한 정보를 return하기 위한 map;
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_YES);
paramMap.put("distributionType", "normal");
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
List<ProjectIdentification> ossComponents = new ArrayList<>();
List<List<ProjectIdentification>> ossComponentsLicense = null;
String changeExclude = "";
String changeAdded = "";
Project project = new Project();
UploadFile ossReportBean = null;
UploadFile binartTxtBean = null;
String oldFileId = "";
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
Map<String, Object> prjInfo = apiProjectService.selectProjectMaster(prjId);
if (prjInfo.get("binCsvFileId") != null) {
oldFileId = String.valueOf((int) prjInfo.get("binCsvFileId"));
}
}
if (ossReport != null) {
if (!ossReport.getOriginalFilename().contains("xls")) { // 확장자 xls, xlsx, xlsm 허용
return responseService.getFailResult(CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE));
} else if (CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT <= ossReport.getSize()) { // file size 5MB 이하만 허용.
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
} else {
boolean checkDistributionTypeFlag = apiProjectService.checkDistributionType(paramMap); // 잘못된 project에 oss report를 upload하려고 할 경우 ex) bin -> bin Android
if (!checkDistributionTypeFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE));
}
if (!isEmpty(oldFileId)) {
ossReportBean = apiFileService.uploadFile(ossReport, null, oldFileId);
} else {
ossReportBean = apiFileService.uploadFile(ossReport);
}
// get Excel Sheet name starts with SRC
List<String> sheet = null;
boolean sheetNamesEmptyFlag = isEmpty(sheetNames) ? true : false;
try {
if (sheetNamesEmptyFlag) {
sheet = ExcelUtil.getSheetNoStartsWith("BIN", Arrays.asList(ossReportBean), CommonFunction.emptyCheckProperty("upload.path", "/upload"));
} else {
List<UploadFile> list = new ArrayList<UploadFile>();
list.add(ossReportBean);
List<Object> sheets = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
boolean createListFlag = false;
for (Object obj : sheets) {
Map<String, Object> sheetMap = (Map<String, Object>) obj;
if (sheetMap.containsKey("name")) {
if (!createListFlag) {
sheet = new ArrayList<>();
createListFlag = true;
}
sheet.add((String) sheetMap.get("name"));
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Map<String, Object> result = null;
boolean errorFlag = false;
String errorMsg = "";
String sheetName = "";
if (sheetNamesEmptyFlag) {
sheetName = "BIN";
result = apiProjectService.getSheetData(ossReportBean, prjId, sheetName, sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY);
if (result.containsKey("errorMsg")) {
errorMsg = (String) result.get("errorMsg");
}
} else {
for (String sheetNm : sheetNames.split(",")) {
sheetName = sheetNm.trim();
if (isEmpty(sheetName)) continue;
Map<String, Object> rtnMap = apiProjectService.getSheetData(ossReportBean, prjId, sheetName, sheet != null ? sheet.toArray(new String[sheet.size()]) : ArrayUtils.EMPTY_STRING_ARRAY, true);
String rtnErrorMsg = "";
if (rtnMap.containsKey("errorMsg")) {
rtnErrorMsg = (String) rtnMap.get("errorMsg");
if (!isEmpty(rtnErrorMsg) && rtnErrorMsg.toUpperCase().startsWith("THERE ARE NO OSS LISTED")) {
errorMsg = rtnErrorMsg;
break;
}
}
List<ProjectIdentification> rtnOssComponents = (List<ProjectIdentification>) rtnMap.get("ossComponents");
rtnOssComponents = (rtnOssComponents != null ? rtnOssComponents : new ArrayList<>());
if (rtnOssComponents.isEmpty()) {
errorFlag = true;
break;
} else {
ossComponents.addAll(rtnOssComponents);
}
List<List<ProjectIdentification>> rtnOssComponentsLicense = (List<List<ProjectIdentification>>) rtnMap.get("ossComponentLicense");
if (rtnOssComponentsLicense != null) {
if (ossComponentsLicense == null) {
ossComponentsLicense = new ArrayList<>();
}
ossComponentsLicense.addAll(rtnOssComponentsLicense);
}
}
}
if (!isEmpty(errorMsg) && errorMsg.toUpperCase().startsWith("THERE ARE NO OSS LISTED")) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE));
}
if (!isEmpty(errorMsg)) {
resultMap.put("errorMessage", errorMsg);
}
if (sheetNamesEmptyFlag) {
ossComponents = (List<ProjectIdentification>) result.get("ossComponents");
ossComponents = (ossComponents != null ? ossComponents : new ArrayList<>());
ossComponentsLicense = (List<List<ProjectIdentification>>) result.get("ossComponentLicense");
if (ossComponents.isEmpty()) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, getMessage("api.upload.file.sheet.no.match", new String[]{"BIN*"}));
}
} else {
if (errorFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, getMessage("api.upload.file.sheet.no.match", new String[]{sheetName + "*"}));
}
}
project.setBinCsvFileId(ossReportBean.getRegistFileId()); // set file id
}
}
if (binartTxt != null) {
if (binartTxt.getOriginalFilename().contains("txt")) {
binartTxtBean = apiFileService.uploadFile(binartTxt); // file 등록 처리 이후 upload된 file정보를 return함.
String binaryFileId = binartTxtBean.getRegistFileId();
List<String> binaryTxtList = CommonFunction.getBinaryListBinBinaryTxt(fileService.selectFileInfoById(binaryFileId));
if (binaryTxtList != null && !binaryTxtList.isEmpty()) {
// 현재 osslist의 binary 목록을 격납
Map<String, ProjectIdentification> componentBinaryList = new HashMap<>();
for (ProjectIdentification bean : ossComponents) {
if (bean != null && !isEmpty(bean.getBinaryName())) {
componentBinaryList.put(bean.getBinaryName(), bean);
}
}
List<ProjectIdentification> addComponentList = Lists.newArrayList();
// 존재여부 확인
for (String binaryNameTxt : binaryTxtList) {
if (!componentBinaryList.containsKey(binaryNameTxt)) {
// add 해야할 list
ProjectIdentification bean = new ProjectIdentification();
// 화면에서 추가한 것 처럼 jqg로 시작하는 component id를 임시로 설정한다.
bean.setGridId("jqg_"+binaryFileId+"_"+addComponentList.size());
bean.setBinaryName(binaryNameTxt);
addComponentList.add(bean);
changeAdded += "<br> - " + binaryNameTxt;
}
// exclude처리된 경우
else {
ProjectIdentification bean = componentBinaryList.get(binaryNameTxt);
if (bean != null && CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
changeExclude += "<br>" + binaryNameTxt;
}
}
}
if (addComponentList != null && !addComponentList.isEmpty()) {
ossComponents.addAll(addComponentList);
}
}
project.setBinBinaryFileId(binaryFileId);
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE));
}
}
if (ossReportBean == null
&& binartTxtBean == null) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE));
} else {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BIN);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE));
} else {
List<ProjectIdentification> ossComponentList = new ArrayList<>();
List<List<ProjectIdentification>> ossComponentsLicenseList = new ArrayList<>();
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
apiProjectService.getIdentificationGridList(prjId, CoConstDef.CD_DTL_COMPONENT_ID_BIN, ossComponentList, ossComponentsLicenseList, null);
}
ossComponentList.addAll(ossComponents);
ossComponentsLicenseList.addAll(ossComponentsLicense);
project.setPrjId(prjId);
projectService.registSrcOss(ossComponentList, ossComponentsLicenseList, project, CoConstDef.CD_DTL_COMPONENT_ID_BIN); // bin tab
String csvFileId = project.getBinCsvFileId();
if (!isEmpty(changeExclude) || !isEmpty(changeAdded)) {
String changedByResultTxt = "";
if (!isEmpty(changeAdded)) {
changedByResultTxt += "<b>The following binaries were added to OSS List automatically because they exist in the binary.txt.</b><br>";
changedByResultTxt += changeAdded;
}
if (!isEmpty(changeExclude)) {
if (!isEmpty(changedByResultTxt)) {
changedByResultTxt += "<br><br>";
}
changedByResultTxt += "<b>The following binaries are written to the OSS report as excluded, but they are in the binary.txt. Make sure it is not included in the final firmware.</b><br>";
changedByResultTxt += changeExclude;
}
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedByResultTxt);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(
loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedLicenseName);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// oss name이 nick name으로 등록되어 있는 경우, 자동치환된 Data를 comment his에 등록
try {
if (getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId,
CoConstDef.CD_DTL_COMPONENT_ID_BIN)) != null) {
String changedLicenseName = (String) getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED,
prjId, CoConstDef.CD_DTL_COMPONENT_ID_BIN),
true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(changedLicenseName);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId)) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(chagedOssVersion);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (comment != null) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN");
commentHisBean.setContents(comment);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// session 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_BIN, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_BIN,
prjId));
}
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getSingleResult(resultMap);
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "Identification OSS Report", notes = "Identification > android > oss report", hidden = true)
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {Url.API.FOSSLIGHT_API_OSS_REPORT_ANDROID})
public CommonResult ossReportAndroid(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "OSS Report > sheetName : 'BIN (Android)'", required = true) @RequestPart(required = true) MultipartFile ossReport,
@ApiParam(value = "NOTICE.html", required = true) @RequestPart(required = true) MultipartFile noticeHtml,
@ApiParam(value = "result.txt", required = false) @RequestPart(required = false) MultipartFile resultTxt,
@ApiParam(value = "Comment", required = false) @RequestParam(required = false) String comment){
T2Users userInfo = userService.checkApiUserAuth(_token); // token이 정상적인 값인지 확인
Map<String, Object> resultMap = new HashMap<String, Object>(); // 성공, 실패에 대한 정보를 return하기 위한 map;
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_YES);
paramMap.put("distributionType", "android");
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
UploadFile ossReportBean = null;
if (searchFlag) {
if (!ossReport.getOriginalFilename().contains("xls")){ // 확장자 xls, xlsx, xlsm 허용
return responseService.getFailResult(CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_EXT_UNSUPPORT_MESSAGE));
} else if (CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT <= ossReport.getSize()) { // file size 5MB 이하만 허용.
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
} else {
boolean checkDistributionTypeFlag = apiProjectService.checkDistributionType(paramMap); // 잘못된 project에 oss report를 upload하려고 할 경우 ex) bin Android -> bin
if (!checkDistributionTypeFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UPLOAD_TARGET_ERROR_MESSAGE));
}
ossReportBean = apiFileService.uploadFile(ossReport); // ossReport 등록
}
String noticeHtmlFileName = noticeHtml.getOriginalFilename();
String codeExt[] = StringUtil.split(codeMapper.selectExtType(CoConstDef.CD_ANDROID_NOTICE_XML), ",");
int count = 0;
for (int i = 0; i < codeExt.length; i++) {
if (noticeHtmlFileName.endsWith(codeExt[i])) {
count++;
}
;
}
UploadFile noticeHtmlBean = null;
UploadFile noticeXMLBean = null;
if (count == 1) {
Map<String, UploadFile> Files = apiFileService.uploadNoticeXMLFile(noticeHtml, prjId);
noticeHtmlBean = Files.get("noticeHTML");
noticeXMLBean = Files.get("noticeXML");
}else if (count == 0) {
noticeHtmlBean = apiFileService.uploadFile(noticeHtml); // noticeHtml 등록
} else {
noticeHtmlBean = null;
}
UploadFile resultTxtBean = null;
if (resultTxt != null) {
resultTxtBean = apiFileService.uploadFile(resultTxt); // resultTxt 등록
}
Map<String, Object> result = apiProjectService.readAndroidBuildImage(ossReportBean, noticeHtmlBean, resultTxtBean);
List<ProjectIdentification> ossComponents = (List<ProjectIdentification>) result.get("ossComponents");
List<List<ProjectIdentification>> ossComponentsLicense = (List<List<ProjectIdentification>>) result.get("ossComponentLicense");
if (ossReportBean == null
&& noticeHtmlBean == null
&& resultTxtBean == null) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_NOTEXISTS_MESSAGE));
} else {
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE));
} else {
Project project = new Project(); // detail project vo
project.setPrjId(prjId);
project.setSrcAndroidCsvFileId(ossReportBean.getRegistFileId());
project.setSrcAndroidNoticeFileId(noticeXMLBean != null ? noticeXMLBean.getRegistFileId() : noticeHtmlBean.getRegistFileId());
project.setSrcAndroidNoticeXmlId(noticeHtmlBean != null ? noticeHtmlBean.getRegistFileId() : "");
project.setSrcAndroidResultFileId(resultTxtBean != null ? resultTxtBean.getRegistFileId() : "");
projectService.registSrcOss(ossComponents, ossComponentsLicense, project,
CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
String csvFileId = project.getSrcAndroidCsvFileId();
String resultFileId = project.getSrcAndroidResultFileId();
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileId)) != null) {
String changedByResultTxt = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileId), true);
if (!isEmpty(changedByResultTxt)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedByResultTxt);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// 분석결과서 업로드시 라이선스명(닉네임)이 변경된 사항이 있으면 이력으로 등록한다.
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, csvFileId), true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedLicenseName);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// oss name이 nick name으로 등록되어 있는 경우, 자동치환된 Data를 comment his에 등록
try {
if (getSessionObject(
CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId,
CoConstDef.CD_DTL_COMPONENT_ID_ANDROID)) != null) {
String changedLicenseName = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(),
CoConstDef.SESSION_KEY_NICKNAME_CHANGED, prjId, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID),
true);
if (!isEmpty(changedLicenseName)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(changedLicenseName);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
if (getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId)) != null) {
String chagedOssVersion = (String) getSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_OSS_VERSION_CHANGED, csvFileId), true);
if (!isEmpty(chagedOssVersion)) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(chagedOssVersion);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (comment != null) {
CommentsHistory commentHisBean = new CommentsHistory();
commentHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_IDENTIFICAITON_HIS);
commentHisBean.setReferenceId(prjId);
commentHisBean.setExpansion1("BIN(Android)");
commentHisBean.setContents(comment);
commentHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commentHisBean, false);
}
try {
History h = new History();
h = projectService.work(project);
h.sethAction(CoConstDef.ACTION_CODE_UPDATE);
project = (Project) h.gethData();
h.sethEtc(project.etcStr());
historyService.storeData(h);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
// session 정보 삭제
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_ANDROID, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_ANDROID,
prjId));
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getSingleResult(resultMap);
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "Verification Package File Upload", notes = "Verification > Package File Upload")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {Url.API.FOSSLIGHT_API_PACKAGE_UPLOAD})
public CommonResult ossReportAndroid(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Package FIle", required = true) @RequestPart(required = true) MultipartFile packageFile,
@ApiParam(value = "Verify when file is uploaded (YES : Y, NO : N)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String verifyFlag){
Map<String, Object> resultMap = new HashMap<String, Object>(); // 성공, 실패에 대한 정보를 return하기 위한 map;
T2Users userInfo = userService.checkApiUserAuth(_token); // token이 정상적인 값인지 확인
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap);
String errorMsg = "";
String afterFileSeq = "";
boolean uploadFlag = false;
if (searchFlag) {
Map<String, Object> result = apiProjectService.selectVerificationCheck(prjId);
String useYn = (String) result.get("useYn");
String packageFileSeq = (String) result.get("packageFileSeq").toString();
if (CoConstDef.CD_OPEN_API_PACKAGE_FILE_LIMIT < Integer.parseInt(packageFileSeq)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE, "Up to 3 packaging files can be uploaded.");
}
String filePath = CommonFunction.emptyCheckProperty("packaging.path", "/upload/packaging") + "/" + prjId;
UploadFile packageFileBean = apiFileService.uploadFile(packageFile, filePath); // packagingFile 등록
afterFileSeq = packageFileBean.getRegistSeq();
if (CoConstDef.FLAG_YES.equals(useYn) && CoConstDef.CD_OPEN_API_PACKAGE_FILE_LIMIT >= Integer.parseInt(packageFileSeq)) {
// packaging File comment
String uploadComment = "Packaging file, "+packageFileBean.getOriginalFilename()+", was uploaded by "+userInfo.getUserId()+". <br>";
paramMap = new HashMap<String, Object>();
paramMap.put("prjId", prjId);
paramMap.put("packageFileId", packageFileBean.getRegistSeq());
paramMap.put("packageFileSeq", packageFileSeq);
apiProjectService.updatePackageFile(paramMap);
CommentsHistory commHisBean = new CommentsHistory();
commHisBean.setReferenceDiv(CoConstDef.CD_DTL_COMMENT_PACKAGING_HIS);
commHisBean.setReferenceId(prjId);
commHisBean.setContents(uploadComment);
commHisBean.setLoginUserName(userInfo.getUserId());
commentService.registComment(commHisBean);
errorMsg = null; // 정상적으로 처리됨.
uploadFlag = true;
} else {
if (!CoConstDef.FLAG_YES.equals(useYn)) {
errorMsg = "delete project"; // 삭제된 project
}
}
} else {
errorMsg = "Authrization Issue"; // 해당 사용자 권한으로는 등록할 project가 없음
}
try {
String emailType = isEmpty(errorMsg) ? CoConstDef.CD_MAIL_PACKAGING_UPLOAD_SUCCESS : CoConstDef.CD_MAIL_PACKAGING_UPLOAD_FAILURE;
CoMail mailBean = new CoMail(emailType);
mailBean.setParamPrjId(prjId);
mailBean.setParamExpansion1(packageFile.getOriginalFilename()); // packaging file name
mailBean.setParamExpansion2(errorMsg); // error message
mailBean.setToIds(new String[] { userInfo.getUserId() });
mailBean.setLoginUserName(userInfo.getUserId());
mailBean.setLoginUserRole(userInfo.getAuthority());
CoMailManager.getInstance().sendMail(mailBean);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// after upload complete, verify
if ("Y".equals(verifyFlag) && uploadFlag) {
try {
Map<String, Object> file = new HashMap<>();
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> resMap = null;
List<String> fileSeqs = apiProjectService.getPackageFileList(prjId);
map.put("prjId", prjId);
map.put("fileSeqs", fileSeqs);
String packagingComment = apiProjectService.setClearFiles(map);
map.put("packagingComment", packagingComment);
Map<String, Object> project = new HashMap<>();
project.put("prjId", prjId);
List<Map<String, Object>> list = apiProjectService.getVerifyOssList(project);
list = apiProjectService.serMergeGridData(list);
List<String> filePaths = new ArrayList<String>();
List<String> componentsList = new ArrayList<String>();
for (Map<String, Object> ossComponents : list) {
componentsList.add(Integer.toString((int) ossComponents.get("componentId")));
filePaths.add((String) ossComponents.get("filePath"));
}
map.put("gridFilePaths", filePaths);
map.put("gridComponentIds", componentsList);
boolean isChangedPackageFile = apiProjectService.getChangedPackageFile(prjId, fileSeqs);
int seq = 1;
map.put("packagingFileIdx", seq);
map.put("isChangedPackageFile", isChangedPackageFile);
for (String fileSeq : fileSeqs) {
map.put("fileSeq", fileSeq);
map.put("packagingFileIdx", seq++);
map.put("isChangedPackageFile", isChangedPackageFile);
result.add(apiProjectService.processVerification(map, file, project));
}
resMap = result.get(0);
if (fileSeqs.size() > 1){
resMap.put("verifyValid", result.get(result.size()-1).get("verifyValid"));
resMap.put("fileCounts", result.get(result.size()-1).get("fileCounts"));
}
apiProjectService.updateVerifyFileCount((ArrayList<String>) resMap.get("verifyValid"));
apiProjectService.updateVerifyFileCount((HashMap<String,Object>) resMap.get("fileCounts"));
}catch(Exception e) {
log.error(e.getMessage(), e);
}
}
return responseService.getSingleResult(resultMap);
}
@ApiOperation(value = "Project Add Watcher", notes = "Project Add Watcher")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_PROJECT_ADD_WATCHER})
public CommonResult addPrjWatcher(
@RequestHeader String _token,
@ApiParam(value = "Project Id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Watcher Email", required = true) @RequestParam(required = true) String[] emailList){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<>();
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> prjIdList = new ArrayList<String>();
prjIdList.add(prjId);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjIdList);
paramMap.put("ossReportFlag", CoConstDef.FLAG_NO);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiProjectService.existProjectCnt(paramMap);
if (searchFlag) {
if (emailList != null) {
for (String email : emailList) {
boolean ldapCheck = false;
if (ldapCheckFlag) {
ldapCheck = apiProjectService.existLdapUserToEmail(email);
} else {
ldapCheck = true;
}
if (ldapCheck) {
boolean watcherFlag = apiProjectService.existsWatcherByEmail(prjId, email);
if (watcherFlag) {
Map<String, Object> param = new HashMap<>();
param.put("prjId", prjId);
param.put("division", "");
param.put("userId", "");
param.put("prjEmail", email);
apiProjectService.insertWatcher(param);
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
break;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE;
break;
}
}
if (!errorCode.equals(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE)
&& !errorCode.equals(CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE)) {
return responseService.getSingleResult(resultMap);
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getFailResult(errorCode, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
@ApiOperation(value = "Project Not Applicable", notes = "Project Not Applicable")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {Url.API.FOSSLIGHT_API_PROJECT_NOT_APPLICABLE})
public CommonResult prjNotApplicable(
@RequestHeader String _token,
@ApiParam(value = "Project Id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Tab Flag (3rd, BIN, SRC)", required = true, allowableValues = "3rd,SRC,BIN") @RequestParam(required = true) String tabFlag){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<>();
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
try {
Map<String, Object> projectDetailMap = apiProjectService.selectProjectMaster(prjId);
String status = (String) projectDetailMap.get("status");
String identificationStatus = (String) projectDetailMap.get("identificationStatus");
String creator = (String) projectDetailMap.get("creator");
String reviewer = (String) projectDetailMap.get("reviewer");
boolean searchFlag = status.equals(CoConstDef.CD_DTL_PROJECT_STATUS_DROP) || status.equals(CoConstDef.CD_DTL_PROJECT_STATUS_COMPLETE) || identificationStatus.equals(CoConstDef.CD_DTL_IDENTIFICATION_STATUS_CONFIRM) ? false : true;
if (searchFlag) {
String email = userInfo.getEmail();
boolean authFlag = false;
if (creator.equals(userInfo.getUserId()) || reviewer.equals(userInfo.getUserId()) || userInfo.getAuthority().equals("ROLE_ADMIN") || !apiProjectService.existsWatcherByEmail(prjId, email)) {
authFlag = true;
}
if (authFlag) {
Map<String, Object> param = new HashMap<>();
param.put("prjId", prjId);
param.put("referenceId", prjId);
switch (tabFlag.toUpperCase()) {
case "3RD" :
param.put("referenceDiv", CoConstDef.CD_DTL_COMPONENT_ID_PARTNER);
param.put("identificationSubStatusPartner", CoConstDef.FLAG_NO);
break;
case "SRC" :
param.put("referenceDiv", CoConstDef.CD_DTL_COMPONENT_ID_SRC);
param.put("identificationSubStatusSrc", CoConstDef.FLAG_NO);
break;
case "BIN" :
param.put("referenceDiv", CoConstDef.CD_DTL_COMPONENT_ID_BIN);
param.put("identificationSubStatusBin", CoConstDef.FLAG_NO);
break;
}
apiProjectService.updateSubStatus(param);
return responseService.getSingleResult(resultMap);
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getFailResult(errorCode, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
}
| 86,000 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiVulnerabilityController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiVulnerabilityController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.API;
import oss.fosslight.service.ApiVulnerabilityService;
import oss.fosslight.service.T2UserService;
@Api(tags = {"4. Vulnerability"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
public class ApiVulnerabilityController extends CoTopComponent {
/** The response service. */
private final ResponseService responseService;
/** The user service. */
private final T2UserService userService;
private final ApiVulnerabilityService apiVulnerabilityService;
@ApiOperation(value = "Search Vulnerability Info", notes = "NVD Data 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_VULNERABILITY_DATA})
public CommonResult getVulnerabilityData(
@RequestHeader String _token,
@ApiParam(value = "OSS name", required = false) @RequestParam(required = false) String ossName,
@ApiParam(value = "OSS version", required = false) @RequestParam(required = false) String ossVersion,
@ApiParam(value = "CVE_ID", required = false) @RequestParam(required = false) String cveId) {
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
// ossName과 cveId 둘 다 입력하지 않을 경우 에러 처리
if (isEmpty(ossName) && isEmpty(cveId)) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
if (isEmpty(ossVersion)) { // ossVersion을 입력하지 않을 경우 전체 검색으로 처리함.
ossVersion = "-";
}
List<Map<String, Object>> content = apiVulnerabilityService.selectNvdList(ossName, ossVersion, cveId);
if (content.size() > 0) {
resultMap.put("content", content);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Search Vulnerability Max Score Info", notes = "NVD Max Score Data 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_VULNERABILITY_MAX_DATA})
public CommonResult getVulnerabilityMaxData(
@RequestHeader String _token,
@ApiParam(value = "OSS name", required = true) @RequestParam(required = true) String ossName,
@ApiParam(value = "OSS version", required = false) @RequestParam(required = false) String ossVersion) {
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
if (isEmpty(ossVersion)) { // ossVersion을 입력하지 않을 경우 전체 검색으로 처리함.
ossVersion = "-";
}
List<Map<String, Object>> content = apiVulnerabilityService.selectMaxScoreNvdInfo(ossName, ossVersion);
if (content.size() > 0) {
resultMap.put("content", content);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
}
| 4,659 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiOssController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiOssController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.Url.API;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.service.ApiOssService;
import oss.fosslight.service.OssService;
import oss.fosslight.service.T2UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import oss.fosslight.domain.T2Users;
import java.lang.reflect.Type;
import org.apache.jena.ext.com.google.common.reflect.TypeToken;
@Api(tags = {"1. OSS & License"})
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping(value = "/api/v1")
public class ApiOssController extends CoTopComponent {
private final ResponseService responseService;
private final T2UserService userService;
private final ApiOssService apiOssService;
private final OssService ossService;
@ApiOperation(value = "Search OSS List", notes = "OSS 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_OSS_SEARCH})
public CommonResult getOssInfo(
@RequestHeader String _token,
@ApiParam(value = "OSS Name", required = true) @RequestParam(required = true) String ossName,
@ApiParam(value = "OSS Version", required = false) @RequestParam(required = false) String ossVersion){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
try {
paramMap.put("ossName", ossName);
paramMap.put("ossVersion", ossVersion);
List<Map<String, Object>> content = apiOssService.getOssInfo(paramMap);
if (content.size() > 0) {
resultMap.put("content", content);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Search OSS Info by downloadLocation", notes = "downloadLocation별 OSS Info 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_DOWNLOADLOCATION_SEARCH})
public CommonResult getOssInfoByDownloadLocation(
@RequestHeader String _token,
@ApiParam(value = "Download Location", required = true) @RequestParam(required = true) String downloadLocation){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
List<Map<String, Object>> content = apiOssService.getOssInfoByDownloadLocation(downloadLocation);
if (content.size() > 0) {
resultMap.put("content", content);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Search License Info", notes = "License Info 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_LICENSE_SEARCH})
public CommonResult getLicenseInfo(
@RequestHeader String _token,
@ApiParam(value = "License Name", required = true) @RequestParam(required = true) String licenseName){
// 사용자 인증
userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
List<Map<String, Object>> content = apiOssService.getLicenseInfo(licenseName);
if (content.size() > 0) {
resultMap.put("content", content);
}
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "Register New OSS", notes = "신규 OSS 등록")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {API.FOSSLIGHT_API_OSS_REGISTER})
public CommonResult registerOss(
@RequestHeader String _token,
@ApiParam(value = "OSS Master", required = true) @RequestBody(required = true) OssMaster ossMaster) {
if (userService.isAdmin(_token)) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
resultMap = ossService.saveOss(ossMaster);
resultMap = ossService.sendMailForSaveOss(resultMap);
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
}
| 6,529 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiSelfCheckController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiSelfCheckController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.API;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.T2Users;
import oss.fosslight.domain.UploadFile;
import oss.fosslight.service.ApiFileService;
import oss.fosslight.service.ApiProjectService;
import oss.fosslight.service.ApiSelfCheckService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.SelfCheckService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.ExcelDownLoadUtil;
import oss.fosslight.util.ExcelUtil;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
@Api(tags = {"5. SelfCheck"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
public class ApiSelfCheckController extends CoTopComponent {
@Resource private Environment env;
private String RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX;
@PostConstruct
public void setResourcePathPrefix(){
RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX = CommonFunction.emptyCheckProperty("export.template.path", "/template");
}
private boolean ldapCheckFlag = CoConstDef.FLAG_YES.equals(avoidNull(CommonFunction.getProperty("ldap.check.flag"))) ? true : false;
private final Logger log = LoggerFactory.getLogger(getClass());
private final ResponseService responseService;
private final T2UserService userService;
private final ApiSelfCheckService apiSelfCheckService;
private final ApiFileService apiFileService;
private final ApiProjectService apiProjectService;
private final SelfCheckService selfCheckService;
private final FileService fileService;
@ApiOperation(value = "Create SelfCheck", notes = "SelfCheck 생성")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_SELFCHECK_CREATE})
public CommonResult createSelfCheck(
@RequestHeader String _token,
@ApiParam(value = "Project Name", required = true) @RequestParam(required = true) String prjName,
@ApiParam(value = "Project Version", required = false) @RequestParam(required = false) String prjVersion){
// 사용자 인증
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> result = new HashMap<String, Object>();
try {
int createCnt = apiSelfCheckService.getCreateProjectCnt(userInfo.getUserId());
if (CoConstDef.CD_OPEN_API_CREATE_PROJECT_LIMIT > createCnt) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("prjName", prjName);
paramMap.put("prjVersion", avoidNull(prjVersion, ""));
paramMap.put("loginUserName", userInfo.getUserId());
result = apiSelfCheckService.createSelfCheck(paramMap);
String prjId = (String) result.get("prjId");
if (isEmpty(prjId)) {
throw new Exception(); // parameter Error -> create Failure
}
} else {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_CREATE_OVERFLOW_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_CREATE_OVERFLOW_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getSingleResult(result);
}
@SuppressWarnings("unchecked")
@ApiOperation(value = "SelfCheck OSS Report", notes = "SelfCheck > oss report")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {API.FOSSLIGHT_API_OSS_REPORT_SELFCHECK})
public CommonResult ossReportSelfCheck(
@RequestHeader String _token,
@ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "OSS Report > sheetName : 'Start with Self-Check, SRC or BIN '", required = false) @RequestPart(required = false) MultipartFile ossReport,
@ApiParam(value = "Reset Flag (YES : Y, NO : N, Default : Y)", required = false, allowableValues = "Y,N") @RequestParam(required = false) String resetFlag,
@ApiParam(value = "Sheet Names", required = false) @RequestParam(required = false) String sheetNames) {
T2Users userInfo = userService.checkApiUserAuth(_token);
try {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjId);
boolean searchFlag = apiSelfCheckService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (!searchFlag) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE));
}
String oldFileId = "";
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
Map<String, Object> prjInfo = apiSelfCheckService.selectProjectMaster(prjId);
if (prjInfo.get("srcCsvFileId") != null) {
oldFileId = String.valueOf((int) prjInfo.get("srcCsvFileId"));
}
}
if (ossReport == null) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
UploadFile bean = null;
if (!isEmpty(oldFileId)) {
bean = apiFileService.uploadFile(ossReport, null, oldFileId);
} else {
bean = apiFileService.uploadFile(ossReport); // file 등록 처리 이후 upload된 file정보를 return함.
}
List<UploadFile> list = new ArrayList<UploadFile>();
list.add(bean);
List<Object> checkFileLimit = null;
if (bean.getFileExt().contains("csv")) {
checkFileLimit = CommonFunction.checkCsvFileLimit(list);
} else {
checkFileLimit = CommonFunction.checkXlsxFileLimit(list);
}
if (checkFileLimit != null && checkFileLimit.contains("FILE_SIZE_LIMIT_OVER")) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
}
// if (ossReport.getOriginalFilename().contains("xls") // 확장자 xls, xlsx, xlsm 허용
// && CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT > bean.getSize()) { // file size 5MB 이하만 허용.
if (CoConstDef.CD_XLSX_UPLOAD_FILE_SIZE_LIMIT <= bean.getSize()) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_SIZEOVER_MESSAGE));
}
List<String> sheetList = new ArrayList<>();
boolean sheetNamesEmptyFlag = isEmpty(sheetNames) ? true : false;
if (sheetNamesEmptyFlag) {
List<Object> sheets = ExcelUtil.getSheetNames(list, CommonFunction.emptyCheckProperty("upload.path", "/upload"));
for (Object obj : sheets) {
Map<String, Object> sheetMap = (Map<String, Object>) obj;
if (sheetMap.containsKey("name")) {
sheetList.add((String) sheetMap.get("name"));
}
}
} else {
if (sheetNames.contains(",")) {
for (String sheetName : sheetNames.split(",")) {
if (!isEmpty(sheetName.trim())) sheetList.add(sheetName.trim());
}
} else {
sheetList.add(sheetNames);
}
}
String[] sheet = sheetList.toArray(new String[sheetList.size()]);
Map<String, Object> rtnMap = null;
List<ProjectIdentification> ossComponentList = new ArrayList<>();
List<List<ProjectIdentification>> ossComponentsLicenseList = new ArrayList<>();
for (String sheetNm : sheetList) {
Map<String, Object> result = apiProjectService.getSheetData(bean, prjId, sheetNm, sheet, sheetNamesEmptyFlag);
Map<String, Object> resultMap = getSheetDataResult(result);
if (!resultMap.isEmpty()) {
rtnMap = resultMap;
if (rtnMap.containsKey(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE)) {
rtnMap = null;
continue;
} else if (rtnMap.containsKey("ossComponents")) {
ossComponentList.addAll((List<ProjectIdentification>) rtnMap.get("ossComponents"));
List<List<ProjectIdentification>> ossComponentsLicenses = (List<List<ProjectIdentification>>) rtnMap.get("ossComponentsLicense");
if (!ossComponentsLicenses.isEmpty()) {
ossComponentsLicenseList.addAll(ossComponentsLicenses);
}
} else {
break;
}
}
}
if (rtnMap.containsKey("validError")) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_DATA_VALIDERROR_MESSAGE));
}
if (!ossComponentList.isEmpty()) {
rtnMap = null;
if (CoConstDef.FLAG_NO.equals(avoidNull(resetFlag))) {
apiSelfCheckService.getIdentificationGridList(prjId, CoConstDef.CD_DTL_SELF_COMPONENT_ID, ossComponentList, ossComponentsLicenseList);
}
Project project = new Project();
project.setPrjId(prjId);
project.setSrcCsvFileId(bean.getRegistFileId()); // set file id
selfCheckService.registSrcOss(ossComponentList, ossComponentsLicenseList, project);
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.CD_DTL_COMPONENT_ID_SRC, prjId));
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_PROJECT_SRC, prjId));
}
return responseService.getSingleResult(rtnMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE,
CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> getSheetDataResult(Map<String, Object> result) {
Map<String, Object> rtnMap = new HashMap<>();
String errorMsg = "";
if (result.containsKey("errorMsg")) {
errorMsg = (String) result.get("errorMsg");
}
if (!isEmpty(errorMsg) && errorMsg.toUpperCase().startsWith("THERE ARE NO OSS LISTED")) {
rtnMap.put(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE));
return rtnMap;
}
if (!isEmpty(errorMsg)) {
rtnMap.put("errorMessage", errorMsg);
}
List<ProjectIdentification> ossComponents = (List<ProjectIdentification>) result.get("ossComponents");
List<List<ProjectIdentification>> ossComponentsLicense = (List<List<ProjectIdentification>>) result.get("ossComponentLicense");
if (ossComponents == null || ossComponents.isEmpty()) {
rtnMap.put(CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_FILE_DATA_EMPTY_MESSAGE));
return rtnMap;
}
T2CoProjectValidator pv = new T2CoProjectValidator();
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setValidLevel(pv.VALID_LEVEL_BASIC);
pv.setAppendix("mainList", ossComponents); // sub grid
pv.setAppendix("subList", ossComponentsLicense);
T2CoValidationResult vr = pv.validate(new HashMap<>());
if (!vr.isValid()) {
rtnMap.put("validError", "validError");
} else {
rtnMap.put("ossComponents", ossComponents);
rtnMap.put("ossComponentsLicense", ossComponentsLicense != null ? ossComponentsLicense : new ArrayList<ProjectIdentification>());
}
return rtnMap;
}
@ApiOperation(value = "SelfCheck Export", notes = "SelfCheck > Export")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@PostMapping(value = {API.FOSSLIGHT_API_EXPORT_SELFCHECK})
public ResponseEntity<FileSystemResource> selfCheckExport(@RequestHeader String _token, @ApiParam(value = "Project id", required = true) @RequestParam(required = true) String prjId){
String downloadId = "";
T2File fileInfo = new T2File();
try {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjId);
boolean searchFlag = apiSelfCheckService.existProjectCnt(paramMap); // 조회가 안된다면 권한이 없는 project id를 입력함.
if (searchFlag) {
downloadId = ExcelDownLoadUtil.getExcelDownloadId("selfReport", prjId, RESOURCE_PUBLIC_DOWNLOAD_EXCEL_PATH_PREFIX);
fileInfo = fileService.selectFileInfo(downloadId);
return excelToResponseEntity(fileInfo.getLogiPath() + fileInfo.getLogiNm(), fileInfo.getOrigNm());
} else {
return null;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
@ApiOperation(value = "SelfCheck Add Watcher", notes = "SelfCheck Add Watcher")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_SELFCHECK_ADD_WATCHER})
public CommonResult addPrjWatcher(
@RequestHeader String _token,
@ApiParam(value = "Project Id", required = true) @RequestParam(required = true) String prjId,
@ApiParam(value = "Watcher Email", required = true) @RequestParam(required = true) String[] emailList){
Map<String, Object> resultMap = new HashMap<>();
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
try {
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("prjId", prjId);
boolean searchFlag = apiSelfCheckService.existProjectCnt(paramMap);
if (searchFlag) {
if (emailList != null) {
for (String email : emailList) {
boolean ldapCheck = false;
if (ldapCheckFlag) {
ldapCheck = apiProjectService.existLdapUserToEmail(email);
} else {
ldapCheck = true;
}
if (ldapCheck) {
boolean watcherFlag = apiSelfCheckService.existsWatcherByEmail(prjId, email);
if (watcherFlag) {
Map<String, Object> param = new HashMap<>();
param.put("prjId", prjId);
param.put("division", "");
param.put("userId", "");
param.put("email", email);
apiSelfCheckService.insertWatcher(param);
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
break;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE;
break;
}
}
if (!errorCode.equals(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE)
&& !errorCode.equals(CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE)) {
return responseService.getSingleResult(resultMap);
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getFailResult(errorCode, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
}
| 17,925 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiPartnerController.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/controller/v1/ApiPartnerController.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.controller.v1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import oss.fosslight.CoTopComponent;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.common.Url.API;
import oss.fosslight.domain.T2Users;
import oss.fosslight.service.ApiPartnerService;
import oss.fosslight.service.T2UserService;
@Api(tags = {"2. 3rd Party"})
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/api/v1")
public class ApiPartnerController extends CoTopComponent {
private boolean ldapCheckFlag = CoConstDef.FLAG_YES.equals(avoidNull(CommonFunction.getProperty("ldap.check.flag"))) ? true : false;
private final ResponseService responseService;
private final T2UserService userService;
private final ApiPartnerService apiPartnerService;
protected static final Logger log = LoggerFactory.getLogger("DEFAULT_LOG");
@ApiOperation(value = "3rd Party Search", notes = "3rd party 조회")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_PARTNER_SEARCH})
public CommonResult getVulnerabilityData(
@RequestHeader String _token,
@ApiParam(value = "3rd Party ID List", required = false) @RequestParam(required = false) String[] partnerIdList,
@ApiParam(value = "Division", required = false) @RequestParam(required = false) String division,
@ApiParam(value = "Create Date (Format: fromDate-toDate > yyyymmdd-yyyymmdd)", required = false) @RequestParam(required = false) String createDate,
@ApiParam(value = "Status (PROG:progress, REQ:Request, REV:Review, CONF:Confirm)", required = false, allowableValues = "PROG,REQ,REV,CONF") @RequestParam(required = false) String status,
@ApiParam(value = "Update Date (Format: fromDate-toDate > yyyymmdd-yyyymmdd)", required = false) @RequestParam(required = false) String updateDate,
@ApiParam(value = "Creator", required = false) @RequestParam(required = false) String creator){
// 사용자 인증
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
try {
CommonFunction.splitDate(createDate, paramMap, "-", "createDate");
CommonFunction.splitDate(updateDate, paramMap, "-", "updateDate");
// paramMap.put("userRole", userInfo.getAuthority());
paramMap.put("creator", creator);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("division", division);
paramMap.put("status", status);
paramMap.put("partnerIdList", partnerIdList);
try {
resultMap = apiPartnerService.getPartnerMasterList(paramMap);
return responseService.getSingleResult(resultMap);
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
}
@ApiOperation(value = "3rd Party Add Watcher", notes = "3rd Party Add Watcher")
@ApiImplicitParams({
@ApiImplicitParam(name = "_token", value = "token", required = true, dataType = "String", paramType = "header")
})
@GetMapping(value = {API.FOSSLIGHT_API_PARTNER_ADD_WATCHER})
public CommonResult addPrjWatcher(
@RequestHeader String _token,
@ApiParam(value = "3rd Party ID", required = true) @RequestParam(required = true) String partnerId,
@ApiParam(value = "Watcher Email", required = true) @RequestParam(required = true) String[] emailList){
T2Users userInfo = userService.checkApiUserAuth(_token);
Map<String, Object> resultMap = new HashMap<>();
String errorCode = CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE; // Default error message
try {
Map<String, Object> paramMap = new HashMap<>();
List<String> partnerIdList = new ArrayList<String>();
partnerIdList.add(partnerId);
String[] partnerIds = partnerIdList.toArray(new String[partnerIdList.size()]);
paramMap.put("userId", userInfo.getUserId());
paramMap.put("userRole", userRole(userInfo));
paramMap.put("partnerIdList", partnerIds);
paramMap.put("readOnly", CoConstDef.FLAG_NO);
boolean searchFlag = apiPartnerService.existPartnertCnt(paramMap);
if (searchFlag) {
if (emailList != null) {
for (String email : emailList) {
boolean ldapCheck = false;
if (ldapCheckFlag) {
ldapCheck = apiPartnerService.existLdapUserToEmail(email);
} else {
ldapCheck = true;
}
if (ldapCheck) {
boolean watcherFlag = apiPartnerService.existsWatcherByEmail(partnerId, email);
if (watcherFlag) {
Map<String, Object> param = new HashMap<>();
param.put("partnerId", partnerId);
param.put("division", "");
param.put("userId", "");
param.put("partnerEmail", email);
apiPartnerService.insertWatcher(param);
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
break;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE;
break;
}
}
if (!errorCode.equals(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE)
&& !errorCode.equals(CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE)) {
return responseService.getSingleResult(resultMap);
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE;
}
} else {
errorCode = CoConstDef.CD_OPEN_API_PERMISSION_ERROR_MESSAGE;
}
} catch (Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_PARAMETER_ERROR_MESSAGE));
}
return responseService.getFailResult(errorCode, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, errorCode));
}
}
| 7,239 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SingleResult.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/entity/SingleResult.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SingleResult<T> extends CommonResult {
private T data;
} | 262 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CommonResult.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/entity/CommonResult.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CommonResult {
@ApiModelProperty(value = "응답 성공여부 : true/false")
private boolean success;
@ApiModelProperty(value = "응답 코드 번호 : > 0 정상, < 0 비정상")
private String code;
@ApiModelProperty(value = "응답 메시지")
private String msg;
}
| 547 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ListResult.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/entity/ListResult.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class ListResult<T> extends CommonResult {
private List<T> list;
} | 290 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ResponseService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/service/ResponseService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.service;
import java.util.List;
import org.springframework.stereotype.Service;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.entity.ListResult;
import oss.fosslight.api.entity.SingleResult;
@Service
public class ResponseService {
// enum으로 api 요청 결과에 대한 code, message를 정의합니다.
public enum CommonResponse {
/** The success. */
SUCCESS("100", "");
/** The code. */
String code;
/** The msg. */
String msg;
CommonResponse(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
// 단일건 결과를 처리하는 메소드
public <T> SingleResult<T> getSingleResult(T data) {
SingleResult<T> result = new SingleResult<>();
result.setData(data);
setSuccessResult(result);
return result;
}
// 다중건 결과를 처리하는 메소드
public <T> ListResult<T> getListResult(List<T> list) {
ListResult<T> result = new ListResult<>();
result.setList(list);
setSuccessResult(result);
return result;
}
// 성공 결과만 처리하는 메소드
public CommonResult getSuccessResult() {
CommonResult result = new CommonResult();
setSuccessResult(result);
return result;
}
// 실패 결과만 처리하는 메소드
public CommonResult getFailResult(String code, String msg) {
CommonResult result = new CommonResult();
result.setSuccess(false);
result.setCode(code);
result.setMsg(msg);
return result;
}
// 결과 모델에 api 요청 성공 데이터를 세팅해주는 메소드
private void setSuccessResult(CommonResult result) {
result.setSuccess(true);
result.setCode(CommonResponse.SUCCESS.getCode());
result.setMsg(CommonResponse.SUCCESS.getMsg());
}
}
| 2,260 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CUserNotFoundException.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/advice/CUserNotFoundException.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.advice;
public class CUserNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CUserNotFoundException(String msg, Throwable t) {
super(msg, t);
}
public CUserNotFoundException(String msg) {
super(msg);
}
public CUserNotFoundException() {
super();
}
}
| 485 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CCommunicationException.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/advice/CCommunicationException.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.advice;
public class CCommunicationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CCommunicationException(String msg, Throwable t) {
super(msg, t);
}
public CCommunicationException(String msg) {
super(msg);
}
public CCommunicationException() {
super();
}
}
| 489 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CSigninFailedException.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/advice/CSigninFailedException.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.advice;
public class CSigninFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CSigninFailedException(String msg, Throwable t) {
super(msg, t);
}
public CSigninFailedException(String msg) {
super(msg);
}
public CSigninFailedException() {
super();
}
}
| 485 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ExceptionAdvice.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/advice/ExceptionAdvice.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.advice;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.api.entity.CommonResult;
import oss.fosslight.api.service.ResponseService;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
@RequiredArgsConstructor
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
private final ResponseService responseService;
private final MessageSource messageSource;
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult defaultException(HttpServletRequest request, Exception e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_UNKNOWN_ERROR_MESSAGE));
}
@ExceptionHandler(CUserNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult userNotFound(HttpServletRequest request, CUserNotFoundException e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_USER_NOTFOUND_MESSAGE));
}
@ExceptionHandler(CSigninFailedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult emailSigninFailed(HttpServletRequest request, CSigninFailedException e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_SIGNIN_FAILED_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_SIGNIN_FAILED_MESSAGE));
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public CommonResult accessDeniedException(HttpServletRequest request, AccessDeniedException e) {
return responseService.getFailResult(getMessage("accessDenied.code"), getMessage("accessDenied.msg"));
}
@ExceptionHandler(CCommunicationException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CommonResult communicationException(HttpServletRequest request, CCommunicationException e) {
return responseService.getFailResult(CoConstDef.CD_OPEN_API_COMMUNICATION_ERROR_MESSAGE
, CoCodeManager.getCodeString(CoConstDef.CD_OPEN_API_MESSAGE, CoConstDef.CD_OPEN_API_COMMUNICATION_ERROR_MESSAGE));
}
// org.apache.catalina.connector.ClientAbortException: java.io.IOException
@ExceptionHandler(ClientAbortException.class)
public void clientAbortException(HttpServletRequest request, ClientAbortException e) {
final String message = "ClientAbortException generated by request {} {} from remote address {} with X-FORWARDED-FOR {}";
final String headerXFF = request.getHeader("X-FORWARDED-FOR");
log.debug(message, request.getMethod(), request.getRequestURL(), request.getRemoteAddr(), headerXFF);
}
private String getMessage(String code) {
return getMessage(code, null);
}
private String getMessage(String code, Object[] args) {
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}
| 3,887 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiControllerAspect.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/api/aop/ApiControllerAspect.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.api.aop;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.config.AppConstBean;
@Aspect
@Component
@Slf4j
public class ApiControllerAspect {
private final String convertParamJson = CoConstDef.FLAG_YES;
@Around("execution(* "+ AppConstBean.APP_COMPONENT_SCAN_PACKAGE
+ ".api.controller..*.*(..)) && @annotation(org.springframework.web.bind.annotation.GetMapping)")
public Object getLogging(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = // 5
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String params = "";
Map<String, String[]> paramMap = request.getParameterMap();
if (!paramMap.isEmpty()) {
params = " [" + paramMapToString(paramMap) + "]";
}
long start = System.currentTimeMillis();
try {
return pjp.proceed(pjp.getArgs()); // 6
} finally {
long end = System.currentTimeMillis();
log.info("IP: {}, method: {}, token: {} {}ms, URL: {}, params: {}", request.getRemoteHost(),request.getMethod(), request.getHeader("_token"),
end - start, request.getRequestURI(), params);
}
}
@Around("execution(* "+ AppConstBean.APP_COMPONENT_SCAN_PACKAGE
+ ".api.controller..*.*(..)) && @annotation(org.springframework.web.bind.annotation.PostMapping)")
public Object postLogging(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = // 5
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
Map<String, String[]> paramMap = request.getParameterMap();
String params = "";
if (!paramMap.isEmpty()) {
params = " [" + paramMapToString(paramMap) + "]";
}
long start = System.currentTimeMillis();
try {
return pjp.proceed(pjp.getArgs()); // 6
} finally {
long end = System.currentTimeMillis();
log.info("IP: {}, method: {}, token: {} {}ms, URL: {}, params: {}", request.getRemoteHost(),request.getMethod(), request.getHeader("_token"),
end - start, request.getRequestURI(), params);
}
}
private String paramMapToString(Map<String, String[]> paramMap) {
if (CoConstDef.FLAG_YES.equals(convertParamJson)) {
JSONObject jsonObject = new JSONObject();
List<String> ignoreParamList = new ArrayList<>();
for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
String key = entry.getKey();
if (ignoreParamList.contains(key)) {
continue;
}
String[] value = entry.getValue();
try {
jsonObject.put(key, Arrays.toString(value));
} catch (JSONException e) {
//e.printStackTrace();
}
}
return jsonObject.toString();
} else {
return paramMap.entrySet().stream()
.map(entry -> String.format("%s -> (%s)", entry.getKey(), Joiner.on(",").join(entry.getValue())))
.collect(Collectors.joining(", "));
}
}
}
| 3,629 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoValidMap.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/T2CoValidMap.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation;
import java.util.HashMap;
@SuppressWarnings("serial")
public class T2CoValidMap<K,V> extends HashMap<K, V> {
public V get(Object o){
V v = (V)super.get(o);
if (v == null) {
throw new IllegalArgumentException("key " + o + " doesn't exist");
}
return v;
}
public V getEvenNull(Object o){
return (V)super.get(o);
}
} | 560 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoValidationResult.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/T2CoValidationResult.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.util.StringUtil;
public class T2CoValidationResult {
/** The err map. */
private Map<String,String> errMap = null;
/** The rule map. */
private Map<String,Map<String,String>> ruleMap = null;
/** The message map. */
private Map<String,String> messageMap = null;
/** The data map. */
private Map<String,String> dataMap = null;
/** The valid data map. */
private Map<String,String> validDataMap = null;
/** The default format. */
private final String DEFAULT_FORMAT = "<div class=\"errorMsg\">{0}</div>";
/** The format. */
private String format = DEFAULT_FORMAT;
/** The diff map. */
private Map<String,String> diffMap = null;
private Map<String,String> infoMap = null;
public T2CoValidationResult(Map<String, Map<String,String>> ruleMap, Map<String, String> messageMap){
this.ruleMap = ruleMap;
this.messageMap = messageMap;
this.validDataMap = new T2CoValidMap<>();
}
public void setErrorCodeMap(Map<String, String> map){
errMap = map;
}
public Map<String, String> getErrorCodeMap(){
if (errMap == null){
return new HashMap<String, String>();
}else{
return errMap;
}
}
public Map<String, String> getWarningCodeMap(){
if (diffMap == null){
return new HashMap<String, String>();
}else{
return diffMap;
}
}
public Map<String, String> getInfoCodeMap(){
if (infoMap == null){
return new HashMap<String, String>();
}else{
return infoMap;
}
}
public void setDataMap(Map<String,String> map){
dataMap = map;
}
public Map<String, String> getDataMap(){
return dataMap == null ? new HashMap<String,String>() : dataMap;
}
void validate(String key){
if (dataMap == null) {
throw new IllegalStateException("no dataMap");
}
if (dataMap.containsKey(key)) {
validDataMap.put(key, dataMap.get(key));
} else {
throw new IllegalArgumentException("invalid key. Entry not found in dataMap.");
}
}
public Map<String, String> getValidDataMap(){
if (isValid()){
return validDataMap;
}
return new T2CoValidMap<>();
}
public boolean isValid(){
if (errMap == null) {
throw new IllegalStateException("Not validated yet.");
}
return errMap.isEmpty();
}
public void setFormat(String str){
format = str;
}
public String getValidMessage(String key){
boolean printErrCd = false;
if (errMap == null || !errMap.containsKey(key)){
return "";
}else if (messageMap == null || !messageMap.containsKey(errMap.get(key))){
return errMap.get(key);
}else{
String errCd = errMap.get(key);
String msg;
if (errCd.endsWith(".LENGTH")){
Map<String,String> rule = ruleMap.get(key);
// key에 해당ㅇ하는 rule이 없을 경우
if (rule == null) {
// root key를 기준으로(例 : CARD.1 → CARD)、시쿼스 키를 찾는다
String rootKey = key.replaceFirst("\\.\\d+", "");
rule = ruleMap.get(rootKey);
if (rule == null && key.indexOf(".") > -1) {
rootKey = key.substring(0, key.indexOf("."));
rule = ruleMap.get(rootKey);
}
}
msg = MessageFormat.format(messageMap.get(errCd), T2CoValidator.getLimitLength(rule));
}else{
msg = messageMap.get(errCd);
}
return printErrCd ? (errMap.get(key) + " " + msg) : msg;
}
}
public String format(String str){
if (str == null || "".equals(str)) {
return "";
}
return MessageFormat.format(format, str);
}
public String getFormattedMessage(String key){
return format(getValidMessage(key));
}
public Map<String, String> getFormattedMessageMap(){
if (errMap == null) {
return new HashMap<>();
}
Map<String, String> formatted = new HashMap<>();
Iterator<String> itr = errMap.keySet().iterator();
while (itr.hasNext()){
String key = (String)itr.next();
String camelKey = key;
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
camelKey = StringUtil.convertToCamelCase(camelKey);
}
formatted.put(camelKey, getFormattedMessage(key));
if (!StringUtil.isEmpty(getFormattedMessage(key))) {
formatted.put(camelKey+"Style", "style=\"background:#FEF8F8;border:1px solid #FF0000;\"");
}
}
formatted.put("isValid", isValid() ? "true" : "false");
return formatted;
}
public Map<String, String> getValidMessageMap() {
Map<String, String> messageMap = new HashMap<>();
Iterator<String> itr = errMap.keySet().iterator();
while (itr.hasNext()){
String key = (String)itr.next();
String camelKey = key;
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
if (camelKey.indexOf(".") > -1) {
String _name = StringUtil.convertToCamelCase(camelKey.substring(0, camelKey.indexOf(".")));
String _rowId = camelKey.substring(camelKey.indexOf("."));
camelKey = _name + _rowId;
} else {
camelKey = StringUtil.convertToCamelCase(camelKey);
}
}
messageMap.put(camelKey, getValidMessage(key));
}
messageMap.put("isValid", isValid() ? "true" : "false");
return messageMap;
}
public Map<String, String> getDiffMessageMap() {
Map<String, String> messageMap = new HashMap<>();
Iterator<String> itr = diffMap.keySet().iterator();
while (itr.hasNext()){
String key = (String)itr.next();
String camelKey = key;
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
if (camelKey.indexOf(".") > -1) {
String _name = StringUtil.convertToCamelCase(camelKey.substring(0, camelKey.indexOf(".")));
String _rowId = camelKey.substring(camelKey.indexOf("."));
camelKey = _name + _rowId;
} else {
camelKey = StringUtil.convertToCamelCase(camelKey);
}
}
messageMap.put(camelKey, getDiffMessage(key));
}
messageMap.put("isDiff", isDiff() ? "true" : "false");
return messageMap;
}
public boolean isDiff(){
if (diffMap == null) {
throw new IllegalStateException("Not validated yet.");
}
return diffMap.isEmpty();
}
public String getDiffMessage(String key){
boolean printErrCd = false;
if (diffMap == null || !diffMap.containsKey(key)){
return "";
}else if (messageMap == null || !messageMap.containsKey(diffMap.get(key))){
return diffMap.get(key);
}else{
String errCd = diffMap.get(key);
String msg;
if (errCd.endsWith(".LENGTH")){
Map<String,String> rule = ruleMap.get(key);
// key에 해당ㅇ하는 rule이 없을 경우
if (rule == null) {
// root key를 기준으로(例 : CARD.1 → CARD)、시쿼스 키를 찾는다
String rootKey = key.replaceFirst("\\.\\d+", "");
rule = ruleMap.get(rootKey);
if (rule == null && key.indexOf(".") > -1) {
rootKey = key.substring(0, key.indexOf("."));
rule = ruleMap.get(rootKey);
}
}
msg = MessageFormat.format(messageMap.get(errCd), T2CoValidator.getLimitLength(rule));
}else{
msg = messageMap.get(errCd);
}
return printErrCd ? (diffMap.get(key) + " " + msg) : msg;
}
}
public Map<String, String> getInfoMessageMap() {
Map<String, String> messageMap = new HashMap<>();
Iterator<String> itr = infoMap.keySet().iterator();
while (itr.hasNext()){
String key = (String)itr.next();
String camelKey = key;
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
camelKey = StringUtil.convertToCamelCase(camelKey);
}
messageMap.put(camelKey, getInfoMessage(key));
}
messageMap.put("hasInfo", hasInfo() ? "true" : "false");
return messageMap;
}
public boolean hasInfo(){
if (infoMap == null) {
throw new IllegalStateException("Not validated yet.");
}
return !infoMap.isEmpty();
}
public String getInfoMessage(String key){
boolean printErrCd = false;
if (infoMap == null || !infoMap.containsKey(key)){
return "";
}else if (messageMap == null || !messageMap.containsKey(infoMap.get(key))){
return infoMap.get(key);
}else{
String errCd = infoMap.get(key);
String msg;
if (errCd.endsWith(".LENGTH")){
Map<String,String> rule = ruleMap.get(key);
// key에 해당ㅇ하는 rule이 없을 경우
if (rule == null) {
// root key를 기준으로(例 : CARD.1 → CARD)、시쿼스 키를 찾는다
String rootKey = key.replaceFirst("\\.\\d+", "");
rule = ruleMap.get(rootKey);
if (rule == null && key.indexOf(".") > -1) {
rootKey = key.substring(0, key.indexOf("."));
rule = ruleMap.get(rootKey);
}
}
msg = MessageFormat.format(messageMap.get(errCd), T2CoValidator.getLimitLength(rule));
}else{
msg = messageMap.get(errCd);
}
return printErrCd ? (infoMap.get(key) + " " + msg) : msg;
}
}
public void setDiffCodeMap(Map<String, String> map){
diffMap = map;
}
public void setInfoMap(Map<String, String> map) {
infoMap = map;
}
public boolean isAdminCheck(List<String> adminCheckList) {
Iterator<String> itr = errMap.keySet().iterator();
boolean result = true;
while (itr.hasNext()){
String key = (String)itr.next();
String componentId = key.split("\\.")[1];
if (adminCheckList.indexOf(componentId) == -1) {
result = false;
}
}
return result;
}
} | 12,039 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoValidationConfig.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/T2CoValidationConfig.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import oss.fosslight.CoTopComponent;
import oss.fosslight.config.AppConstBean;
@Component
@PropertySources(value = {@PropertySource(value=AppConstBean.APP_CONFIG_VALIDATION_PROPERTIES)})
public class T2CoValidationConfig extends CoTopComponent {
private static T2CoValidationConfig instance = null;
private static Map<String, Map<String, String>> ruleMap = null;
private static Map<String, Object> ruleAllMap = null;
private static Map<String, String> messageConfigMap = null;
private static Environment env;
@SuppressWarnings("static-access")
@Resource
public void setEnvironment(Environment env) throws IOException {
this.env = env;
init();
}
private final static String RULE_TYPE_DEF = "LENGTH, REQUIRED, FORMAT, COMPOSITE, SPLIT_WHEN_INIT, COPY_WHEN_INIT, USE_SEQUENCE";
public T2CoValidationConfig(){}
private void init() throws IOException{
load();
instance = new T2CoValidationConfig();
}
public static T2CoValidationConfig getInstance(){
if (instance == null){
throw new IllegalStateException("not initialized");
}
return instance;
}
public Map<String, Map<String,String>> getRuleMap(){
return ruleMap;
}
public Map<String, Object> getRuleAllMap(){
return ruleAllMap;
}
public Map<String, String> getMessageConfigMap(){
return messageConfigMap;
}
@SuppressWarnings({ "static-access", "unchecked" })
synchronized private void load() throws IOException{
Map<String, Map<String, String>> ruleMap = new HashMap<>();
Map<String, String> messageConfigMap = new HashMap<>();
List<String> ruleTypeDef = Arrays.asList(RULE_TYPE_DEF.split("\\s*,\\s*"));
Map<String, Object> map = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
for (org.springframework.core.env.PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
if (propertySource instanceof CompositePropertySource
&& propertySource.getName().indexOf("validation") > 0) {
CompositePropertySource cps = (CompositePropertySource) propertySource;
Iterator<org.springframework.core.env.PropertySource<?>> itr = cps.getPropertySources().iterator();
while (itr.hasNext()) {
Map<? extends String, ? extends Object> property = (Map<? extends String, ? extends Object>) itr.next().getSource();
map.putAll(property);
}
}
}
}
for (Object oKey : map.keySet()){
String key = (String)oKey;
if (key.indexOf(".") < 0 ){
continue;
}
String val = (String) map.get(key);
while (val.matches(".*\\$\\{[\\w\\d_]+\\}.*")){
String refKey = val.replaceFirst(".*\\$\\{([\\w\\d]+)\\}.*", "$1");
String refVal = ((String) map.get(key)).replaceAll("\\\\", "\\\\\\\\");//escape 재처리
val = val.replaceAll("\\$\\{" + refKey + "\\}", refVal);
}
//Map에 값추가
if (key.endsWith(".MSG")){
String ruleKey = key.substring(0, key.length() - 4);//.MSG제거
messageConfigMap.put(ruleKey.toUpperCase(), val);
}else{
String ruleKey = key.replaceFirst("(.*?[^\\\\])\\..*", "$1");
String ruleType = key.substring(ruleKey.length() + 1).toUpperCase();
ruleKey = ruleKey.replaceAll("\\\\\\.", "\\.");//.을 escape 해서 제거
if (ruleTypeDef.contains(ruleType)){
Map<String, String> rule = ruleMap.get(ruleKey);
if (rule == null){
rule = new HashMap<>();
ruleMap.put(ruleKey.toUpperCase(), rule);
}
rule.put(ruleType, val);
} else {
//미정의된 rule type(형식 오류)의 경우
throw new IllegalArgumentException("undefined rule-type found in properties:" + ruleType);
}
}
}
this.ruleMap = ruleMap;
this.messageConfigMap = messageConfigMap;
this.ruleAllMap = map;
}
public void reload() throws IOException{
if (instance != null){
instance.load();
}else{
throw new IllegalStateException("not initialized.");
}
}
}
| 5,505 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/T2CoValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.domain.ComBean;
import oss.fosslight.util.StringUtil;
@Slf4j
public abstract class T2CoValidator extends CoTopComponent {
/** The Constant DEFAULT_REQUIRED_MARKER. */
private final static String DEFAULT_REQUIRED_MARKER = "<span style=\"color:#f00\">*</span>";
/** The rule map. */
private Map<String, Map<String, String>> ruleMap = null;
/** The message config map. */
private Map<String, String> messageConfigMap = null;
/** The hint. */
private List<String> hint = new ArrayList<String>(1);
/** The ignore. */
private List<String> ignore = new ArrayList<String>(1);
/** The custom marker. */
private String customMarker = null;
protected T2CoValidator(){
T2CoValidationConfig conf = T2CoValidationConfig.getInstance();
ruleMap = conf.getRuleMap();
messageConfigMap = conf.getMessageConfigMap();
}
public void setHint(String keys){
if (keys != null){
hint = Arrays.asList(keys.split("\\s*,\\s*"));
log.trace("HINT:" + hint);
}
}
public void setIgnore(String keys){
if (keys != null){
ignore = Arrays.asList(keys.split("\\s*,\\s*"));
log.trace("IGNORE:" + ignore);
}
}
public void setRequiredMarker(String maker) {
customMarker = maker;
}
protected String basicValidation(String inputValue, Map<String, String> rule){
return basicValidation(inputValue, rule, false);
}
protected String basicValidation(String inputValue, Map<String, String> rule, boolean ignoreRequired){
String errCd = null;
int limitLength = getLimitLength(rule);
String[] inputs = nvl(inputValue).split("\\t");
for (String input:inputs){
if (!ignoreRequired && isRequired(rule) && isEmpty(input) ){
//필수체크
errCd = "REQUIRED";
}else if ( limitLength < safeLength(input) ){
//길이체크
errCd = "LENGTH";
}else if (
!isEmpty(input) &&
!input.matches(rule.get("FORMAT"))
){
//형식체크
errCd = "FORMAT";
}
if (errCd != null){
break;
}
}
return errCd;
}
private void printDebugLog(String inputValue, String errCd, String ruleKey, String ruleKeySeq){
if (ruleMap != null) {
if (errCd != null) {
Map<String, String> rule = getRule(ruleKey);
log.trace("basic validation for [" + ruleKey + "] ----------------");
log.trace( (isRequired(rule) ? "required" : "optional") + ", limit " + getLimitString(ruleKey) + ", format " + rule.get("FORMAT"));
log.trace(ruleKeySeq + "=" + inputValue + "[error code:" + errCd + "]");
}
} else {
log.debug("ruleMap is null.");
}
}
public T2CoValidationResult validateRequest(Map<String, String> map, ServletRequest request){
return validateRequest(map, request, null);
}
public T2CoValidationResult validateRequest(Map<String, String> map, ServletRequest request, Map<String, String> keyPreMap){
Map<String, String> reqMap = new HashMap<String, String>();
saveRequest(request, reqMap, keyPreMap);
T2CoValidationResult vr = validate(reqMap);
if (map != null){
map.putAll(reqMap);
}
// key prefix 처리 추가
if (keyPreMap != null && !keyPreMap.isEmpty() && !vr.getErrorCodeMap().isEmpty()) {
// Data Key 복원
Map<String, String> errMap = vr.getErrorCodeMap();
Map<String, String> replaceErrMap = new HashMap<>();
for (String key : errMap.keySet()) {
if (key.indexOf("@") > -1) {
String paramName = key.substring(key.indexOf("@")+1);
String restoreKey = key.replaceAll(keyPreMap.get(paramName)+"@", "");
replaceErrMap.put(restoreKey, errMap.get(key));
} else {
replaceErrMap.put(key, errMap.get(key));
}
}
vr.setErrorCodeMap(replaceErrMap);
}
return vr;
}
public T2CoValidationResult validateRequest(ServletRequest request){
return validateRequest(null, request);
}
public T2CoValidationResult validateObject(Map<String, String> map, Object source){
return validateObject(map, source, null);
}
@SuppressWarnings("unchecked")
public T2CoValidationResult validateObject(Map<String, String> map, Object source, String keyPre){
Map<String, String> reqMap = null;
List<String> gridKeys = null;
if (source instanceof List<?>) {
reqMap = new HashMap<>();
gridKeys = new ArrayList<>();
int seqSuffix = 1;
String _gridKey;
for (Object sourceVO : (List<Object>)source) {
_gridKey = avoidNull(((ComBean)sourceVO).getGridId(), ((ComBean)sourceVO).getNo());
if (!isEmpty(_gridKey)) {
gridKeys.add(_gridKey);
}
reqMap.putAll(ConverObjectToMap(sourceVO, seqSuffix++, keyPre));
}
} else {
reqMap = ConverObjectToMap(source, -1, keyPre);
}
if (map != null) {
reqMap.putAll(map);
}
T2CoValidationResult vr = validate(reqMap);
if (!isEmpty(keyPre)) {
//STEP.
//keyPre 변수가 있을시
//validation_properties의 property 중 Prefix@ 형태를 제거한후
//에러맵을 교체한다.
Map<String, String> errMap = vr.getErrorCodeMap();
Map<String, String> replaceErrMap = new HashMap<>();
for (String key : errMap.keySet()) {
replaceErrMap.put(key.replaceAll(keyPre+"@", ""), errMap.get(key));
}
vr.setErrorCodeMap(replaceErrMap);
}
// 시퀀스 번호를 grid key 값으로 치환한다.
if (gridKeys != null && !gridKeys.isEmpty() && !vr.getErrorCodeMap().isEmpty()) {
Map<String, String> errMap = vr.getErrorCodeMap();
Map<String, String> addErrMap = new HashMap<>();
for (String key : errMap.keySet()) {
if (key.indexOf(".") > -1) {
String seqStr = key.substring(key.indexOf(".") +1);
int seq = StringUtil.string2integer(seqStr);
if (gridKeys.size() >= seq) {
addErrMap.put(key.replace("." + seqStr, "." + gridKeys.get(seq -1)), errMap.get(key));
}
}else{
addErrMap.put(key, errMap.get(key));
}
}
//Grid에 대한 에러맵이 존재할 경우 결과에 격납
if (!addErrMap.isEmpty()) {
vr.setErrorCodeMap(addErrMap);
}
}
return vr;
}
public T2CoValidationResult validateObject(Object sourceVO) {
return validateObject(null, sourceVO);
}
public Map<String, String> ConverObjectToMap(Object obj, int seq, String keyPre){
Map<String, String> resultMap = new HashMap<>();
Method[] methods = obj.getClass().getMethods();
for (Method method : methods){
// is getter check
if (!(!method.getName().startsWith("get") || method.getParameterTypes().length != 0
|| void.class.equals(method.getReturnType())
|| !(String.class.equals(method.getReturnType()) || String[].class.equals(method.getReturnType())))) {
Object valueObj = invokeGetter(method.getName(), obj);
if (valueObj != null) {
String key = StringUtil.convertToUnderScore(method.getName().substring(3)).toUpperCase();
if (seq > 0) {
key += "." + Integer.toString(seq);
}
if (valueObj instanceof String[]) {
String tempVal = "";
for (String strVal : (String[]) valueObj) {
if (!isEmpty(tempVal)) {
tempVal += "\t";
}
tempVal += strVal;
}
valueObj = tempVal;
}
if (!isEmpty(keyPre)) {
key = keyPre + "@" + key;
}
resultMap.put(key, (String) valueObj);
}
}
}
return resultMap;
}
private Object invokeGetter(String name, Object obj) {
PropertyDescriptor objPropertyDescriptor;
Object variableValue = null;
try {
if (name.startsWith("get")) {
objPropertyDescriptor = new PropertyDescriptor((String)name.substring(3), obj.getClass());
variableValue = objPropertyDescriptor.getReadMethod() != null ? objPropertyDescriptor.getReadMethod().invoke(obj) : null;
}
} catch (IntrospectionException e) {
//if (log.isDebugEnabled()) {e.printStackTrace();}
} catch (IllegalAccessException e) {
//if (log.isDebugEnabled()) {e.printStackTrace();}
} catch (IllegalArgumentException e) {
//if (log.isDebugEnabled()) {e.printStackTrace();}
} catch (InvocationTargetException e) {
//if (log.isDebugEnabled()) {e.printStackTrace();}
}
return variableValue;
}
public T2CoValidationResult validate(Map<String, String> map){
checkStatus();
//hint에서 설정한 없을 수도 있지만, 반드시 있어야하는 key에 대해서 시스템 오류를 장지하기 위해 임의 추가
{
Iterator<String> itr = hint.iterator();
while (itr.hasNext()){
String mustHave = (String)itr.next();
if (!map.containsKey(mustHave)){
map.put(mustHave, "");
}
}
}
//검증
T2CoValidationResult vr = new T2CoValidationResult(ruleMap, messageConfigMap);
Map<String, String> errMap = new HashMap<String, String>(); // error message
Map<String, String> diffMap = new HashMap<String, String>(); // warning message
Map<String, String> infoMap = new HashMap<String, String>(); // gray로 표시 추가정보 표시용도
vr.setErrorCodeMap(errMap);
vr.setDataMap(map);
vr.setDiffCodeMap(diffMap);
vr.setInfoMap(infoMap);
try{
Iterator<String> itr = ruleMap.keySet().iterator();
while (itr.hasNext()){
String ruleKey = (String)itr.next();
boolean doValidate = false;
Map<String, String> rule = getRule(ruleKey);
List<String> seqSuffix = new ArrayList<String>();
if ("TRUE".equalsIgnoreCase(rule.get("USE_SEQUENCE"))) {
for (int i = 1; map.containsKey(ruleKey + "." + i); i++) {
seqSuffix.add("." + i);
}
} else {
seqSuffix.add("");
}
Iterator<String> itr2 = seqSuffix.iterator();
while (itr2.hasNext()){
String ruleKeySeq = ruleKey + (String)itr2.next(); // 연번 이없는 경우는 ruleKey 와 같음
if (map.containsKey(ruleKeySeq)) {
doValidate = true;
} else if (rule.containsKey("COMPOSITE")) {
StringBuffer buf = new StringBuffer();
String[] comp = parseExp(rule.get("COMPOSITE"));
boolean hasInputKey = false;
boolean hasInputValue = false;
for (int i = 0; i < comp.length; i++){
if (comp[i].matches("'.*'")){
buf.append(comp[i].substring(1,comp[i].length() - 1));
}else{
if (map.containsKey(comp[i])){
doValidate = true;
hasInputKey = true;
String s = map.get(comp[i]);
hasInputValue = hasInputValue || !isEmpty(s);
buf.append(s);
}
}
}
if (hasInputKey){
map.put(ruleKeySeq, hasInputValue ? buf.toString() : "");// COMPSITE로 설정한 값을 추가
}
}
doValidate = (doValidate || this.hint.contains(ruleKey)) && !this.ignore.contains(ruleKey);
if (doValidate){
String errCd = basicValidation(map.get(ruleKeySeq), rule);
if (log.isDebugEnabled()){
printDebugLog(map.get(ruleKeySeq), errCd, ruleKey, ruleKeySeq);
}
if (errCd != null){
errCd = ruleKey + "." + errCd;
errMap.put(ruleKeySeq, errCd);
}else{
vr.validate(ruleKeySeq);
}
}
}
}
} catch(Exception e) {
log.error(e.getMessage());
}
customValidation(map, errMap, diffMap, infoMap);
return vr;
}
protected static int safeLength(String str){
return str == null ? 0 : str.length();
}
static int getLimitLength(Map<String, String> rule){
int maxLength = 0;
try {
maxLength = Integer.parseInt((String)rule.get("LENGTH"));
if (maxLength < 0) {
throw new Exception();
}
} catch(Exception e) {
throw new IllegalArgumentException("rule map has invalid value at 'LENGTH' of " + rule.get("KEY"));
}
return maxLength == 0 ? Integer.MAX_VALUE : maxLength;
}
public void saveRequest(ServletRequest request, Map<String, String> map){
saveRequest(request, map, null);
}
public void saveRequest(ServletRequest request, Map<String, String> map, Map<String, String> keyPreMap){
Enumeration<?> names = request.getParameterNames();
while ( names.hasMoreElements() ){
boolean ignore = false;
String name = (String) names.nextElement();
String value = "";
if (request.getParameterValues(name).length > 1){
String[] vals = request.getParameterValues(name);
Map<String,String> rule = getRule(CoConstDef.VALIDATION_USE_CAMELCASE ? StringUtil.convertToUnderScore(name).toUpperCase() : name);
if (rule != null && "TRUE".equalsIgnoreCase(rule.get("USE_SEQUENCE"))) {
for (int i = 0; i < vals.length; i++){
value = vals[i];
if (i == 0) {
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
name = StringUtil.convertToUnderScore(name).toUpperCase();
}
String _val = "";
for (int subIdx = 0; subIdx < vals.length; subIdx++){
_val = (subIdx == 0 ? "" : value + "\t") + vals[subIdx];
}
map.put( convertPrefixKey(name, keyPreMap), treatment(baseTreatment(_val)) );
}
map.put( convertPrefixKey(name, keyPreMap) + "." + Integer.toString(i+1), treatment(baseTreatment(value)) );
}
ignore = true;
} else {
for (int i = 0; i < vals.length; i++){
value = (i == 0 ? "" : value + "\t") + vals[i];
}
}
}else{
value = request.getParameter(name);
}
if (!ignore) {
if (CoConstDef.VALIDATION_USE_CAMELCASE) {
name = StringUtil.convertToUnderScore(name).toUpperCase();
}
map.put( convertPrefixKey(name, keyPreMap), treatment(baseTreatment(value)) );
}
}
return;
}
private String convertPrefixKey(String name, Map<String, String> keyPreMap) {
if (keyPreMap != null && keyPreMap.containsKey(name)) {
return keyPreMap.get(name) + "@" + name;
}
return name;
}
public boolean isRequired(String key){
checkStatus();
if (key == null) {
throw new NullPointerException("key name is null.");
}
return ruleMap.containsKey(key) && isRequired(getRule(key));
}
private boolean isRequired(Map<String, String> rule){
return rule.get("REQUIRED").toUpperCase().equals("TRUE");
}
public String getLimitString(String key){
int limitLength = getLimitLength(getRule(key));
return limitLength == Integer.MAX_VALUE ? "" : Integer.toString(limitLength);
}
public String getCustomMessage(String key){
if (messageConfigMap.containsKey(key)) {
return messageConfigMap.get(key);
}
log.error("Can not find validation message config key : " + key);
return "Error";
}
private void checkStatus(){
if (this.ruleMap == null){
throw new IllegalStateException("No Validation Rule.");
}
return;
}
public Map<String, String> getRequiredItemMap(){
if (!isEmpty(customMarker)) {
return getRequiredItemMap(customMarker);
} else {
return getRequiredItemMap(DEFAULT_REQUIRED_MARKER);
}
}
public Map<String, String> getRequiredItemMap(String marker){
checkStatus();
Map<String, String> map = new HashMap<String, String>();
Iterator<String> itr = ruleMap.keySet().iterator();
while (itr.hasNext()){
String key = (String) itr.next();
map.put(key, isRequired(key) ? marker : "");
}
return map;
}
public Map<String, String> getLimitLengthMap(){
checkStatus();
Map<String, String> map = new HashMap<String, String>();
Iterator<String> itr = ruleMap.keySet().iterator();
while (itr.hasNext()){
String key = (String) itr.next();
map.put(key, getLimitString(key));
}
return map;
}
private static String[] parseExp(String str){
str = str.replaceAll("((?:'.*?[^']|')'|[^'\\+])\\s*\\+\\s*", "$1\n").replaceAll("''(.)", "'$1");
return str.split("\\n");
}
public void arrangeMapByRule(Map<String,String> map){
checkStatus();
//확인 입력 등 기록 되지 않은 값 복원
{
Iterator<String> itr = map.keySet().iterator();
Map<String,String> addition = new HashMap<String, String>();
while (itr.hasNext()){
String key = (String)itr.next();
Map<String,String> rule = getRule(key);
if (ruleMap.containsKey(key) && rule.get("COPY_WHEN_INIT") != null){
String copyTo = rule.get("COPY_WHEN_INIT");
if (!map.containsKey(copyTo)){
addition.put(copyTo, map.get(key));
}
}
}
map.putAll(addition);
}
// COMPOSITE 로 지정된 분할 된 값 의 복원
{
Iterator<String> itr = map.keySet().iterator();
Map<String,String> addition = new HashMap<String, String>();
while (itr.hasNext()){
String key = (String)itr.next();
Map<String,String> rule = getRule(key);
if (rule.containsKey("COMPOSITE")){
String val = map.get(key);
String[] comp = parseExp(rule.get("COMPOSITE"));
String[] split = null;
if (rule.containsKey("SPLIT_WHEN_INIT")){
split = parseExp(rule.get("SPLIT_WHEN_INIT"));
if (comp.length != split.length){
throw new IllegalArgumentException("inconsistency of COMPOSITE and SPLIT_WHEN_INIT of rule map.");
}
}
for (int i = 0; i < comp.length; i++){
if (isEmpty(val)) {
if (!comp[i].matches("'.*'")){
addition.put(comp[i], "");
}
} else {
if (comp.length - 1 <= i) {
//last element
if (!comp[i].matches("'.*'")) {
addition.put(comp[i], val);
}
} else {
//has next
if (!comp[i].matches("'.*'")) {
if (comp[i + 1].matches("'.*'")) {
// 다음 COMPOSITE 요소 가 리터럴 이라면, 그 리터럴 직전까지 ( 없으면 끝까지 ) 를 취득
String literal = comp[i + 1].substring(1, comp[i + 1].length() - 1);
int p = val.indexOf(literal) < 0 ? val.length() : val.indexOf(literal);
addition.put(comp[i], val.substring(0, p));
val = val.substring(p);
} else {
// 다음 COMPOSITE 요소 가 변수 라면 지정 이 있으면 그 길이 없으면 끝까지 취득
int limit = val.length();//값의 최대치를 초기화
if (split != null){
try{
limit = Integer.parseInt(split[i].replaceFirst(".+\\{(\\d+)\\}$", "$1"));
}catch(Exception e){
throw new IllegalArgumentException("invalid argument for SPLIT_WHEN_INIT of rule map.");
}
}
int p = limit < val.length() ? limit : val.length();
addition.put(comp[i], val.substring(0, p));
val = val.substring(p);
}
} else {
val = val.substring(comp[i].length() - 2);//2 means ' * 2
}
}
}
}
}
}
map.putAll(addition);
}
}
protected Map<String,String> getRule(String key){
checkStatus();
return ruleMap.containsKey(key) ? ruleMap.get(key) : new HashMap<String, String>();
}
private String baseTreatment(String s){
if (s == null){
return null;
}
return s.replaceAll("\\t", " ")
.replaceFirst("^[\\u0020\\u3000]*", "")
.replaceFirst("[\\u0020\\u3000]*$", "");
}
protected abstract void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap);
public abstract void setAppendix(String key, Object obj);
protected abstract String treatment(String paramvalue);
protected String checkBasicError(String basicKey, String val) {
return checkBasicError(basicKey, null, val, false);
}
protected String checkBasicError(String basicKey, String val, boolean ignoreRequired) {
return checkBasicError(basicKey, null, val, ignoreRequired);
}
protected String checkBasicError(String basicKey, String gridKey, String val) {
return checkBasicError(basicKey, gridKey, val, false);
}
protected String checkBasicError(String basicKey, String gridKey, String val, boolean ignoreRequired) {
String errCd = "";
Map<String, String> ruleMap = getRule(basicKey);
if (ruleMap != null && !ruleMap.isEmpty()) {
errCd = basicValidation(val, ruleMap, ignoreRequired);
if (!isEmpty(errCd)) {
errCd = basicKey + "." + errCd;
}
}
return errCd;
}
} | 26,668 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2BasicValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/T2BasicValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation;
import java.util.Map;
public abstract class T2BasicValidator extends T2CoValidator{
protected String PROC_MODE;
public void setAppendix(String key, Object obj){
if (!isEmpty(key) && obj != null) {
if ("PROC_MODE".equals(key)) {
this.PROC_MODE = (String) obj;
}
}
}
protected String treatment(String paramvalue){
if (paramvalue == null) {
return null;
}
return paramvalue;
}
protected void customValidation(Map<String, String> map, Map<String, String> errMap){
return;
}
} | 742 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoPartnerValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/T2CoPartnerValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidator;
public class T2CoPartnerValidator extends T2CoValidator {
private List<ProjectIdentification> ossComponetList = null;
private List<List<ProjectIdentification>> ossComponentLicenseList = null;
private String PROC_TYPE = null;
public final String PROC_TYPE_IDENTIFICATION_SOURCE = "SRC";
public final String PROC_TYPE_IDENTIFICATION_CONFIRM = "CONF";
@SuppressWarnings("unused")
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
if (PROC_TYPE_IDENTIFICATION_CONFIRM.equals(PROC_TYPE)) {
validComfirmProcess(map, errMap);
} else {
Map<String, OssMaster> ossInfo = null;
// dataMap을 사용하지 않고, request정보를 직접 참조
if (ossComponetList != null) {
String basicKey = "";
String gridKey = "";
List<ProjectIdentification> licenseList = null;
OssMaster ossParam = new OssMaster(); // 설정된 oss 정보를 DB에서 취득한다.
ossParam.setOssNames(getOssNames());
if (ossParam.getOssNames() != null && ossParam.getOssNames().length > 0) {
ossInfo = CoCodeManager.OSS_INFO_UPPER;
}
// checkBasicError : REQUIRED, LENGTH, FORMAT 만 체크!
for (ProjectIdentification bean : ossComponetList) {
boolean hasError = false;
boolean hasMultiError = false; // multi license용
// exclude=Y 상태인 경우 체크하지 않음
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
// 1) oss name
{
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS NAME에 대해서 추가적으로 해야할 것이 있다면
}
}
// 2) OSS VERSION
{
basicKey = "OSS_VERSION";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getOssVersion());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 3) DOWNLOAD LOCATION
{
basicKey = "DOWNLOAD_LOCATION";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getDownloadLocation());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 4) HOMEPAGE
{
basicKey = "HOMEPAGE";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getHomepage());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 이후부터는 license와 관련됨
licenseList = findLicense(bean.getGridId());
if (licenseList.isEmpty()) {
hasError = false; // 초기화
// subGrid가 없을 경우, 싱글라이선스로 간주
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 5-1. license name의 basic validator
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
hasError = true;
}
}
} else {
// Multi 또는 dual 라이선스의 경우
hasMultiError = false; // 초기화
List<ProjectIdentification> unExcludeLicenseList = new ArrayList<>();
for (ProjectIdentification licenseBean : licenseList) {
hasError = false; // 초기화
// exclude=Y 상태인 경우 체크하지 않음
if (!CoConstDef.FLAG_YES.equals(licenseBean.getExcludeYn())) {
unExcludeLicenseList.add(licenseBean);
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 5-1. license name의 basic validator
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, licenseBean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + licenseBean.getGridId(), errCd);
hasMultiError = hasError = true;
}
}
{
basicKey = "LICENSE_TEXT";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 5-2 license text의 basic validator
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, licenseBean.getLicenseText(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + licenseBean.getGridId(), errCd);
hasMultiError = hasError = true;
}
}
// 5-3. 라이선스 정보가 db에 없고, license text가 공백인 경우
if (!hasError && !CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseBean.getLicenseName().toUpperCase())
&& isEmpty(licenseBean.getLicenseText())) {
errMap.put(basicKey + "." + licenseBean.getGridId(), "LICENSE_TEXT.REQUIRED");
hasMultiError = hasError = true;
}
// 5-4. 라이선스가 DB에 존재하고, REQ_LICENSE_TEXT_YN='Y'
// 인 경우, license text 필수 체크
// MIT like, BSD like 대응
if (!hasError && CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseBean.getLicenseName().toUpperCase())
&& CoConstDef.FLAG_YES.equals(CoCodeManager.LICENSE_INFO_UPPER
.get(licenseBean.getLicenseName().toUpperCase()).getReqLicenseTextYn())) {
errMap.put(basicKey + "." + licenseBean.getGridId(), "LICENSE_TEXT.REQUIRED");
hasMultiError = hasError = true;
}
}
}
// exclude를 포함하여 체크해야할 validator
if (!hasMultiError) {
basicKey = "LICENSE_NAME";
// 모두 exlucde가 체크되어 선택된 라이선스가 없을 경우
if (unExcludeLicenseList.isEmpty()) {
// header row의 라이선스에 에러 표시
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".NOLICENSE");
} else if (checkOROperation(licenseList)) {
// OR 조건이 두개이상 선택된 경우
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".INCLUDE_DUAL_OPERATE");
} else if (checkANDOperation(licenseList)) {
// AND OR 연산식에 부합하지 않는 경우
// 순서대로 첫번재 exclude 되지 않은 licenes를 기준으로 and 조건
// 라이선스중에 (다음 OR를 만나기전) exclude된 라이선스가 있는지
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".SATISFY");
}
}
}
// 6) path 정보
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는
// 파라미터 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
// OSS가 DB에 존재하고, 선택된 라이선스(멀티인 경우 복수)의 oblication이 소스코드를
// 공개해야하는 경우, 필수 체크
else if (!hasError && isEmpty(bean.getFilePath())) {
if (licenseList.isEmpty()) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(bean.getLicenseName().toUpperCase())
&& CoConstDef.FLAG_YES.equals(CoCodeManager.LICENSE_INFO_UPPER
.get(bean.getLicenseName().toUpperCase()).getObligationDisclosingSrcYn())) {
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".REQUIRED");
}
} else {
// license name에 error가 없을 경우만
if (!errMap.containsKey("LICENSE_NAME." + bean.getGridId())) {
// 선택한 라이선스 중에 하나라도 소스공개 의무를 가질 경우 에러
for (ProjectIdentification licenseBean : licenseList) {
if (!CoConstDef.FLAG_YES.equals(licenseBean.getExcludeYn())
&& CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseBean.getLicenseName().toUpperCase())
&& CoConstDef.FLAG_YES.equals(
CoCodeManager.LICENSE_INFO_UPPER.get(licenseBean.getLicenseName().toUpperCase())
.getObligationDisclosingSrcYn())) {
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".REQUIRED");
break;
}
}
}
}
}
}
}
}
}
}
private void validComfirmProcess(Map<String, String> map, Map<String, String> errMap) {
// TODO Auto-generated method stub
}
private boolean checkANDOperation(List<ProjectIdentification> licenseList) {
// OR 조건으로 각 list로 구분한다.
List<List<ProjectIdentification>> andCombLicenseList = new ArrayList<>();
for (ProjectIdentification bean : licenseList) {
if (bean.getOssLicenseComb().isEmpty() || "OR".equals(bean.getOssLicenseComb())) {
andCombLicenseList.add(new ArrayList<>());
}
andCombLicenseList.get(andCombLicenseList.size() - 1).add(bean);
}
for (List<ProjectIdentification> list : andCombLicenseList) {
for (ProjectIdentification andLicense : list) {
if (!CoConstDef.FLAG_YES.equals(andLicense.getExcludeYn())) {
return hasExclude(list, true);
}
}
}
return false;
}
private boolean hasExclude(List<ProjectIdentification> list, boolean exclude) {
for (ProjectIdentification bean : list) {
if (exclude) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
return true;
}
} else {
if (!CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
return true;
}
}
}
return false;
}
private boolean checkOROperation(List<ProjectIdentification> licenseList) {
// OR 조건으로 각 list로 구분한다.
List<List<ProjectIdentification>> andCombLicenseList = new ArrayList<>();
for (ProjectIdentification bean : licenseList) {
if (andCombLicenseList.isEmpty() || "OR".equals(bean.getOssLicenseComb())) {
andCombLicenseList.add(new ArrayList<>());
}
andCombLicenseList.get(andCombLicenseList.size() - 1).add(bean);
}
boolean hasSelectedLicense = false;
for (List<ProjectIdentification> list : andCombLicenseList) {
boolean hasSelected = hasExclude(list, false);
if (hasSelectedLicense && hasSelected) {
return true;
}
if (hasSelected) {
hasSelectedLicense = hasSelected;
}
}
return false;
}
private String[] getOssNames() {
List<String> names = new ArrayList<>();
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn()) || isEmpty(bean.getOssName()) || names.contains(bean.getOssName().trim())) {
continue;
}
names.add(bean.getOssName().trim());
}
return names.toArray(new String[names.size()]);
}
private List<ProjectIdentification> findLicense(String gridId) {
List<ProjectIdentification> licenseList = new ArrayList<>();
if (ossComponentLicenseList != null && !ossComponentLicenseList.isEmpty()) {
boolean breakFlag = false;
for (List<ProjectIdentification> list : ossComponentLicenseList) {
for (ProjectIdentification bean : list) {
String key = gridId + "-";
if (bean.getGridId().startsWith(key)) {
licenseList.add(bean);
breakFlag = true;
}
}
if (breakFlag) {
break;
}
}
}
return licenseList;
}
@SuppressWarnings("unchecked")
@Override
public void setAppendix(String key, Object obj) {
if ("mainList".equals(key)) {
ossComponetList = (List<ProjectIdentification>) obj;
} else if ("subList".equals(key)) {
ossComponentLicenseList = (List<List<ProjectIdentification>>) obj;
}
}
@Override
protected String treatment(String paramvalue) {
return paramvalue;
}
public void setProcType(String type) {
PROC_TYPE = type;
}
}
| 13,461 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoLicenseValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/T2CoLicenseValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.service.LicenseService;
import oss.fosslight.validation.T2CoValidator;
public class T2CoLicenseValidator extends T2CoValidator {
private LicenseService licenseService = (LicenseService) getWebappContext().getBean(LicenseService.class);
private String licenseId = null;
private String VALID_TYPE = null;
public final String VALID_LICNESELIST_BULK = "LICENSELIST_BULK";
private String PROC_TYPE = null;
public final String PROC_TYPE_DELETE = "DEL";
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
if (PROC_TYPE_DELETE.equals(PROC_TYPE)) {
List<OssMaster> result = licenseService.checkExistsUsedOss(licenseId);
if (result != null && !result.isEmpty()) {
String errMsg = MessageFormat.format(getCustomMessage("LICENSE_NAME.OSSUSED"), result.size());
int ossCnt = 1;
for (OssMaster bean : result) {
if (ossCnt > 40) {
errMsg += "<br>...";
break;
}
errMsg += "<br>" + MessageFormat.format(getCustomMessage("LICENSE_NAME.OSSUSEDEXP"), bean.getOssId(), bean.getOssId(), bean.getOssName() + (!isEmpty(bean.getOssVersion()) ? " " : "") + avoidNull(bean.getOssVersion()));
ossCnt ++;
}
errMap.put("LICENSE_NAME", errMsg);
}
} else {
String targetName = "";
String licenseId = avoidNull(map.get("LICENSE_ID"));
// 1. license name
targetName = "LICENSE_NAME";
if (!errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
if (map.get(targetName).contains(CoConstDef.CD_COMMA_CHAR)) {
errMap.put(targetName, targetName + ".NOTALLOWED_CHAR");
}else {
// DB체크만
LicenseMaster param = new LicenseMaster(licenseId);
param.setLicenseName(map.get(targetName));
LicenseMaster result = licenseService.checkExistsLicense(param);
if (result != null) {
errMap.put(targetName, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(targetName), result.getLicenseId(), result.getLicenseId(), result.getLicenseName()));
}
}
}
// 2. SHORT_IDENTIFIER
targetName = "SHORT_IDENTIFIER";
if (!errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
// 2-1 license name 과 같은 경우
if (map.get(targetName).contains(CoConstDef.CD_COMMA_CHAR)) {
errMap.put(targetName, targetName + ".NOTALLOWED_CHAR");
} else if (map.get(targetName).equalsIgnoreCase(avoidNull(map.get("LICENSE_NAME")))) {
errMap.put(targetName, targetName + ".SAME");
} else {
// 2-2 db 에 존재하는 경우
LicenseMaster param = new LicenseMaster(licenseId);
param.setLicenseName(map.get(targetName));
LicenseMaster result = licenseService.checkExistsLicense(param);
if (result != null) {
errMap.put(targetName, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(targetName), result.getLicenseId(), result.getLicenseId(), result.getLicenseName()));
}
}
}
// 3. NICK NAME
targetName = "LICENSE_NICKNAMES";
if (!errMap.containsKey(targetName) && (map.containsKey(targetName + ".1") || map.containsKey(targetName) )) {
List<String> nickNameKeyList = new ArrayList<>();
if (!map.containsKey(targetName + ".1")) {
checkLicenseNickName(errMap, map, nickNameKeyList, targetName, licenseId);
} else {
for (int i = 1; map.containsKey(targetName + "." + i); i++){
String _seqkey = targetName + "." + i;
checkLicenseNickName(errMap, map, nickNameKeyList, _seqkey, licenseId);
}
}
}
}
}
private void checkLicenseNickName(Map<String, String> errMap, Map<String, String> map, List<String> nickNameKeyList, String _seqkey, String licenseId) {
String targetName = "LICENSE_NICKNAMES";
if (isEmpty(map.get(_seqkey))) {
return;
}
if (!errMap.containsKey(_seqkey)) {
// 3-1 동일한 닉네임을 입력한 경우
if (nickNameKeyList.contains(map.get(_seqkey).toUpperCase())) {
errMap.put(_seqkey, targetName + ".SAME");
} else {
String nickName = map.get(_seqkey).toUpperCase();
nickNameKeyList.add(nickName);
if (nickName.contains(CoConstDef.CD_COMMA_CHAR)) {
errMap.put(_seqkey, targetName + ".NOTALLOWED_CHAR");
} else if (map.get(_seqkey).equalsIgnoreCase(avoidNull(map.get("LICENSE_NAME")))
|| map.get(_seqkey).equalsIgnoreCase(avoidNull(map.get("SHORT_IDENTIFIER")))) { // 3-2 license name 또는 SHORT_IDENTIFIER 과 같은 경우
errMap.put(_seqkey, targetName + ".SAME");
} else {
// 3-4 db 에 존재하는 경우
LicenseMaster param = new LicenseMaster(licenseId);
param.setLicenseName(map.get(_seqkey));
LicenseMaster result = licenseService.checkExistsLicense(param);
if (result != null) {
errMap.put(_seqkey, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(_seqkey), result.getLicenseId(), result.getLicenseId(), result.getLicenseName()));
}
}
}
}
}
public void setProcType(String type) {
PROC_TYPE = type;
}
@Override
public void setAppendix(String key, Object obj) {
if ("licenseId".equals(key)) {
this.licenseId = (String) obj;
}
}
@Override
protected String treatment(String paramvalue) {
return paramvalue;
}
public void setVALIDATION_TYPE(String vALID_TYPE) {
VALID_TYPE = vALID_TYPE;
}
}
| 6,134 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoOssValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/T2CoOssValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.domain.OssAnalysis;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.service.OssService;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidator;
public class T2CoOssValidator extends T2CoValidator {
private OssService ossService = (OssService) getWebappContext().getBean(OssService.class);
private OssMaster ossMaster = null;
private OssAnalysis ossAnalysis = null;
private List<OssMaster> ossList = null;
private List<OssAnalysis> analysisList = null;
private String VALID_TYPE = null;
public final String VALID_DOWNLOADLOCATION = "DOWNLOADLOCATION";
public final String VALID_DOWNLOADLOCATIONS = "DOWNLOADLOCATIONS";
public final String VALID_HOMEPAGE = "HOMEPAGE";
public final String VALID_OSS_BULK = "OSS_BULK";
public final String VALID_OSSLIST_BULK = "OSSLIST_BULK";
public final String VALID_OSSANALYSIS = "OSSANALYSIS";
public final String VALID_OSSANALYSIS_LIST = "OSSANALYSISLIST";
@SuppressWarnings("unchecked")
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
String targetName = "";
String ossId = avoidNull(map.get("OSS_ID"));
// oss 일괄등록 validator
if (VALID_TYPE == VALID_OSSLIST_BULK) {
if (ossList != null) {
for (OssMaster bean : ossList) {
ossBulkValidate(bean, map, errMap, diffMap, infoMap, true);
}
}
} else if (VALID_TYPE == VALID_OSS_BULK) {
ossValidate(ossMaster, map, errMap, diffMap, infoMap, false);
} else if (VALID_TYPE == VALID_OSSANALYSIS) {
ossAnalysisValidate(ossAnalysis, map, errMap, diffMap, infoMap, false);
} else if (VALID_TYPE == VALID_OSSANALYSIS_LIST) {
if (analysisList != null) {
for (OssAnalysis bean : analysisList) {
ossAnalysisValidate(bean, map, errMap, diffMap, infoMap, true);
}
}
} else if (VALID_TYPE == VALID_DOWNLOADLOCATION){ // DOWNLOAD LOCATION URL을 중복으로 작성한 경우
targetName = "DOWNLOAD_LOCATION";
if (isEmpty(ossId) && !errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
OssMaster param = new OssMaster();
param.setDownloadLocation(map.get(targetName));
param.setOssName((String) map.get("OSS_NAME"));
Map<String, Object> paramMap = ossService.checkExistsOssDownloadLocation(param);
List<OssMaster> downLoadLocationList = (List<OssMaster>) paramMap.get("downloadLocation");
if (!downLoadLocationList.isEmpty()) {
String sortOrder = downLoadLocationList.get(0).getSOrder();
String msg = "";
if ("1".equals(sortOrder)) {
msg = MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), "");
} else {
msg = MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
}
for (int i = 0 ; i < downLoadLocationList.size() ; i++) {
if ("1".equals(sortOrder) && !"1".equals(downLoadLocationList.get(i).getSOrder())) {
msg += "<br>" + MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
msg += MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), downLoadLocationList.get(i).getOssName(), downLoadLocationList.get(i).getOssName());
} else {
msg += (i==0?"":",") + MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), downLoadLocationList.get(i).getOssName(), downLoadLocationList.get(i).getOssName());
}
sortOrder = downLoadLocationList.get(i).getSOrder();
}
diffMap.put(targetName, msg);
}
}
} else if (VALID_TYPE == VALID_DOWNLOADLOCATIONS){
targetName = "DOWNLOAD_LOCATIONS";
if (isEmpty(ossId) && !errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
String[] downloadLocations = map.get(targetName).split("\t");
targetName = "DOWNLOAD_LOCATION";
List<String> result = new ArrayList<String>();
for (String downloadLocation : downloadLocations){
OssMaster param = new OssMaster();
param.setDownloadLocation(downloadLocation);
param.setOssName((String) map.get("OSS_NAME"));
Map<String, Object> paramMap = ossService.checkExistsOssDownloadLocation(param);
List<OssMaster> downLoadLocationList = (List<OssMaster>) paramMap.get("downloadLocation");
if (!downLoadLocationList.isEmpty()) {
String sortOrder = downLoadLocationList.get(0).getSOrder();
String msg = "";
if ("1".equals(sortOrder)) {
msg = MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), "");
} else {
msg = MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
}
for (int i = 0 ; i < downLoadLocationList.size() ; i++) {
if ("1".equals(sortOrder) && !"1".equals(downLoadLocationList.get(i).getSOrder())) {
msg += "<br>" + MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
msg += MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), downLoadLocationList.get(i).getOssName(), downLoadLocationList.get(i).getOssName());
} else {
msg += (i==0?"":",") + MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), downLoadLocationList.get(i).getOssName(), downLoadLocationList.get(i).getOssName());
}
sortOrder = downLoadLocationList.get(i).getSOrder();
}
result.add(downloadLocation+"@@"+msg);
}
}
if (result.size() > 0){
diffMap.put("DOWNLOAD_LOCATIONS", StringUtils.join(result, "||"));
}
}
} else if (VALID_TYPE == VALID_HOMEPAGE){ // HOMEPAGE URL을 중복으로 작성한 경우
targetName = "HOMEPAGE";
if (isEmpty(ossId) && !errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
OssMaster param = new OssMaster();
param.setHomepage(map.get(targetName));
param.setOssName((String) map.get("OSS_NAME"));
Map<String, Object> paramMap = ossService.checkExistsOssHomepage(param);
List<OssMaster> homepageList = (List<OssMaster>) paramMap.get("homepage");
if (!homepageList.isEmpty()) {
String sortOrder = homepageList.get(0).getSOrder();
String msg = "";
if ("1".equals(sortOrder)) {
msg = MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), "");
} else {
msg = MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
}
for (int i = 0 ; i < homepageList.size() ; i++) {
if ("1".equals(sortOrder) && !"1".equals(homepageList.get(i).getSOrder())) {
msg += "<br>" + MessageFormat.format(getCustomMessage(targetName + ".PARTIAL_DUPLICATED"), "");
msg += MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), homepageList.get(i).getOssName(), homepageList.get(i).getOssName());
} else {
msg += (i==0?"":",") + MessageFormat.format(getCustomMessage(targetName + ".LIST_LINK"), homepageList.get(i).getOssName(), homepageList.get(i).getOssName());
}
sortOrder = homepageList.get(i).getSOrder();
}
diffMap.put(targetName, msg);
}
}
} else {
// 1. version
targetName = "OSS_VERSION";
if (!errMap.containsKey(targetName) && map.containsKey(targetName)) {
// DB체크만
OssMaster param = new OssMaster(ossId);
param.setOssVersion(map.get(targetName));
param.setOssName(map.get("OSS_NAME"));
OssMaster result = ossService.checkExistsOss(param);
if (result != null) {
errMap.put(targetName, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(targetName), result.getOssId(), result.getOssId(), result.getOssName()));
}
}
// 2. NICK NAME
targetName = "OSS_NICKNAMES";
if (!errMap.containsKey(targetName) && (map.containsKey(targetName + ".1") || map.containsKey(targetName)) ) {
List<String> nickNameKeyList = new ArrayList<>();
if (!map.containsKey(targetName + ".1") && map.containsKey(targetName)) {
String _seqkey = targetName;
if (!errMap.containsKey(_seqkey) && !StringUtil.isEmpty(map.get(_seqkey))) {
// 3-1 동일한 닉네임을 입력한 경우
if (nickNameKeyList.contains(map.get(_seqkey).trim().toUpperCase())) {
errMap.put(_seqkey, targetName + ".SAME");
} else {
nickNameKeyList.add(map.get(_seqkey).trim().toUpperCase());
// 3-2 oss name 과 같은 경우
if (map.get(_seqkey).trim().equalsIgnoreCase(avoidNull(map.get("OSS_NAME")).trim())) {
errMap.put(_seqkey, targetName + ".SAME");
// 3-3 db 에 존재하는 경우
} else {
OssMaster param = new OssMaster(ossId);
param.setOssName(map.get(_seqkey).trim());
if (!isEmpty(map.get("OSS_NAME"))) {
param.setOssNameTemp(map.get("OSS_NAME"));
}
OssMaster result = ossService.checkExistsOssNickname(param);
if (result != null) {
errMap.put(_seqkey, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(_seqkey), result.getOssId(), result.getOssId(), result.getOssName()));
}
}
}
}
}else{
for (int i = 1; map.containsKey(targetName + "." + i); i++){
String _seqkey = targetName + "." + i;
if (!errMap.containsKey(_seqkey) && !StringUtil.isEmpty(map.get(_seqkey))) {
// 3-1 동일한 닉네임을 입력한 경우
if (nickNameKeyList.contains(map.get(_seqkey).trim().toUpperCase())) {
errMap.put(_seqkey, targetName + ".SAME");
} else {
nickNameKeyList.add(map.get(_seqkey).trim().toUpperCase());
// 3-2 oss name 과 같은 경우
if (map.get(_seqkey).trim().equalsIgnoreCase(avoidNull(map.get("OSS_NAME")).trim())) {
errMap.put(_seqkey, targetName + ".SAME");
// 3-3 db 에 존재하는 경우
} else {
OssMaster param = new OssMaster(ossId);
param.setOssName(map.get(_seqkey).trim());
if (!isEmpty(map.get("OSS_NAME"))) {
param.setOssNameTemp(map.get("OSS_NAME"));
}
OssMaster result = ossService.checkExistsOssNickname(param);
if (result != null) {
errMap.put(_seqkey, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATED"), map.get(_seqkey), result.getOssId(), result.getOssId(), result.getOssName()));
}
}
}
}
}
}
}
// 17.02.15 yuns
// OSS NAME이 이미 등록되어 있는 경우 체크 추가
targetName = "OSS_NAME";
if (!errMap.containsKey(targetName) && map.containsKey(targetName) && !isEmpty(map.get(targetName))) {
OssMaster param = new OssMaster(ossId);
param.setOssName(map.get(targetName));
OssMaster result = ossService.checkExistsOssNickname2(param);
if (result != null) {
errMap.put(targetName, MessageFormat.format(getCustomMessage(targetName + ".DUPLICATEDNICK"), map.get(targetName), result.getOssId(), result.getOssId(), result.getOssName()));
}
}
}
}
@SuppressWarnings("unchecked")
private void ossValidate(OssMaster ossBean, Map<String, String> map, Map<String, String> errMap,
Map<String, String> diffMap, Map<String, String> infoMap, boolean useGridSeq) {
if (ossBean != null) {
// OSS Name
// 이미등록된 경우 체크
String basicKey = "OSS_NAME";
String gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, ossBean.getOssName(), false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), errCd);
} else {
// 초기표시인 경우, Identification과 동일
if (useGridSeq) {
if (!CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossBean.getOssName().toUpperCase())) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".UNCONFIRMED");
}
} else {
OssMaster param = new OssMaster();
param.setOssName(ossBean.getOssName());
OssMaster result = ossService.checkExistsOssNickname2(param);
if (result != null) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATEDNICK2");
}
}
}
// OSS Version
basicKey = "OSS_VERSION";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, ossBean.getOssVersion(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), errCd);
} else {
// OSS Name에 에러가 있는 경우 version의 유효성 체크할 필요 없음
if (!hasError(errMap, "OSS_NAME", ossBean.getGridId(), useGridSeq)) {
if (useGridSeq) {
if (!CoCodeManager.OSS_INFO_UPPER.containsKey( (ossBean.getOssName() + "_" + ossBean.getOssVersion()).toUpperCase() )) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".UNCONFIRMED");
}
} else {
// DB체크만
// 필요한가? 어짜피 skip하면됨 일단은 체크
OssMaster param = new OssMaster();
param.setOssVersion(ossBean.getOssVersion());
param.setOssName(ossBean.getOssName());
OssMaster result = ossService.checkExistsOss(param);
if (result != null) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATED2");
}
}
}
}
// license
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, ossBean.getLicenseName(), false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), errCd);
} else {
boolean breakPoint = false;
String chkStr = ossBean.getLicenseName().replaceAll("\\(", " ").replaceAll("\\)", " ").toUpperCase();
for (String s1 : chkStr.split(" OR ")) {
for (String s2 : s1.split(" AND ")) {
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(s2.trim().toUpperCase())) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".UNCONFIRMED");
breakPoint = true;
break;
}
}
if (breakPoint) {
break;
}
}
// error가 없다면, 괄호안에 OR 조건이 포함되어 있는지 체크
// 괄호 안에는 OR Operator가 존재할 수 없음 (AND만)
if (!breakPoint) {
Pattern p = Pattern.compile("\\(([^()]*)\\)");
Matcher m = p.matcher(ossBean.getLicenseName());
while (m.find()) {
if (m.group().toUpperCase().indexOf(" OR ") > -1) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".ORCONDITIONS");
break;
}
}
}
}
// nickname 체크
basicKey = "OSS_NICKNAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (!isEmpty(ossBean.getOssNickname())) {
List<String> nickList = Arrays.asList(ossBean.getOssNickname().split(","));
String upperOssName = ossBean.getOssName().trim().toUpperCase();
List<String> dupCheckList = new ArrayList<>();
for (String s : nickList) {
if (isEmpty(s)) {
continue;
}
String upperNick = s.trim().toUpperCase();
// oss name과 동일한 경우
if (upperNick.equalsIgnoreCase(upperOssName)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATED");
} else if (dupCheckList.contains(upperNick)) {
// 동일한 nick name을 두번이상 설정한 경우
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
// 다른 oss 에서 이미 사용하고 있는 경우
OssMaster param = new OssMaster();
param.setOssName(upperNick);
param.setOssNameTemp(upperOssName);
OssMaster result = ossService.checkExistsOssNickname(param);
if (result != null) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".SAME");
}
}
dupCheckList.add(upperNick);
}
}
// downloadlocation
basicKey = "DOWNLOAD_LOCATION";
gridKey = StringUtil.convertToCamelCase(basicKey);
String[] downloadLocation = ossBean.getDownloadLocation().split(",");
for (String location : downloadLocation){
errCd = checkBasicError(basicKey, gridKey, location.trim(), true);
if (!isEmpty(errCd)){
break;
}
}
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), errCd);
} else if (!isEmpty(ossBean.getDownloadLocation())){
for (String location : downloadLocation){
OssMaster param = new OssMaster();
// version up 인 경우, 해당 oss name을 제외하고 검증
if (!isEmpty(ossBean.getOssName()) && CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossBean.getOssName().trim().toUpperCase())) {
param.setOssName(CoCodeManager.OSS_INFO_UPPER_NAMES.get(ossBean.getOssName().trim().toUpperCase()));
}
param.setDownloadLocation(location.trim());
Map<String, Object> paramMap = ossService.checkExistsOssDownloadLocation(param);
List<OssMaster> list = (List<OssMaster>) paramMap.get("downloadLocation");
if (list != null && !list.isEmpty()) {
String sortOrder = list.get(0).getSOrder();
if ("1".equals(sortOrder)) {
diffMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
diffMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".PARTIAL_DUPLICATED");
}
break;
}
}
}
// homepage
basicKey = "HOMEPAGE";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, ossBean.getHomepage().trim(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), errCd);
} else if (!isEmpty(ossBean.getHomepage())) {
OssMaster param = new OssMaster();
// version up 인 경우, 해당 oss name을 제외하고 검증
if (!isEmpty(ossBean.getOssName()) && CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(ossBean.getOssName().trim().toUpperCase())) {
param.setOssName(CoCodeManager.OSS_INFO_UPPER_NAMES.get(ossBean.getOssName().trim().toUpperCase()));
}
param.setHomepage(ossBean.getHomepage().trim());
Map<String, Object> paramMap = ossService.checkExistsOssHomepage(param);
List<OssMaster> list = (List<OssMaster>) paramMap.get("homepage");
if (list != null && !list.isEmpty()) {
String sortOrder = list.get(0).getSOrder();
if ("1".equals(sortOrder)) {
diffMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
diffMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), basicKey+".PARTIAL_DUPLICATED");
}
}
}
}
}
private void ossBulkValidate(OssMaster ossBean,
Map<String, String> map,
Map<String, String> errMap,
Map<String, String> diffMap,
Map<String, String> infoMap,
boolean useGridSeq) {
/** OSS_NAME */
String basicKey = "OSS_NAME";
String gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, ossBean.getOssName(), false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""), errCd);
} else if (ossService.checkExistsOssNickname2(ossBean) != null) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""),
"OSS_NAME.DUPLICATEDNICK_SHORT");
} else if (ossService.checkExistsOssByname(ossBean) == 0) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""), "OSS_NAME.UNCONFIRMED");
}
/** OSS_NICKNAME */
basicKey = "OSS_NICKNAMES";
OssMaster nicknameCheckBean = new OssMaster();
nicknameCheckBean.setOssNameTemp(ossBean.getOssName());
if (!Objects.isNull(ossBean.getOssNicknames())) {
for (String ossNickname : ossBean.getOssNicknames()) {
nicknameCheckBean.setOssName(ossNickname);
if (!Objects.isNull(ossService.checkExistsOssNickname(nicknameCheckBean))) {
errMap.put(basicKey + (useGridSeq ? "."+ossBean.getGridId() : ""), "OSS_NICKNAMES.SAME_SHORT");
break;
}
}
}
/** declared licenses */
basicKey = "DECLARED_LICENSES";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (Objects.isNull(ossBean.getDeclaredLicenses()) || ossBean.getDeclaredLicenses().isEmpty()) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""), "LICENSE_NAME.REQUIRED");
} else {
for (String license : ossBean.getDeclaredLicenses()) {
errCd = checkBasicError(basicKey, gridKey, license, false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""), errCd);
break;
}
if (!CommonFunction.checkLicense(license)) {
errMap.put(basicKey + "." + ossBean.getGridId(), "LICENSE_NAME.UNCONFIRMED");
break;
}
}
}
/** detected licenses **/
basicKey = "DETECTED_LICENSES";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (!Objects.isNull(ossBean.getDetectedLicenses())) {
for (String license : ossBean.getDetectedLicenses()) {
errCd = checkBasicError(basicKey, gridKey, license, false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "." + ossBean.getGridId() : ""), errCd);
break;
}
if (!CommonFunction.checkLicense(license)) {
errMap.put(basicKey + "." + ossBean.getGridId(), "LICENSE_NAME.UNCONFIRMED");
break;
}
}
}
}
@SuppressWarnings("unchecked")
private void ossAnalysisValidate(OssAnalysis analysisBean, Map<String, String> map, Map<String, String> errMap,
Map<String, String> diffMap, Map<String, String> infoMap, boolean useGridSeq) {
if (analysisBean != null) {
// OSS Name
// 이미등록된 경우 체크
String basicKey = "OSS_NAME";
String gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, analysisBean.getOssName(), false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), errCd);
} else {
// 초기표시인 경우, Identification과 동일
if (useGridSeq) {
if (!CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(analysisBean.getOssName().toUpperCase())) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".UNCONFIRMED");
}
} else {
OssMaster param = new OssMaster();
param.setOssName(analysisBean.getOssName());
OssMaster result = ossService.checkExistsOssNickname2(param);
if (result != null) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATEDNICK2");
}
}
}
// OSS Version
basicKey = "OSS_VERSION";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, analysisBean.getOssVersion(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), errCd);
} else {
// OSS Name에 에러가 있는 경우 version의 유효성 체크할 필요 없음
if (!hasError(errMap, "OSS_NAME", analysisBean.getGridId(), useGridSeq)) {
if (useGridSeq) {
if (!CoCodeManager.OSS_INFO_UPPER.containsKey( (analysisBean.getOssName() + "_" + avoidNull(analysisBean.getOssVersion())).toUpperCase() )) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".UNCONFIRMED");
}
} else {
// DB체크만
// 필요한가? 어짜피 skip하면됨 일단은 체크
OssMaster param = new OssMaster();
param.setOssVersion(analysisBean.getOssVersion());
param.setOssName(analysisBean.getOssName());
OssMaster result = ossService.checkExistsOss(param);
if (result != null) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATED2");
}
}
}
}
// license
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, analysisBean.getLicenseName(), false);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), errCd);
} else {
boolean breakPoint = false;
for (String s2 : analysisBean.getLicenseName().split(",")) {
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(s2.trim().toUpperCase())) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".UNCONFIRMED");
breakPoint = true;
break;
}
}
// error가 없다면, 괄호안에 OR 조건이 포함되어 있는지 체크
// 괄호 안에는 OR Operator가 존재할 수 없음 (AND만)
if (!breakPoint) {
Pattern p = Pattern.compile("\\(([^()]*)\\)");
Matcher m = p.matcher(analysisBean.getLicenseName());
while (m.find()) {
if (m.group().toUpperCase().indexOf(" OR ") > -1) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".ORCONDITIONS");
break;
}
}
}
}
// nickname 체크
basicKey = "OSS_NICKNAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (!isEmpty(analysisBean.getOssNickname())) {
List<String> nickList = Arrays.asList(analysisBean.getOssNickname().split(","));
String upperOssName = analysisBean.getOssName().trim().toUpperCase();
List<String> dupCheckList = new ArrayList<>();
String sameMsg = "The same OSS ";
for (String s : nickList) {
if (isEmpty(s)) {
continue;
}
String upperNick = s.trim().toUpperCase();
// oss name과 동일한 경우
if (upperNick.equalsIgnoreCase(upperOssName)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATED");
} else if (dupCheckList.contains(upperNick)) {
// 동일한 nick name을 두번이상 설정한 경우
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
// 다른 oss 에서 이미 사용하고 있는 경우
OssMaster param = new OssMaster();
param.setOssName(upperNick);
param.setOssNameTemp(upperOssName);
OssMaster result = ossService.checkExistsOssNickname(param);
if (result != null) {
if (sameMsg.contains(") exists.")) {
sameMsg = sameMsg.substring(0, sameMsg.indexOf(") exists.")).trim() + ",";
sameMsg += s.trim() + ") exists.";
} else {
sameMsg += "(" + s.trim() + ") exists.";
}
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), sameMsg);
}
}
dupCheckList.add(upperNick);
}
}
// downloadlocation
basicKey = "DOWNLOAD_LOCATION";
gridKey = StringUtil.convertToCamelCase(basicKey);
String[] downloadLocation = analysisBean.getDownloadLocation().split(",");
for (String location : downloadLocation){
errCd = checkBasicError(basicKey, gridKey, location.trim(), true);
if (!isEmpty(errCd)){
break;
}
}
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), errCd);
} else if (!isEmpty(analysisBean.getDownloadLocation())){
for (String location : downloadLocation){
OssMaster param = new OssMaster();
// version up 인 경우, 해당 oss name을 제외하고 검증
if (!isEmpty(analysisBean.getOssName()) && CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(analysisBean.getOssName().trim().toUpperCase())) {
param.setOssName(CoCodeManager.OSS_INFO_UPPER_NAMES.get(analysisBean.getOssName().trim().toUpperCase()));
}
param.setDownloadLocation(location.trim());
Map<String, Object> paramMap = ossService.checkExistsOssDownloadLocation(param);
List<OssMaster> list = (List<OssMaster>) paramMap.get("downloadLocation");
if (list != null && !list.isEmpty()) {
String sortOrder = list.get(0).getSOrder();
if ("1".equals(sortOrder)) {
diffMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
diffMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".PARTIAL_DUPLICATED");
}
break;
}
}
}
// homepage
basicKey = "HOMEPAGE";
gridKey = StringUtil.convertToCamelCase(basicKey);
errCd = checkBasicError(basicKey, gridKey, analysisBean.getHomepage().trim(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), errCd);
} else if (!isEmpty(analysisBean.getHomepage())) {
OssMaster param = new OssMaster();
// version up 인 경우, 해당 oss name을 제외하고 검증
if (!isEmpty(analysisBean.getOssName()) && CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(analysisBean.getOssName().trim().toUpperCase())) {
param.setOssName(CoCodeManager.OSS_INFO_UPPER_NAMES.get(analysisBean.getOssName().trim().toUpperCase()));
}
param.setHomepage(analysisBean.getHomepage().trim());
Map<String, Object> paramMap = ossService.checkExistsOssHomepage(param);
List<OssMaster> list = (List<OssMaster>) paramMap.get("homepage");
if (list != null && !list.isEmpty()) {
String sortOrder = list.get(0).getSOrder();
if ("1".equals(sortOrder)) {
diffMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".DUPLICATED");
} else {
diffMap.put(basicKey + (useGridSeq ? "."+analysisBean.getGridId() : ""), basicKey+".PARTIAL_DUPLICATED");
}
}
}
}
}
private boolean hasError(Map<String, String> errMap, String basicKey, String gridId, boolean useGridSeq) {
return errMap.containsKey(basicKey + (useGridSeq ? "."+gridId : ""));
}
@SuppressWarnings("unchecked")
@Override
public void setAppendix(String key, Object obj) {
if ("ossMaster".equals(key)) {
this.ossMaster = (OssMaster) obj;
} else if ("ossList".equals(key)) {
this.ossList = (List<OssMaster>) obj;
} else if ("ossAnalysis".equals(key)) {
this.ossAnalysis = (OssAnalysis) obj;
} else if ("analysisList".equals(key)) {
this.analysisList = (List<OssAnalysis>) obj;
}
}
@Override
protected String treatment(String paramvalue) {
return paramvalue;
}
public void setVALIDATION_TYPE(String vALID_TYPE) {
VALID_TYPE = vALID_TYPE;
}
}
| 31,698 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoAdminValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/T2CoAdminValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.domain.T2Code;
import oss.fosslight.domain.T2Users;
import oss.fosslight.service.CodeService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.validation.T2BasicValidator;
public class T2CoAdminValidator extends T2BasicValidator {
private CodeService codeService = (CodeService) getWebappContext().getBean(CodeService.class);
private T2UserService userService = (T2UserService) getWebappContext().getBean(T2UserService.class);
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
// 1) First, execute Default Check
super.customValidation(map, errMap);
// 2) Seconds
String targetKey = "CD_NO";
String targetKey2 = "";
// 코드 관리
if (CoConstDef.GRID_OPERATION_ADD.equals(map.get("OPER")) && map.containsKey(targetKey) && !errMap.containsKey(targetKey)) {
// 중목체크
T2Code vo = new T2Code();
vo.setCdNo(map.get(targetKey));
if (codeService.isExists(vo)) {
errMap.put(targetKey, targetKey + ".DUPLICATED");
}
}
// 코드 상세 등록 /수정
targetKey = "CD_DTL_NO";
if (map.containsKey("CD_DTL_NO.1")) {
// 중목체크
List<String> cdDtlList = new ArrayList<>();
for (int i = 1; map.containsKey(targetKey + "." + i); i++){
String _seqkey = targetKey + "." + i;
if (!errMap.containsKey(_seqkey)) {
String val = map.get(_seqkey);
if (cdDtlList.contains(val)) {
// 중목
errMap.put(_seqkey, targetKey + ".DUPLICATED");
} else {
cdDtlList.add(val);
}
}
}
}
// 사용자 등록 AD 계정 유효성 체크
targetKey = "USER_ID";
targetKey2 = "USER_PW";
if (map.containsKey(targetKey) && map.containsKey(targetKey2) && !errMap.containsKey(targetKey) && !errMap.containsKey(targetKey2)) {
// 기 등록 여부 체크
T2Users _param = new T2Users();
_param.setUserId(map.get(targetKey));
if (!isEmpty(_param.getUserId()) && userService.checkDuplicateId(_param)) {
errMap.put(targetKey, targetKey+".DUPLICATED");
}
String ldapFlag = CoCodeManager.getCodeExpString(CoConstDef.CD_SYSTEM_SETTING, CoConstDef.CD_LDAP_USED_FLAG);
if (CoConstDef.FLAG_YES.equals(ldapFlag)) { // configuration에서 LDAP을 선택시만 check함.
if (!isEmpty(map.get(targetKey2))) {
if (!userService.checkAdAccounts(map, targetKey, targetKey2, null)) {
if (map.containsKey("EMAIL") && !errMap.containsKey("EMAIL")) {
if (!userService.checkAdAccounts(map, "EMAIL", targetKey2, null)) {
errMap.put(targetKey2, targetKey2+".AUTH");
}
} else {
errMap.put(targetKey2, targetKey2+".AUTH");
}
}
}
}
}
targetKey = "EMAIL";
if (map.containsKey(targetKey) && !errMap.containsKey(targetKey)) {
// email 등록 여부 체크
String email = (String) map.get(targetKey);
if (!isEmpty(email)) {
List<T2Users> duplicateEmailList = userService.checkEmail(email);
if (duplicateEmailList.size() > 0) {
errMap.put(targetKey, targetKey+".DUPLICATED");
}
}
}
return;
}
}
| 4,137 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
DistributionValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/DistributionValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import oss.fosslight.domain.Project;
import oss.fosslight.validation.T2CoValidator;
public class DistributionValidator extends T2CoValidator {
private Project dataBean = null;
private String validType = "";
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
if (dataBean != null) {
// basic validation
String basicKey = "";
boolean isMod = !isEmpty(dataBean.getDistributeDeployTime());
// distributeName
{
basicKey = "DISTRIBUTE_NAME";
String errCd = checkBasicError(basicKey, dataBean.getDistributeName(), isMod);
if (!isEmpty(errCd)) {
errMap.put(basicKey, errCd);
}
}
// master category
{
basicKey = "DISTRIBUTE_MASTER_CATEGORY";
String errCd = checkBasicError(basicKey, dataBean.getDistributeMasterCategory(), isMod);
if (!isEmpty(errCd)) {
errMap.put(basicKey, errCd);
}
}
// model info
if (dataBean.getModelList() != null && !dataBean.getModelList().isEmpty()) {
// 중복체크
List<String> modelDuplCheckList = new ArrayList<>();
List<String> dupKeyList = new ArrayList<>();
for (Project bean : dataBean.getModelList()) {
String key = avoidNull(bean.getCategory()) + "|" + avoidNull(bean.getModelName()).trim().toUpperCase();
if (dupKeyList.contains(key)) {
modelDuplCheckList.add(key);
} else {
dupKeyList.add(key);
}
}
for (Project bean : dataBean.getModelList()) {
// model name
basicKey = "MODEL_NAME";
String errCd = checkBasicError(basicKey, bean.getModelName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else if (modelDuplCheckList.contains(avoidNull(bean.getCategory()) + "|" + avoidNull(bean.getModelName()).trim().toUpperCase())){
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".DUPLICATED");
} else if (avoidNull(bean.getModelName()).trim().length() < 2) {
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".MINLENGTH");
}
basicKey = "RELEASE_DATE";
errCd = checkBasicError(basicKey, bean.getReleaseDate());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
}
} else if ("Distribution".equalsIgnoreCase(validType)) {
errMap.put("VALID_MSG_MODEL_LIST", "MODEL_NAME.REQUIRED_INFO");
}
}
}
@Override
protected String treatment(String paramvalue) {
return paramvalue;
}
@Override
public void setAppendix(String key, Object obj) {
if ("project".equals(key)) {
this.dataBean = (Project) obj;
}
}
public void setValidType(String vType) {
this.validType = vType;
}
}
| 3,108 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2CoProjectValidator.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/validation/custom/T2CoProjectValidator.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.validation.custom;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.domain.BinaryAnalysisResult;
import oss.fosslight.domain.BinaryData;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssComponentsLicense;
import oss.fosslight.domain.OssLicense;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.service.AutoIdService;
import oss.fosslight.service.BinaryDataService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.OssService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SelfCheckService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.util.StringUtil;
import oss.fosslight.validation.T2CoValidator;
@Slf4j
public class T2CoProjectValidator extends T2CoValidator {
private SelfCheckService selfcheckService = (SelfCheckService) getWebappContext().getBean(SelfCheckService.class);
private ProjectService projectService = (ProjectService) getWebappContext().getBean(ProjectService.class);
private OssService ossService = (OssService) getWebappContext().getBean(OssService.class);
private T2UserService userService = (T2UserService) getWebappContext().getBean(T2UserService.class);
private FileService fileService = (FileService) getWebappContext().getBean(FileService.class);
private BinaryDataService binaryDataService = (BinaryDataService) getWebappContext().getBean(BinaryDataService.class);
private List<ProjectIdentification> ossComponetList = null;
private List<List<ProjectIdentification>> ossComponentLicenseList = null;
private Map<String, List<ProjectIdentification>> ossComponentLicenseListMap = null;
@SuppressWarnings("unused")
private List<String> noticeBinaryList = null;
private List<String> existsResultBinaryNameList = null;
// validation check level (일반사용자 or Admin)
private boolean checkForAdmin = false;
// 처리 구분(화면별)
private String PROC_TYPE = null;
private int LEVEL = -1;
private boolean ignoreExcludeDataFlag = false;
private String projectId = null;
public final String PROC_TYPE_BASICINFO = "BASIC";
public final String PROC_TYPE_IDENTIFICATION_PARTNER = "PARTNER";
public final String PROC_TYPE_IDENTIFICATION_SOURCE = "SRC";
public final String PROC_TYPE_IDENTIFICATION_BAT = "BAT";
public final String PROC_TYPE_IDENTIFICATION_BIN = "BIN";
public final String PROC_TYPE_IDENTIFICATION_ANDROID = "ANDROID";
public final String PROC_TYPE_SELFCHECK = "SELF";
public final String PROC_TYPE_IDENTIFICATION_BOM = "BOM";
public final String PROC_TYPE_IDENTIFICATION_BOM_MERGE = "BOM_MERGE";
public final String PROC_TYPE_PACKAGING = "PACKAGING";
public final String PROC_TYPE_DISTRBUTE = "DISTRIBUTE";
public final String PROC_TYPE_VERIFIY = "VERIFY";
public final int VALID_LEVEL_BASIC = 1;
public final int VALID_LEVEL_REQUEST = 2;
@Override
protected void customValidation(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
// 기본적인 유효성 체크만 필요한 경우
if (VALID_LEVEL_BASIC == LEVEL) {
if (!isEmpty(PROC_TYPE)) {
validateIdentificationBasic(map, errMap);
}
} else if (VALID_LEVEL_REQUEST == LEVEL) {
if (!isEmpty(PROC_TYPE)) {
if (PROC_TYPE_IDENTIFICATION_PARTNER.equals(PROC_TYPE)) {
validatePartnerRequest(map, errMap, diffMap);
} else {
validateIdentificationRequest(map, errMap, diffMap);
}
}
} else {
if (!isEmpty(PROC_TYPE)) {
switch (PROC_TYPE) {
case PROC_TYPE_BASICINFO: // 프로젝트 기본정보 validation
validateProjectBasicInfo(map, errMap);
break;
case PROC_TYPE_IDENTIFICATION_PARTNER: // 프로젝트 Identification
// 3rd용 유효성 체크
validateProjectPartner(map, errMap, diffMap, infoMap);
break;
case PROC_TYPE_IDENTIFICATION_SOURCE: // 프로젝트 Identification // src용 유효성 체크
case PROC_TYPE_IDENTIFICATION_BIN: // 프로젝트 Identification src용 // 유효성 체크
case PROC_TYPE_IDENTIFICATION_ANDROID: // 프로젝트 Identification // src용 유효성 체크
validateProjectSrc(map, errMap, diffMap, infoMap);
break;
case PROC_TYPE_IDENTIFICATION_BAT: // 프로젝트 Identification bat용 // 유효성 체크
validateProjectBat(map, errMap, diffMap, infoMap);
break;
case PROC_TYPE_PACKAGING: // 프로젝트 Identification Packaging용 유효성 // 체크
validateProjectPackaging(map, errMap);
break;
case PROC_TYPE_DISTRBUTE: // 프로젝트 Identification Packaging용 유효성 // 체크
validateProjectDistribute(map, errMap);
break;
case PROC_TYPE_VERIFIY:
validateProjectVerify(map, errMap);
break;
case PROC_TYPE_IDENTIFICATION_BOM_MERGE:
validateProjectBomMerge(map, errMap, diffMap, infoMap);
break;
case PROC_TYPE_SELFCHECK :
validateSelfCheck(map, errMap);
break;
}
}
}
}
private void validatePartnerRequest(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap) {
//ossComponetList==> grid 데이터(사용자 등록 데이터)
if (ossComponetList != null) {
// validation case에 따라 필요한 정보를 추출한다.
List<String> ossNameList = new ArrayList<>();
for (ProjectIdentification bean : ossComponetList) {
if (!isEmpty(bean.getOssName()) && !ossNameList.contains(avoidNull(bean.getOssName()))) {
ossNameList.add(avoidNull(bean.getOssName()));
}
}
Map<String, OssMaster> ossInfoByName = null;
ossInfoByName = CoCodeManager.OSS_INFO_UPPER;
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
String basicKey = "";
String gridKey = "";
if ("-".equals(bean.getOssName())) {
// license check
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
} else if (isEmpty(bean.getLicenseName())) {
errMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
} else if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(bean.getLicenseName().toUpperCase())) {
diffMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
}
}
// FILE PATH
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는 파라미터 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
}
continue;
}
String checkKey = bean.getOssName().trim() +"_"+ avoidNull(bean.getOssVersion()).trim();
checkKey = checkKey.toUpperCase();
OssMaster ossBean = ossInfoByName.get(checkKey);
List<ProjectIdentification> licenseList = null;
if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getGridId())) {
licenseList = ossComponentLicenseListMap.get(bean.getGridId());
}
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
if (isEmpty(bean.getOssName()) && !checkNonPermissiveLicense(licenseList)) {
errMap.put("OSS_NAME."+bean.getComponentId(), "OSS_NAME.REQUIRED");
}
// oss 등록 여부 체크
if (!isEmpty(bean.getOssName()) && !diffMap.containsKey("OSS_NAME." + bean.getComponentId())) {
String licenseText = "";
if (ossBean != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(ossBean.getOssLicenses(), true); // msgType return
}
if (!ossInfoByName.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfoByName, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.UNCONFIRMED");
}
}
// license 등록 여부 (등록되어 있는 오픈소스이나 사용자가 입력한 라이선스는 포함하고 있지 않은 경우 & Detected License도 미 포함인 경우)
else if (!hasOssLicense2(ossBean, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
// Declared License가 미포함인 경우
else if (!hasOssLicense2(ossBean, licenseList, false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(ossBean, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
// 관리되지 않은 라이선스가 포함되어 있는 경우
if (licenseList != null) {
for (ProjectIdentification license : licenseList) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (isEmpty(license.getLicenseName())) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
break;
}
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())
&& !ossInfoByName.containsKey(checkKey)) {
if (CommonFunction.isAdmin() && !errMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
} else if (!diffMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
}
break;
}
}
}
if (!errMap.containsKey("LICENSE_NAME." + bean.getComponentId()) && licenseList != null) {
boolean hasSelected = false;
for (ProjectIdentification license : licenseList) {
if (!CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
hasSelected = true;
break;
}
}
if (!hasSelected) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.NOLICENSE");
}
else if (licenseList != null // bom merge licese 정보를 이용해서 dual license 중복 여부를 확인한다. // oss list에 등록되어 있고, dual license를 가지는 oss에 대해서만 체크
&& !CoConstDef.FLAG_YES.equals(bean.getExcludeYn())
&& ossInfoByName.containsKey(checkKey)
&& CoConstDef.LICENSE_DIV_MULTI.equals(ossBean.getLicenseDiv())
&& CoConstDef.FLAG_YES.equals(ossBean.getDualLicenseFlag()) ) {
if (checkOROperation(licenseList, ossBean)) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.INCLUDE_DUAL_OPERATE");
}
}
}
}
}
}
private boolean checkNonPermissiveLicense(List<ProjectIdentification> licenseList) {
if (licenseList != null) {
for (ProjectIdentification license : licenseList) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (!isEmpty(license.getLicenseName())
&& CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER.get(license.getLicenseName().toUpperCase());
if (master != null
&& !CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationDisclosingSrcYn()))
&& !CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationNotificationYn()))) {
return true;
}
}
}
}
return false;
}
@SuppressWarnings("unchecked")
private void validateIdentificationRequest(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap) {
// ossComponetList==> grid 데이터(사용자 등록 데이터)
if (ossComponetList != null) {
// validation case에 따라 필요한 정보를 추출한다.
List<String> ossNameList = new ArrayList<>();
for (ProjectIdentification bean : ossComponetList) {
if (!isEmpty(bean.getOssName()) && !ossNameList.contains(avoidNull(bean.getOssName()))) {
ossNameList.add(avoidNull(bean.getOssName()));
}
}
Map<String, OssMaster> ossInfoByName = null;
ossInfoByName = CoCodeManager.OSS_INFO_UPPER;
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
String basicKey = "";
String gridKey = "";
if ("-".equals(bean.getOssName())) {
// license check
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
} else if (isEmpty(bean.getLicenseName())) {
errMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
} else if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(bean.getLicenseName().toUpperCase())) {
diffMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
}
}
// FILE PATH
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는
// 파라미터 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
}
continue;
}
String checkKey = bean.getOssName().trim() + "_" + avoidNull(bean.getOssVersion()).trim();
checkKey = checkKey.toUpperCase();
OssMaster ossBean = ossInfoByName.get(checkKey);
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName(), CommonFunction.isIgnoreLicense(bean.getLicenseName()));
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
// oss 등록 여부 체크
if (!CommonFunction.isIgnoreLicense(bean.getLicenseName())) {
// oss 등록 여부 체크
if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& !ossInfoByName.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfoByName, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
}
} else {
if (CommonFunction.isAdmin()) {
errMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.UNCONFIRMED");
} else {
diffMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.UNCONFIRMED");
}
}
}
// license 등록 여부 (등록되어 있는 오픈소스이나 사용자가 입력한 라이선스는 포함하고 있지 않은
// 경우)
else if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
String licenseText = "";
if (ossBean != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(ossBean.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(ossBean, bean.getOssComponentsLicenseList())) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(ossBean, bean.getOssComponentsLicenseList(), false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(ossBean, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getComponentId())) {
List<ProjectIdentification> licenseList = ossComponentLicenseListMap.get(bean.getComponentId());
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(ossBean, licenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(ossBean, licenseList, false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(ossBean, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
}
} else {
if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& !ossInfoByName.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfoByName, bean.getComponentId())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
}
}
}
else if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& ossInfoByName.containsKey(checkKey)
) {
String licenseText = "";
if (ossBean != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(ossBean.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(ossBean, bean.getOssComponentsLicenseList())) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(ossBean, bean.getOssComponentsLicenseList(), false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(ossBean, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getComponentId())) {
List<ProjectIdentification> licenseList = ossComponentLicenseListMap.get(bean.getComponentId());
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(ossBean, licenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(ossBean, licenseList, false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(ossBean, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
}
}
// 관리되지 않은 라이선스가 포함되어 있는 경우
if (bean.getOssComponentsLicenseList() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (isEmpty(license.getLicenseName())) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
break;
}
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())
&& !ossInfoByName.containsKey(checkKey)) {
if (CommonFunction.isAdmin()
&& !errMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
} else if (!diffMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
}
break;
}
}
}
if (!errMap.containsKey("LICENSE_NAME." + bean.getComponentId())
&& bean.getOssComponentsLicenseList() != null) {
boolean hasSelected = false;
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (!CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
hasSelected = true;
break;
}
}
if (!hasSelected) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.NOLICENSE");
}
// bom merge licese 정보를 이용해서 dual license 중복 여부를 확인한다.
// oss list에 등록되어 있고, dual license를 가지는 oss에 대해서만 체크
else if (PROC_TYPE_IDENTIFICATION_BOM_MERGE.equals(PROC_TYPE) && !isEmpty(bean.getRefComponentId())
&& !CoConstDef.FLAG_YES.equals(bean.getExcludeYn()) && ossInfoByName.containsKey(checkKey)
&& CoConstDef.LICENSE_DIV_MULTI.equals(ossBean.getLicenseDiv())
&& CoConstDef.FLAG_YES.equals(ossBean.getDualLicenseFlag())) {
// 참조 대상 source 에서 현재 설정된 정보를 취득한다.
ProjectIdentification param = new ProjectIdentification();
param.setComponentId(bean.getRefComponentId());
Map<String, Object> checkLicenseInfo = projectService.identificationSubGrid(param);
if (checkLicenseInfo != null && checkLicenseInfo.containsKey("rows")
&& checkOROperation((List<ProjectIdentification>) checkLicenseInfo.get("rows"), ossBean)) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.INCLUDE_DUAL_OPERATE");
}
} else if (PROC_TYPE_IDENTIFICATION_PARTNER.equals(PROC_TYPE)
&& !CoConstDef.FLAG_YES.equals(bean.getExcludeYn()) && ossInfoByName.containsKey(checkKey)
&& CoConstDef.LICENSE_DIV_MULTI.equals(ossBean.getLicenseDiv())
&& CoConstDef.FLAG_YES.equals(ossBean.getDualLicenseFlag())) {
List<ProjectIdentification> licenseList = findLicense(bean.getGridId());
if (licenseList != null && !licenseList.isEmpty() && checkOROperation(licenseList, ossBean)) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.INCLUDE_DUAL_OPERATE");
}
}
}
}
}
}
@SuppressWarnings("unused")
private void validateIdentificationBasic(Map<String, String> map, Map<String, String> errMap) {
Map<String, OssMaster> ossInfo = null;
// dataMap을 사용하지 않고, request정보를 직접 참조
if (ossComponetList != null) {
String basicKey = "";
String gridKey = "";
String errKey = "";
List<ProjectIdentification> licenseList = null;
// 설정된 oss 정보를 DB에서 취득한다.
OssMaster ossParam = new OssMaster();
ossParam.setOssNames(getOssNames());
if (ossParam.getOssNames() != null && ossParam.getOssNames().length > 0) {
ossInfo = CoCodeManager.OSS_INFO_UPPER;
}
if (ossInfo == null) {
ossInfo = new HashMap<>();
}
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
// oss name
{
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
}
// oss version
{
basicKey = "OSS_VERSION";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getOssVersion(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
}
// License
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
}
// download location
// homepage
// V-DIFF 및 편집중인 상태에서 oss 의 라이선스가 변경되어 oss는 multi이나, 라이선스가 하나만
// 등록되는 현상 대응
if (!isEmpty(bean.getOssName())) {
String checkKey = bean.getOssName().trim() + "_" + avoidNull(bean.getOssVersion()).trim();
checkKey = checkKey.toUpperCase();
licenseList = findLicense(bean.getGridId());
if (licenseList != null && ossInfo.containsKey(checkKey)) {
OssMaster master = ossInfo.get(checkKey);
if (CoConstDef.LICENSE_DIV_MULTI.equals(master.getLicenseDiv())) {
// 멀티 라이선스로 등록된 오픈소스에 싱글 라이선스를 적용한 경우
if (licenseList == null || licenseList.size() < master.getOssLicenses().size()) {
// oss master 가 single에서 multi로 변경된 경우,
// save하면서 multi로 등록한다.
}
} else {
// 싱글 라이선스로 등록된 오픈소스에 멀티 라이선스를 적용한 경우
}
} else {
// 등록되지 않은 오픈소스에 멀티/듀얼 라이선스를 적용한 경우
}
}
{
basicKey = "COPYRIGHT";
gridKey = StringUtil.convertToCamelCase(basicKey);
try {
if (!isEmpty(bean.getCopyrightText())) {
String copyrightText = new String(bean.getCopyrightText().getBytes("UTF-8"), "UTF-8");
Pattern pattern = Pattern.compile("[\uD83C-\uDBFF\uDC00-\uDFFF]+");
Matcher matcher = pattern.matcher(copyrightText);
List<String> matchList = new ArrayList<String>();
while (matcher.find()) {
String group = matcher.group().replaceAll("-", "");
if (!isEmpty(matcher.group()) && group.length() > 0) {
matchList.add(group);
}
}
if (matchList.size() > 0) {
String key = isEmpty(bean.getBinaryName()) ? bean.getFilePath() : bean.getBinaryName();
key += " | " + bean.getOssName() + " | " + bean.getOssVersion( )+ " | " + bean.getLicenseName();
errMap.put(basicKey + "." + key, "COPYRIGHT.INCLUDE_IMOJI");
}
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage());
}
}
}
}
}
@SuppressWarnings("unchecked")
private void validateProjectBomMerge(Map<String, String> map, Map<String, String> errMap,
Map<String, String> diffMap, Map<String, String> infoMap) {
// ossComponetList==> grid 데이터(사용자 등록 데이터)
if (ossComponetList != null) {
// validation case에 따라 필요한 정보를 추출한다.
List<String> ossNameList = new ArrayList<>();
for (ProjectIdentification bean : ossComponetList) {
if (!isEmpty(bean.getOssName()) && !ossNameList.contains(avoidNull(bean.getOssName()))) {
ossNameList.add(avoidNull(bean.getOssName()));
}
}
Map<String, OssMaster> ossInfoByName = null;
ossInfoByName = CoCodeManager.OSS_INFO_UPPER;
// check deactivate oss info
List<String> deactivateOssList = ossService.getDeactivateOssList();
deactivateOssList.replaceAll(String::toUpperCase);
for (ProjectIdentification bean : ossComponetList) {
boolean diffMapLicense = false;
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
String basicKey = "";
String gridKey = "";
if ("-".equals(bean.getOssName())) {
// license check
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (bean.getLicenseName().split(",").length > 1) {
errMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.INCLUDE_MULTI_OPERATE");
} else {
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
} else if (isEmpty(bean.getLicenseName())) {
errMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
} else if (!CommonFunction.checkLicense(bean.getLicenseName())) {
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
} else {
diffMap.put(basicKey + "." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
diffMapLicense = true;
}
} else if (CommonFunction.checkLicense(bean.getLicenseName())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(bean.getLicenseName().trim().toUpperCase());
if (master != null && CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationDisclosingSrcYn()))) {
diffMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.REQUIRED2");
}
}
}
}
// FILE PATH
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는
// 파라미터 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
}
continue;
}
String checkKey = avoidNull(bean.getOssName(), "").trim() + "_" + avoidNull(bean.getOssVersion(), "").trim();
checkKey = checkKey.toUpperCase();
OssMaster checkOSSMaster = ossInfoByName.get(checkKey);
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName(), CommonFunction.isIgnoreLicense(bean.getLicenseName()));
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getComponentId(), errCd);
}
if(checkOSSMaster != null) {
if(CoConstDef.FLAG_YES.equals(checkOSSMaster.getDeactivateFlag())){
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getComponentId(), "OSS_NAME.DEACTIVATED");
} else {
diffMap.put(basicKey + "." + bean.getComponentId(), "OSS_NAME.DEACTIVATED");
}
}
} else {
boolean deactivateFlag = false;
if(!isEmpty(bean.getOssName())) {
if(deactivateOssList.contains(bean.getOssName().toUpperCase())) {
deactivateFlag = true;
}
if(deactivateFlag) {
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getComponentId(), "OSS_NAME.DEACTIVATED");
} else {
diffMap.put(basicKey + "." + bean.getComponentId(), "OSS_NAME.DEACTIVATED");
}
}
}
}
// oss 등록 여부 체크
if (!CommonFunction.isIgnoreLicense(bean.getLicenseName())) {
// oss 등록 여부 체크
if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& !ossInfoByName.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfoByName, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
}
} else {
if (CommonFunction.isAdmin()) {
errMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.UNCONFIRMED");
} else {
diffMap.put("OSS_NAME." + bean.getComponentId(), "OSS_NAME.UNCONFIRMED");
}
}
}
// license 등록 여부 (등록되어 있는 오픈소스이나 사용자가 입력한 라이선스는 포함하고 있지 않은
// 경우)
else if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("LICENSE_NAME." + bean.getComponentId())) {
String licenseText = "";
if (checkOSSMaster != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(checkOSSMaster.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()
&& !isEmpty(bean.getLicenseName())) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(checkOSSMaster, bean.getOssComponentsLicenseList())) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(checkOSSMaster, bean.getOssComponentsLicenseList(), false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(checkOSSMaster, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getComponentId())) {
List<ProjectIdentification> licenseList = ossComponentLicenseListMap.get(bean.getComponentId());
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(checkOSSMaster, licenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(checkOSSMaster, licenseList, false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(checkOSSMaster, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
}
} else {
if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& !ossInfoByName.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfoByName, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.UNCONFIRMED");
}
}
}
else if (!errMap.containsKey("OSS_NAME." + bean.getComponentId())
&& !errMap.containsKey("OSS_VERSION." + bean.getComponentId())
&& ossInfoByName.containsKey(checkKey)
) {
String licenseText = "";
if (checkOSSMaster != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(checkOSSMaster.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(checkOSSMaster, bean.getOssComponentsLicenseList())) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(checkOSSMaster, bean.getOssComponentsLicenseList(), false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(checkOSSMaster, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getComponentId())) {
List<ProjectIdentification> licenseList = ossComponentLicenseListMap.get(bean.getComponentId());
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(checkOSSMaster, licenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(checkOSSMaster, licenseList, false)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
diffMapLicense = true;
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(checkOSSMaster, licenseList)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
}
}
{ // ADD OSS_VERSION REQUIRED MSG
if (!isEmpty(bean.getOssName())
&& !bean.getOssName().equals("-")
&& isEmpty(bean.getOssVersion())) {
if (!errMap.containsKey("OSS_VERSION." + bean.getComponentId())) {
if (ossService.checkOssVersionDiff(bean.getOssName()) > 0) {
diffMap.put("OSS_VERSION." + bean.getComponentId(), "OSS_VERSION.REQUIRED");
}
}
}
}
// 관리되지 않은 라이선스가 포함되어 있는 경우
if (bean.getOssComponentsLicenseList() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (isEmpty(license.getLicenseName())) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.REQUIRED");
break;
}
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())
&& !ossInfoByName.containsKey(checkKey)) {
if (CommonFunction.isAdmin()) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
} else {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.UNCONFIRMED");
diffMapLicense = true;
}
break;
}
}
}
if (!errMap.containsKey("LICENSE_NAME." + bean.getComponentId())
&& bean.getOssComponentsLicenseList() != null) {
boolean hasSelected = false;
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (!CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
hasSelected = true;
break;
}
}
if (!hasSelected) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.NOLICENSE");
}
// bom merge licese 정보를 이용해서 dual license 중복 여부를 확인한다.
// oss list에 등록되어 있고, dual license를 가지는 oss에 대해서만 체크
else if (!isEmpty(bean.getRefComponentId()) && !CoConstDef.FLAG_YES.equals(bean.getExcludeYn())
&& ossInfoByName.containsKey(checkKey)
&& CoConstDef.LICENSE_DIV_MULTI.equals(checkOSSMaster.getLicenseDiv())
&& CoConstDef.FLAG_YES.equals(checkOSSMaster.getDualLicenseFlag())) {
// 참조 대상 source 에서 현재 설정된 정보를 취득한다.
ProjectIdentification param = new ProjectIdentification();
param.setComponentId(bean.getRefComponentId());
Map<String, Object> checkLicenseInfo = projectService.identificationSubGrid(param);
if (checkLicenseInfo != null && checkLicenseInfo.containsKey("rows")
&& checkOROperation((List<ProjectIdentification>) checkLicenseInfo.get("rows"), checkOSSMaster)) {
errMap.put("LICENSE_NAME." + bean.getComponentId(), "LICENSE_NAME.INCLUDE_DUAL_OPERATE");
if (diffMapLicense) { // 일반사용자의 경우 error message 우선순위가 높은 대상들이 diff message로 출력하기 때문에 중복등록 방지를 해야함.
diffMap.remove("LICENSE_NAME." + bean.getComponentId());
}
}
}
}
if (ossInfoByName.containsKey(checkKey)) {
// oss Download_location 체크
if (!errMap.containsKey("DOWNLOAD_LOCATION." + bean.getComponentId())
&& !diffMap.containsKey("DOWNLOAD_LOCATION." + bean.getComponentId())
&& !isEmpty(bean.getDownloadLocation())) {
if (checkOssData(checkOSSMaster, bean.getDownloadLocation(), "DOWNLOAD")) {
diffMap.put("DOWNLOAD_LOCATION." + bean.getComponentId(), "DOWNLOAD_LOCATION.DIFFERENT");
}
}
// oss Homepage 체크
if (!errMap.containsKey("HOMEPAGE." + bean.getComponentId())
&& !diffMap.containsKey("HOMEPAGE." + bean.getComponentId())
&& !isEmpty(bean.getHomepage())) {
if (checkOssData(checkOSSMaster, bean.getHomepage(), "HOMEPAGE")) {
diffMap.put("HOMEPAGE." + bean.getComponentId(), "HOMEPAGE.DIFFERENT");
}
}
if(!diffMap.containsKey("LICENSE_NAME." + bean.getComponentId()) && !errMap.containsKey("LICENSE_NAME." + bean.getComponentId()) && !isEmpty(bean.getLicenseName())) {
String licenseText = CommonFunction.makeRecommendedLicenseString(checkOSSMaster, bean);
if(!isEmpty(licenseText)) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Recommended : " + licenseText );
}
}
if (!diffMap.containsKey("COPYRIGHT_TEXT." + bean.getComponentId()) && !isEmpty(bean.getCopyrightText())) {
if (!checkOssData(ossInfoByName.get(checkKey), bean.getCopyrightText(), "COPYRIGHT")) {
infoMap.put("COPYRIGHT_TEXT." + bean.getComponentId(), "COPYRIGHT.DIFFERENT");
}
}
}
}
}
}
private boolean checkOssData(OssMaster ossMaster, String val, String kind) {
String getData = "";
String getData2 = "";
// null point exception 발생으로 일단 return 추가
if (ossMaster == null || isEmpty(val)) {
return false;
}
String[] splitCheckVal = null;
if (kind.equals("COPYRIGHT")) {
splitCheckVal = new String[] {val};
} else {
splitCheckVal = val.split(",");
}
switch (kind) {
case "DOWNLOAD":
getData = ossMaster.getDownloadLocation();
getData2 = ossMaster.getDownloadLocationGroup();
if (getData.contains(",") && isEmpty(getData2)) {
ossMaster.setDownloadLocationGroup(getData);
getData2 = getData;
}
break;
case "HOMEPAGE":
getData = ossMaster.getHomepage();
break;
case "COPYRIGHT":
getData = avoidNull(ossMaster.getCopyright(), "").trim();
break;
case "LICENSE":
getData = ossMaster.getOssLicenseText();
break;
default:
break;
}
List<String> checkOssNameUrl = CoCodeManager.getCodeNames(CoConstDef.CD_CHECK_OSS_NAME_URL);
boolean splitFlag = false;
for (String checkVal : splitCheckVal) {
if (kind.equals("COPYRIGHT")) {
if (getData.equalsIgnoreCase(checkVal)) return true;
} else {
checkVal = linkPatternCompile(checkOssNameUrl, checkVal);
splitFlag = checkVal.split("//").length == 2 ? true : false;
if (!isEmpty(getData) && !kind.equals("DOWNLOAD")) {
if (kind.equals("HOMEPAGE")) {
if ((checkVal.startsWith("http://") || checkVal.startsWith("https://")) && splitFlag) {
checkVal = checkVal.split("//")[1];
}
if (checkVal.startsWith("www.")) {
checkVal = checkVal.substring(5, checkVal.length());
}
if (getData.contains(";")) {
getData = getData.split(";")[0];
}
getData = linkPatternCompile(checkOssNameUrl, getData);
if (getData.startsWith("http://") || getData.startsWith("https://")) {
getData = getData.split("//")[1];
}
if (getData.startsWith("www.")) {
getData = getData.substring(5, getData.length());
}
}
if (!getData.toUpperCase().equals(checkVal.toUpperCase())) {
return true;
}
}
if (kind.equals("DOWNLOAD") && !isEmpty(getData2)){
if ((checkVal.startsWith("http://") || checkVal.startsWith("https://")) && splitFlag) {
checkVal = checkVal.split("//")[1];
}
if (checkVal.startsWith("www.")) {
checkVal = checkVal.substring(5, checkVal.length());
}
boolean chkFlag = false;
for (String downloadLocation : getData2.split(",")){
downloadLocation = linkPatternCompile(checkOssNameUrl, downloadLocation);
if (downloadLocation.startsWith("http://") || downloadLocation.startsWith("https://")) {
downloadLocation = downloadLocation.split("//")[1];
}
if (downloadLocation.startsWith("www.")) {
downloadLocation = downloadLocation.substring(5, downloadLocation.length());
}
if (downloadLocation.toUpperCase().equals(checkVal.toUpperCase())) {
chkFlag = true;
break;
}
}
if (!chkFlag) {
return true;
}
} else if (kind.equals("DOWNLOAD") && !isEmpty(getData) && isEmpty(getData2)){
if ((checkVal.startsWith("http://") || checkVal.startsWith("https://")) && splitFlag) {
checkVal = checkVal.split("//")[1];
}
if (checkVal.startsWith("www.")) {
checkVal = checkVal.substring(5, checkVal.length());
}
getData = linkPatternCompile(checkOssNameUrl, getData);
if (getData.startsWith("http://") || getData.startsWith("https://")) {
getData = getData.split("//")[1];
}
if (getData.startsWith("www.")) {
getData = getData.substring(5, getData.length());
}
if (!getData.toUpperCase().equals(checkVal.toUpperCase())) {
return true;
}
}
}
}
return false;
}
private String linkPatternCompile(List<String> checkOssNameUrl, String checkVal) {
int urlSearchSeq = -1;
int seq = 0;
for (String url : checkOssNameUrl) {
if (urlSearchSeq == -1 && checkVal.contains(url)) {
urlSearchSeq = seq;
break;
}
seq++;
}
Pattern p = null;
if (checkVal.startsWith("git://")) {
checkVal = checkVal.replace("git://", "https://");
} else if (checkVal.startsWith("ftp://")) {
checkVal = checkVal.replace("ftp://", "https://");
} else if (checkVal.startsWith("svn://")) {
checkVal = checkVal.replace("svn://", "https://");
} else if (checkVal.startsWith("git@")) {
checkVal = checkVal.replace("git@", "https://");
}
if (checkVal.contains(".git")) {
if (checkVal.endsWith(".git")) {
checkVal = checkVal.substring(0, checkVal.length()-4);
} else {
if (checkVal.contains("#")) {
checkVal = checkVal.substring(0, checkVal.indexOf("#"));
checkVal = checkVal.substring(0, checkVal.length()-4);
}
}
}
String[] downloadlocationUrlSplit = checkVal.split("/");
if (downloadlocationUrlSplit[downloadlocationUrlSplit.length-1].indexOf("#") > -1) {
checkVal = checkVal.substring(0, checkVal.indexOf("#"));
}
if ( urlSearchSeq > -1 ) {
switch(urlSearchSeq) {
case 0: // github
if (checkVal.contains("www.")) {
checkVal = checkVal.replace("www.", "");
}
p = Pattern.compile("((http|https)://github.com/([^/]+)/([^/]+))");
break;
case 1: // npm
case 6: // npm
if (checkVal.contains("/package/@")) {
p = Pattern.compile("((http|https)://www.npmjs.(org|com)/package/([^/]+)/([^/]+))");
}else {
p = Pattern.compile("((http|https)://www.npmjs.(org|com)/package/([^/]+))");
}
break;
case 2: // pypi
p = Pattern.compile("((http|https)://pypi.org/project/([^/]+))");
break;
case 3: // maven
p = Pattern.compile("((http|https)://mvnrepository.com/artifact/([^/]+)/([^/]+))");
break;
case 4: // pub
p = Pattern.compile("((http|https)://pub.dev/packages/([^/]+))");
break;
case 5: // cocoapods
p = Pattern.compile("((http|https)://cocoapods.org/pods/([^/]+))");
break;
case 7:
p = Pattern.compile("((http|https)://android.googlesource.com/platform/(.*))");
break;
case 8:
p = Pattern.compile("((http|https)://www.nuget.org/packages/([^/]+))");
break;
case 9:
p = Pattern.compile("((http|https)://stackoverflow.com/revisions/([^/]+)/([^/]+))");
break;
default:
p = Pattern.compile("(.*)");
break;
}
Matcher m = p.matcher(checkVal);
while (m.find()) {
checkVal = m.group(0);
}
}
return checkVal;
}
private boolean hasOssLicense(OssMaster ossMaster, List<OssComponentsLicense> list) {
return hasOssLicense(ossMaster, list, true);
}
private boolean hasOssLicense(OssMaster ossMaster, List<OssComponentsLicense> list, boolean detectedLicenseCheck) {
if (ossMaster == null) {
return true;
}
// license nick name을 포함한 라이선스 명 list를 구성
List<String> checkLicenseNameList = new ArrayList<>(); // declared License
List<String> detectedLicenseList = ossMaster.getDetectedLicenses(); // detected License
if (detectedLicenseList == null) {
detectedLicenseList = new ArrayList<>();
}
for (OssLicense license : ossMaster.getOssLicenses()) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(license.getLicenseName().toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
if (detectedLicenseCheck) {
if (detectedLicenseList != null) {
for (String licenseName : detectedLicenseList) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseName.toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(licenseName.toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName().toUpperCase());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
}
} else {
detectedLicenseList = detectedLicenseList.stream().map(dl -> dl.toUpperCase()).collect(Collectors.toList());
}
boolean declaredLicenseEmptyCheck = true;
for (OssComponentsLicense license : list) {
// 포함되어 있지 않은 라이선스가 하나라도 존재한다면 false
String licenseName = avoidNull(license.getLicenseName()).trim().toUpperCase();
if (!detectedLicenseCheck && detectedLicenseList.contains(licenseName) && !checkLicenseNameList.contains(licenseName)) {
continue;
}
if (!CoConstDef.FLAG_YES.equals(license.getExcludeYn())
&& !checkLicenseNameList.contains(licenseName)) {
return false;
} else {
declaredLicenseEmptyCheck = false;
}
}
if (declaredLicenseEmptyCheck) {
return false;
}
return true;
}
private boolean hasOssLicense(OssMaster ossMaster, String LicenseName, String exclude) {
return hasOssLicense(ossMaster, LicenseName, exclude, true);
}
private boolean hasOssLicense(OssMaster ossMaster, String LicenseName, String exclude, boolean detectedLicenseCheck) {
if (ossMaster == null) {
return true;
}
// license nick name을 포함한 라이선스 명 list를 구성
List<String> checkLicenseNameList = new ArrayList<>();
List<String> detectedLicenseList = ossMaster.getDetectedLicenses();
String[] LicenseNames = LicenseName.split("AND|OR|\\,");
if (detectedLicenseList == null) {
detectedLicenseList = new ArrayList<>();
}
for (OssLicense license : ossMaster.getOssLicenses()) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(license.getLicenseName().toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
if (detectedLicenseCheck) {
if (detectedLicenseList != null) {
for (String licenseName : detectedLicenseList) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseName.toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(licenseName.toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName().toUpperCase());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
}
}
// 포함되어 있지 않은 라이선스가 하나라도 존재한다면 false
for (String LicenseNm : LicenseNames){
if (!detectedLicenseCheck && detectedLicenseList.contains(LicenseNm)) {
continue;
}
if (!CoConstDef.FLAG_YES.equals(exclude)
&& !checkLicenseNameList.contains(avoidNull(LicenseNm).trim().toUpperCase())) {
return false;
}
}
return true;
}
private boolean hasOssLicense2(OssMaster ossMaster, List<ProjectIdentification> list){
return hasOssLicense2(ossMaster, list, true);
}
private boolean hasOssLicense2(OssMaster ossMaster, List<ProjectIdentification> list, boolean detectedLicenseCheck) {
// license nick name을 포함한 라이선스 명 list를 구성
List<String> checkLicenseNameList = new ArrayList<>(); // declared License
List<String> detectedLicenseList = ossMaster.getDetectedLicenses(); // detected License
if (detectedLicenseList == null) {
detectedLicenseList = new ArrayList<>();
}
if (ossMaster != null) {
for (OssLicense license : ossMaster.getOssLicenses()) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(license.getLicenseName().toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName().toUpperCase());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
if (detectedLicenseCheck) {
if (detectedLicenseList != null) {
for (String licenseName : detectedLicenseList) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseName.toUpperCase())) {
LicenseMaster _temp = CoCodeManager.LICENSE_INFO_UPPER.get(licenseName.toUpperCase());
checkLicenseNameList.add(_temp.getLicenseName().toUpperCase());
if (!isEmpty(_temp.getShortIdentifier())) {
checkLicenseNameList.add(_temp.getShortIdentifier().toUpperCase());
}
if (!isEmpty(_temp.getLicenseNameTemp())) {
checkLicenseNameList.add(_temp.getLicenseNameTemp().toUpperCase());
}
// nick name이 등록되어 있다면 닉네임도 포함시킨다.
if (_temp.getLicenseNicknameList() != null) {
for (String s : _temp.getLicenseNicknameList()) {
if (!isEmpty(s)) {
checkLicenseNameList.add(s.toUpperCase());
}
}
}
}
}
}
} else {
detectedLicenseList = detectedLicenseList.stream().map(dl -> dl.toUpperCase()).collect(Collectors.toList());
}
}
if (list != null) {
boolean declaredLicenseEmptyCheck = true; // detected License만 사용할 경우 check
for (ProjectIdentification license : list) {
// 포함되어 있지 않은 라이선스가 하나라도 존재한다면 false
String licenseName = avoidNull(license.getLicenseName()).trim().toUpperCase();
if (!detectedLicenseCheck && detectedLicenseList.contains(licenseName) && !checkLicenseNameList.contains(licenseName)) {
continue;
}
if (!CoConstDef.FLAG_YES.equals(license.getExcludeYn())
&& !checkLicenseNameList.contains(licenseName)) {
return false;
} else {
declaredLicenseEmptyCheck = false;
}
}
if (declaredLicenseEmptyCheck) {
return false;
}
}
return true;
}
private boolean checkNonVersionOss(Map<String, OssMaster> ossInfoByName, String s) {
return CoCodeManager.OSS_INFO_UPPER_NAMES.containsKey(s.toUpperCase());
}
private void validateProjectVerify(Map<String, String> map, Map<String, String> errMap) {
// Check, if you apply for exceptional notice file 체크인 경우 basic
// validator 결과를 무시한다.
for (String str : map.keySet()){
if (str.contains("PACKAGING@")){
if (!errMap.containsKey(str) && isEmpty(map.get(str))) {
errMap.put(str, str+".REQUIRED");
}
}
}
}
private void validateProjectDistribute(Map<String, String> map, Map<String, String> errMap) {
// TODO Auto-generated method stub
}
private void validateProjectPackaging(Map<String, String> map, Map<String, String> errMap) {
// TODO Auto-generated method stub
}
private void validateProjectBat(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
validateProjectGrid(map, errMap, diffMap, infoMap);
}
private void validateProjectSrc(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
validateProjectGrid(map, errMap, diffMap, infoMap);
}
private void validateProjectPartner(Map<String, String> map, Map<String, String> errMap,
Map<String, String> diffMap, Map<String, String> infoMap) {
validateProjectGrid(map, errMap, diffMap, infoMap);
}
private void validateSelfCheck(Map<String, String> map, Map<String, String> errMap){
String targetName = "";
Project prj = new Project();
String prjId = map.get("PRJ_ID");
String prjName = map.get("PRJ_NAME");
String prjVersion = map.get("PRJ_VERSION");
targetName = "PRJ_NAME";
if (!errMap.containsKey(targetName)) {
prj.setPrjId(prjId);
prj.setPrjName(prjName);
prj.setPrjVersion(prjVersion);
boolean exist = selfcheckService.existProjectData(prj);
if (exist) {
errMap.put(targetName, targetName + ".DUPLICATED");
}
}
}
private void validateProjectBasicInfo(Map<String, String> map, Map<String, String> errMap) {
String targetName = "";
String targetNameSub = "";
// PRJ_NAME, PRJ_VERSION, OSS_NOTICE_DUE_DATE
Project prj = new Project();
String prjId = map.get("PRJ_ID");
String prjName = map.get("PRJ_NAME");
String prjVersion = map.get("PRJ_VERSION");
//String prjDate = map.get("OSS_NOTICE_DUE_DATE");
// -- 프로젝트 기본정보 유효성 체크 start --------------------------------
// 1. 신규인경우 프로젝트명 유니크 체크 -> 수정인 경우에도 체크
targetName = "PRJ_NAME";
if (!errMap.containsKey(targetName)) {
prj.setPrjId(prjId);
prj.setPrjName(prjName);
prj.setPrjVersion(prjVersion);
boolean exist = projectService.existProjectData(prj);
if (exist) {
errMap.put(targetName, targetName + ".DUPLICATED");
}
}
// 2. oss type
targetName = "OS_TYPE";
targetNameSub = "OS_TYPE_ETC";
if (!errMap.containsKey(targetName) && !errMap.containsKey(targetNameSub)) {
if (CoConstDef.COMMON_SELECTED_ETC.equals(map.get(targetName)) && isEmpty(map.get(targetNameSub))) {
errMap.put(targetNameSub, targetNameSub + ".REQUIRED");
}
}
// 3. oss Notice
targetName = "NOTICE_TYPE";
targetNameSub = "NOTICE_TYPE_ETC";
if (!errMap.containsKey(targetName) && !errMap.containsKey(targetNameSub)) {
if (CoConstDef.CD_NOTICE_TYPE_PLATFORM_GENERATED.equals(map.get(targetName)) && isEmpty(map.get(targetNameSub))) {
errMap.put(targetNameSub, targetNameSub + ".REQUIRED");
}
}
// 4. MODEL INPOMATION CHECK
targetName = "MODEL_NAME";
targetNameSub = "CATEGORY";
if (map.containsKey(targetName + ".1")) {
// 중목체크
// 동일한 카테고리와 모델이 존재하는지 체크
List<String> modelKeyList = new ArrayList<>();
for (int i = 1; map.containsKey(targetName + "." + i); i++) {
String _seqkey = targetName + "." + i;
String _seqKeySub = targetNameSub + "." + i;
if (!errMap.containsKey(_seqkey) && !errMap.containsKey(_seqKeySub)) {
String _key = map.get(_seqkey) + "_" + map.get(_seqKeySub);
if (modelKeyList.contains(_key)) {
errMap.put(_seqkey, targetName + ".DUPLICATED"); // 중목
} else {
modelKeyList.add(_key);
}
}
}
}
// 5. priority
targetName = "PRIORITY";
if (!errMap.containsKey(targetName)) {
String priority = CoCodeManager.getCodeString(CoConstDef.CD_PROJECT_PRIORITY, map.get(targetName));
if (isEmpty(priority)) {
errMap.put(targetName, targetName + ".REQUIRED");
}
}
if (CommonFunction.isAdmin()) {
targetName = "CREATOR_NM";
if (map.containsKey(targetName) && !isEmpty(map.get("PRJ_ID")) && !"true".equals(map.get("COPY"))) {
if (isEmpty(map.get(targetName))) {
errMap.put(targetName, targetName + ".REQUIRED");
} else if (!map.get(targetName).equals(map.get("CREATOR"))) {
// 퇴사자인 경우는 에러 처리하지 않음
if (!isEmpty(map.get("CREATOR")) && userService.isLeavedMember(map.get("CREATOR"))) {
} else {
errMap.put(targetName, targetName + ".NOTFOUND");
}
}
}
}
}
@SuppressWarnings("unused")
private void validateProjectGrid(Map<String, String> map, Map<String, String> errMap, Map<String, String> diffMap, Map<String, String> infoMap) {
Map<String, OssMaster> ossInfo = null;
// dataMap을 사용하지 않고, request정보를 직접 참조
if (ossComponetList != null) {
String basicKey = "";
String gridKey = "";
String errKey = "";
List<ProjectIdentification> licenseList = null;
// 설정된 oss 정보를 DB에서 취득한다.
OssMaster ossParam = new OssMaster();
ossParam.setOssNames(getOssNames());
if (ossParam.getOssNames() != null && ossParam.getOssNames().length > 0) {
ossInfo = CoCodeManager.OSS_INFO_UPPER;
}
if (ossInfo == null) {
ossInfo = new HashMap<>();
}
// check deactivate oss info
List<String> deactivateOssList = ossService.getDeactivateOssList();
deactivateOssList.replaceAll(String::toUpperCase);
// checkBasicError : REQUIRED, LENGTH, FORMAT 만 체크!
for (ProjectIdentification bean : ossComponetList) {
boolean hasError = false;
boolean hasMultiError = false; // multi license용
String checkKey = bean.getOssName().trim() + "_" + avoidNull(bean.getOssVersion()).trim();
checkKey = checkKey.toUpperCase();
OssMaster ossmaster = ossInfo.get(checkKey);
// exclude=Y 상태인 경우 체크하지 않음
if (!ignoreExcludeDataFlag && CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
// exclude 상태에서도 체크 되어야하는 case
// bin android case only
if (existsResultBinaryNameList != null && !isEmpty(bean.getBinaryName())) {
if (existsResultBinaryNameList.contains(bean.getBinaryName())) {
errMap.put("BINARY_NAME." + bean.getGridId(), "BINARY_NAME.RESULTTXT_EXISTS");
}
}
continue;
}
// nullpoint
bean.setOssName(avoidNull(bean.getOssName()));
licenseList = findLicense(bean.getGridId());
// oss 를 설정하지 않고, class 파일을 추가하는 경우, oss Name 에 하이픈을 입력한다.
// class 파일을 설정한 경우, 라이선스 유무와 파일패스 설정 여부만 확인한다.
if ("-".equals(avoidNull(bean.getOssName()).trim())) {
// license check
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
if (bean.getLicenseName().split(",").length > 1) {
errMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.INCLUDE_MULTI_OPERATE");
} else {
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else if (isEmpty(bean.getLicenseName())) {
errMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.REQUIRED");
} else if (!CommonFunction.checkLicense(bean.getLicenseName())) {
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.UNCONFIRMED");
} else {
diffMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.UNCONFIRMED");
}
} else if (bean.getComponentLicenseList() != null) {
if (bean.getComponentLicenseList().size() > 1) {
errMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.INCLUDE_MULTI_OPERATE");
}
} else if (CommonFunction.checkLicense(bean.getLicenseName())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(bean.getLicenseName().trim().toUpperCase());
if (master != null && CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationDisclosingSrcYn()))) {
diffMap.put("OSS_NAME." + bean.getGridId(), "OSS_NAME.REQUIRED2");
}
}
}
}
// FILE PATH
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는
// 파라미터 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
// OSS가 DB에 존재하고, 선택된 라이선스(멀티인 경우 복수)의 oblication이 소스코드를
// 공개해야하는 경우, 필수 체크
else if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(bean.getRefDiv())
&& isEmpty(bean.getFilePath())) {
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".REQUIRED");
}
}
// Notice는 OSS와 상관없이,
if (PROC_TYPE_IDENTIFICATION_ANDROID.equals(PROC_TYPE)) {
basicKey = "BINARY_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errKey = basicKey + "." + bean.getGridId();
if (!errMap.containsKey(errKey)) {
// 길이, 형식 체크만 한다.
String errCd = checkBasicError(basicKey, gridKey, bean.getBinaryName(), true);
if (!isEmpty(errCd)) {
errMap.put(errKey, errCd);
} else if (isEmpty(bean.getBinaryName())) {
errMap.put(errKey, basicKey + ".REQUIRED");
}
}
basicKey = "BINARY_NOTICE";
gridKey = StringUtil.convertToCamelCase(basicKey);
errKey = basicKey + "." + bean.getGridId();
// nullpoint 대응
bean.setBinaryNotice(avoidNull(bean.getBinaryNotice()));
if (!diffMap.containsKey(errKey)) {
// 길이, 형식 체크만 한다.
String errCd = checkBasicError(basicKey, gridKey, bean.getBinaryNotice(), true);
if (!isEmpty(errCd)) {
diffMap.put(errKey, errCd);
} else if (("ok".equalsIgnoreCase(bean.getBinaryNotice())
|| "ok(NA)".equalsIgnoreCase(bean.getBinaryNotice()))
&& !checkUsedPermissive(bean, licenseList)) {
diffMap.put(errKey, basicKey + ".NOTICE_FIND");
} else if (("nok".equalsIgnoreCase(bean.getBinaryNotice())
|| "nok(NA)".equalsIgnoreCase(bean.getBinaryNotice()))
&& checkUsedPermissive(bean, licenseList)) {
diffMap.put(errKey, basicKey + ".NOTICE_PERMISSIVE");
}
}
}
continue;
}
// 1) oss name
{
basicKey = "OSS_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getOssName(),
CommonFunction.isIgnoreLicense(bean.getLicenseName()));
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS NAME에 대해서 추가적으로 해야할 것이 있다면
}
if ((isEmpty(bean.getOssName()) || "-".equals(bean.getOssName())) && bean.getComponentLicenseList() != null) {
if (bean.getComponentLicenseList().size() > 1) {
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errMap.put(basicKey + "." + bean.getGridId(), "LICENSE_NAME.INCLUDE_MULTI_OPERATE");
}
}
if (ossmaster != null) {
if (CoConstDef.FLAG_YES.equals(ossmaster.getDeactivateFlag())){
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getGridId(), "OSS_NAME.DEACTIVATED");
} else {
diffMap.put(basicKey + "." + bean.getGridId(), "OSS_NAME.DEACTIVATED");
}
}
} else {
boolean deactivateFlag = false;
if (!isEmpty(bean.getOssName())) {
if (deactivateOssList.contains(bean.getOssName().toUpperCase())) {
deactivateFlag = true;
}
if (deactivateFlag) {
if (CommonFunction.isAdmin()) {
errMap.put(basicKey + "." + bean.getGridId(), "OSS_NAME.DEACTIVATED");
} else {
diffMap.put(basicKey + "." + bean.getGridId(), "OSS_NAME.DEACTIVATED");
}
}
}
}
}
// 2) OSS VERSION
{
basicKey = "OSS_VERSION";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getOssVersion());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 3) DOWNLOAD LOCATION
{
basicKey = "DOWNLOAD_LOCATION";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getDownloadLocation());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 4) HOMEPAGE
{
basicKey = "HOMEPAGE";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getHomepage());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
} else {
// OSS VERSION에 대해서 추가적으로 해야할 것이 있다면
}
}
// 이후부터는 license와 관련됨
if (licenseList == null || licenseList.isEmpty() || licenseList.size() < 2) {
hasError = false; // 초기화
// subGrid가 없을 경우, 싱글라이선스로 간주
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 5-1. license name의 basic validator
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, bean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
hasError = true;
}
}
} else {
// Multi 또는 dual 라이선스의 경우
hasMultiError = false; // 초기화
List<ProjectIdentification> unExcludeLicenseList = new ArrayList<>();
for (ProjectIdentification licenseBean : licenseList) {
hasError = false; // 초기화
// exclude=Y 상태인 경우 체크하지 않음
if (!CoConstDef.FLAG_YES.equals(licenseBean.getExcludeYn())) {
unExcludeLicenseList.add(licenseBean);
{
basicKey = "LICENSE_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
// 5-1. license name의 basic validator
// 기본체크
String errCd = checkBasicError(basicKey, gridKey, licenseBean.getLicenseName());
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + licenseBean.getGridId(), errCd);
hasMultiError = hasError = true;
}
}
}
}
// exclude를 포함하여 체크해야할 validator
if (!hasMultiError) {
basicKey = "LICENSE_NAME";
// 모두 exlucde가 체크되어 선택된 라이선스가 없을 경우
if (unExcludeLicenseList.isEmpty()) {
// header row의 라이선스에 에러 표시
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".NOLICENSE");
} else if (checkOROperation(licenseList, ossmaster)) {
// OR 조건이 두개이상 선택된 경우
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".INCLUDE_DUAL_OPERATE");
}
}
}
// 6) path 정보
{
basicKey = "FILE_PATH";
gridKey = StringUtil.convertToCamelCase(basicKey);
// FILE_PATH의 경우 basic validator에서 형식, 길이 체크만 한다.
// basic validator의 체크 순서가 필수부터 체크하기 때문에, 필수체크를 무시하는 파라미터
// 플래그를 추가
String errCd = checkBasicError(basicKey, gridKey, bean.getFilePath(), true);
if (!isEmpty(errCd)) {
errMap.put(basicKey + "." + bean.getGridId(), errCd);
}
// OSS가 DB에 존재하고, 선택된 라이선스(멀티인 경우 복수)의 oblication이 소스코드를
// 공개해야하는 경우, 필수 체크
else if (PROC_TYPE_IDENTIFICATION_ANDROID.equals(PROC_TYPE) && isEmpty(bean.getFilePath())) {
// 17.02.21 yuns bin(android)의 경우 무조건 필수체크로 변경
errMap.put(basicKey + "." + bean.getGridId(), basicKey + ".REQUIRED");
}
// 170524 add yun SRC의 path 정보에 복수개의 path를 선언하는 경우, 에러는 아니지만
// 다른 색상으로 표시
else if (diffMap != null && PROC_TYPE_IDENTIFICATION_SOURCE.equals(PROC_TYPE)
&& (avoidNull(bean.getFilePath()).indexOf("\r\n") > -1
|| avoidNull(bean.getFilePath()).indexOf("\n") > -1)) {
diffMap.put(basicKey + "." + bean.getGridId(), basicKey + ".FORMAT");
}
}
// binary name (Android Model만)
// TODO Android Model과 일반 Model이 같이 있는 경우, 어떻게 구분할 것인가? 일단
// binary name과 notice 칼럼으로 판단
if (PROC_TYPE_IDENTIFICATION_ANDROID.equals(PROC_TYPE)) {
basicKey = "BINARY_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errKey = basicKey + "." + bean.getGridId();
if (!errMap.containsKey(errKey)) {
// 길이, 형식 체크만 한다.
String errCd = checkBasicError(basicKey, gridKey, bean.getBinaryName(), true);
if (!isEmpty(errCd)) {
errMap.put(errKey, errCd);
} else if (isEmpty(bean.getBinaryName())) {
errMap.put(errKey, basicKey + ".REQUIRED");
}
}
basicKey = "BINARY_NOTICE";
gridKey = StringUtil.convertToCamelCase(basicKey);
errKey = basicKey + "." + bean.getGridId();
// nullpoint 대응
bean.setBinaryNotice(avoidNull(bean.getBinaryNotice()));
if (!diffMap.containsKey(errKey)) {
// 길이, 형식 체크만 한다.
String errCd = checkBasicError(basicKey, gridKey, bean.getBinaryNotice(), true);
if (!isEmpty(errCd)) {
diffMap.put(errKey, errCd);
}
else if (("ok".equalsIgnoreCase(bean.getBinaryNotice())
|| "ok(NA)".equalsIgnoreCase(bean.getBinaryNotice()))
&& !checkUsedPermissive(bean, licenseList)) {
diffMap.put(errKey, basicKey + ".NOTICE_FIND");
} else if (("nok".equalsIgnoreCase(bean.getBinaryNotice())
|| "nok(NA)".equalsIgnoreCase(bean.getBinaryNotice()))
&& checkUsedPermissive(bean, licenseList)) {
diffMap.put(errKey, basicKey + ".NOTICE_PERMISSIVE");
}
}
}
// Admin용 validation
// admin review시 confirm을 위한 추가 validation
if (!isEmpty(bean.getLicenseName())) {
if (bean.getOssComponentsLicenseList() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (!CoCodeManager.LICENSE_INFO_UPPER
.containsKey(avoidNull(license.getLicenseName()).toUpperCase())
&& !ossInfo.containsKey(checkKey)) {
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "LICENSE_NAME.UNCONFIRMED");
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "LICENSE_NAME.UNCONFIRMED");
}
}
break;
}
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getGridId())) {
for (ProjectIdentification license : ossComponentLicenseListMap.get(bean.getGridId())) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (!CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(license.getLicenseName()).toUpperCase())
&& !ossInfo.containsKey(checkKey)) {
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "LICENSE_NAME.UNCONFIRMED");
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "LICENSE_NAME.UNCONFIRMED");
}
}
break;
}
}
}
}
// LGE license인 경우는 OSS name과 version을 입력하지 않아도 된다.
if (!CommonFunction.isIgnoreLicense(bean.getLicenseName())) {
// oss 등록 여부 체크
if (!errMap.containsKey("OSS_NAME." + bean.getGridId())
&& !errMap.containsKey("OSS_VERSION." + bean.getGridId())
&& !ossInfo.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfo, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getGridId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getGridId(), "OSS_VERSION.UNCONFIRMED");
}
} else {
if (CommonFunction.isAdmin()) {
errMap.put("OSS_NAME." + bean.getGridId(), "OSS_NAME.UNCONFIRMED");
} else {
diffMap.put("OSS_NAME." + bean.getGridId(), "OSS_NAME.UNCONFIRMED");
}
}
}
// license 등록 여부 (등록되어 있는 오픈소스이나 사용자가 입력한 라이선스는 포함하고 있지 않은
// 경우)
else if (!errMap.containsKey("OSS_NAME." + bean.getGridId())
&& !errMap.containsKey("LICENSE_NAME." + bean.getGridId())) {
String licenseText = "";
if (ossmaster != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(ossmaster.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()) {
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(ossmaster, bean.getOssComponentsLicenseList())) {
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "Declared : " + licenseText);
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(ossmaster, bean.getOssComponentsLicenseList(), false)) {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(ossmaster, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getGridId())) {
List<ProjectIdentification> useLicenseList = ossComponentLicenseListMap.get(bean.getGridId());
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(ossmaster, useLicenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "Declared : " + licenseText);
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(ossmaster, useLicenseList, false)) {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(ossmaster, useLicenseList)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap == null) {
if (PROC_TYPE_IDENTIFICATION_PARTNER.equals(PROC_TYPE)) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(ossmaster, bean.getLicenseName(), bean.getExcludeYn())) {
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "Declared : " + licenseText);
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(ossmaster, bean.getLicenseName(), bean.getExcludeYn(), false)) {
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeSingle(ossmaster, bean.getLicenseName())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
}
}
}
} else {
if (!errMap.containsKey("OSS_NAME." + bean.getGridId())
&& !errMap.containsKey("OSS_VERSION." + bean.getGridId())
&& !ossInfo.containsKey(checkKey)) {
if (checkNonVersionOss(ossInfo, bean.getOssName())) {
// oss는 등록되어 있지만, 해당 version은 없는 경우
if (CommonFunction.isAdmin()) {
errMap.put("OSS_VERSION." + bean.getGridId(), "OSS_VERSION.UNCONFIRMED");
} else {
diffMap.put("OSS_VERSION." + bean.getGridId(), "OSS_VERSION.UNCONFIRMED");
}
}
}
else if (!errMap.containsKey("OSS_NAME." + bean.getGridId())
&& !errMap.containsKey("OSS_VERSION." + bean.getGridId())
&& ossInfo.containsKey(checkKey)
) {
String licenseText = "";
if (ossmaster != null) {
licenseText = CommonFunction.makeLicenseExpressionMsgType(ossmaster.getOssLicenses(), true); // msgType return
}
if (bean.getOssComponentsLicenseList() != null
&& !bean.getOssComponentsLicenseList().isEmpty()) {
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense(ossmaster, bean.getOssComponentsLicenseList())) {
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "Declared : " + licenseText);
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense(ossmaster, bean.getOssComponentsLicenseList(), false)) {
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeComponents(ossmaster, bean.getOssComponentsLicenseList())) {
diffMap.put("LICENSE_NAME." + bean.getComponentId(), "Declared : " + licenseText);
}
} else if (ossComponentLicenseListMap != null
&& ossComponentLicenseListMap.containsKey(bean.getGridId())) {
List<ProjectIdentification> useLicenseList = ossComponentLicenseListMap.get(bean.getGridId());
String LICENSE_KEY = "LICENSE_NAME." + bean.getGridId();
// Declared & Detected License를 전부 사용하지 않는 case
if (!hasOssLicense2(ossmaster, useLicenseList)) {
if (CommonFunction.isAdmin()) {
errMap.put(LICENSE_KEY, "Declared : " + licenseText);
} else {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
// Declared License를 사용하지 않는 case
else if (!hasOssLicense2(ossmaster, useLicenseList, false)) {
if (!errMap.containsKey(LICENSE_KEY)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
//Declared License 중 Permissive가 아닌 type(Copyleft, weak copyleft, Proprietary, Proprietary Free)의 License가 누락된 경우
else if (hasOssLicenseTypeProject(ossmaster, useLicenseList)) {
diffMap.put(LICENSE_KEY, "Declared : " + licenseText);
}
}
}
}
if (ossInfo.containsKey(checkKey)) {
// oss Download_location 체크
if (!diffMap.containsKey("DOWNLOAD_LOCATION." + bean.getGridId())
&& !isEmpty(bean.getDownloadLocation())) {
if (checkOssData(ossInfo.get(checkKey), bean.getDownloadLocation(), "DOWNLOAD")) {
diffMap.put("DOWNLOAD_LOCATION." + bean.getGridId(), "DOWNLOAD_LOCATION.DIFFERENT");
}
}
// oss Homepage 체크
if (!diffMap.containsKey("HOMEPAGE." + bean.getGridId()) && !isEmpty(bean.getHomepage())) {
if (checkOssData(ossInfo.get(checkKey), bean.getHomepage(), "HOMEPAGE")) {
diffMap.put("HOMEPAGE." + bean.getGridId(), "HOMEPAGE.DIFFERENT");
}
}
if(!diffMap.containsKey("LICENSE_NAME." + bean.getGridId()) && !errMap.containsKey("LICENSE_NAME." + bean.getGridId()) && !isEmpty(bean.getLicenseName())) {
String licenseText = CommonFunction.makeRecommendedLicenseString(ossmaster, bean);
if(!isEmpty(licenseText)) {
diffMap.put("LICENSE_NAME." + bean.getGridId(), "Recommended : " + licenseText );
}
}
if (!diffMap.containsKey("COPYRIGHT_TEXT." + bean.getGridId()) && !isEmpty(bean.getCopyrightText())) {
if (!checkOssData(ossInfo.get(checkKey), bean.getCopyrightText(), "COPYRIGHT")) {
infoMap.put("COPYRIGHT_TEXT." + bean.getGridId(), "COPYRIGHT.DIFFERENT");
}
}
}
// exception 처리
// LICENSE_NAME.UNCONFIRMED 의 경우, notice warning message 미표시
if (PROC_TYPE_IDENTIFICATION_ANDROID.equals(PROC_TYPE)) {
String chkKey1 = "LICENSE_NAME." + bean.getGridId();
String chkKey2 = "BINARY_NOTICE." + bean.getGridId();
if (errMap.containsKey(chkKey1) && (errMap.containsKey(chkKey2) || diffMap.containsKey(chkKey2))) {
String _diffCode1 = errMap.get(chkKey1);
if ("LICENSE_NAME.UNCONFIRMED".equals(_diffCode1)) {
if (errMap.containsKey(chkKey2)) {
errMap.remove(chkKey2);
}
if (diffMap.containsKey(chkKey2)) {
diffMap.remove(chkKey2);
}
}
}
if (diffMap.containsKey(chkKey1) && (errMap.containsKey(chkKey2) || diffMap.containsKey(chkKey2))) {
String _diffCode1 = diffMap.get(chkKey1);
if ("LICENSE_NAME.UNCONFIRMED".equals(_diffCode1)) {
if (errMap.containsKey(chkKey2)) {
errMap.remove(chkKey2);
}
if (diffMap.containsKey(chkKey2)) {
diffMap.remove(chkKey2);
}
}
}
}
{ // ADD OSS_VERSION REQUIRED MSG
if (!isEmpty(bean.getOssName())
&& !bean.getOssName().equals("-")
&& isEmpty(bean.getOssVersion())) {
if (!errMap.containsKey("OSS_VERSION." + bean.getGridId())) {
if (ossService.checkOssVersionDiff(bean.getOssName()) > 0) {
diffMap.put("OSS_VERSION." + bean.getGridId(), "OSS_VERSION.REQUIRED");
}
}
}
}
} // end of loop
Map<String, List<BinaryData>> checkBinaryInfoMap = new HashMap<>();
boolean isAndroid = false;
if ((PROC_TYPE_IDENTIFICATION_ANDROID.equals(PROC_TYPE) || PROC_TYPE_IDENTIFICATION_BIN.equals(PROC_TYPE) || PROC_TYPE_IDENTIFICATION_PARTNER.equals(PROC_TYPE)) && !isEmpty(projectId)) {
Project projectInfo = projectService.getProjectBasicInfo(projectId);
checkBinaryInfoMap = binaryDataService.getBinaryListFromBinaryDB(isAndroid, projectInfo);
}
if(checkBinaryInfoMap != null) {
String errMessageFormatSame = "Same {0}";
String errMessageFormatSimilar = "Similar {0}";
String errMessageFormatModified = "Modified ";
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
continue;
}
basicKey = "BINARY_NAME";
gridKey = StringUtil.convertToCamelCase(basicKey);
errKey = basicKey + "." + bean.getGridId();
if (!diffMap.containsKey(errKey)) {
String binaryName = avoidNull(bean.getBinaryName());
if (isEmpty(binaryName)) {
continue;
}
List<BinaryData> _batList = checkBinaryInfoMap.get(binaryName);
if (_batList != null && !_batList.isEmpty()) {
String msgParam = "";
String msgParamSame = ""; // 동일한 binary가 존재하는 경우
String msgParamLicense = "";
// oss name version이 동일한게 있으면 pass
boolean hasBatOssSameTlsh = false;
// 먼저 사용자 입력 정보와 동일한 binary 정보가 db에 존재하는 경우 message를
// 표시하지 않는다
boolean doCheck = true;
boolean tlshDistanceOver = true;
for (BinaryData _temp : _batList) {
// 동일한 binary가 없는 경우 유사한 binary 체크
if (avoidNull(bean.getOssName(), "-").equalsIgnoreCase(_temp.getOssName())
&& avoidNull(bean.getOssVersion()).equalsIgnoreCase(_temp.getOssVersion())
&& compareLicenseWithLicenseNameSort(bean, _temp)) {
doCheck = false;
}
if(_temp.getTlshDistance() > 120){
tlshDistanceOver = false;
}
}
if (doCheck && tlshDistanceOver) {
BinaryData _temp = null;
for (BinaryData _temp2 : _batList) {
if (_temp2.getTlshDistance() == 0) {
hasBatOssSameTlsh = true;
_temp = _temp2;
break;
}
}
if(_temp == null) {
_temp = _batList.get(0);
}
boolean isSameLicense = compareLicenseWithLicenseNameSort(bean, _temp);
boolean isSameOssName = avoidNull(bean.getOssName(), "-").equalsIgnoreCase(_temp.getOssName());
boolean isSameOssVersion = avoidNull(bean.getOssVersion()).equalsIgnoreCase(_temp.getOssVersion());
//2) OSS NAME + VERSION 등일하나 LICENSE 만 다른 경우
if(isSameOssName
&& isSameOssVersion
&& !isSameLicense) {
// Same binary : / <License>
diffMap.put(errKey, MessageFormat.format(hasBatOssSameTlsh ? errMessageFormatSame : errMessageFormatSimilar, (hasBatOssSameTlsh ? ":" : " ("+_temp.getTlshDistance()+") :") + " /"+_temp.getLicense())); // message를
}
// 3) OSS NAME LICENSE는 동일하나 VERSION 이 다른경우
else if(isSameOssName && isSameLicense && !isSameOssVersion) {
// Same binary : <OSS Name> <OSS Version>
infoMap.put(errKey, MessageFormat.format(hasBatOssSameTlsh ? errMessageFormatSame : errMessageFormatSimilar, (hasBatOssSameTlsh ? ":" : " ("+_temp.getTlshDistance()+") :") + makeBinaryOssName(_temp.getOssName(), _temp.getOssVersion())+" /"));
}
// 4) OSS NAME 은 동일하나 VERSION 과 LICENSE 가 다른 경우
else if(isSameOssName && !isSameOssVersion && !isSameLicense) {
// Same binary : <OSS Name> <OSS Version> / <License>
diffMap.put(errKey, MessageFormat.format(hasBatOssSameTlsh ? errMessageFormatSame : errMessageFormatSimilar, (hasBatOssSameTlsh ? ":" : " ("+_temp.getTlshDistance()+") :") + makeBinaryOssName(_temp.getOssName(), _temp.getOssVersion()) + " / "+_temp.getLicense()));
}
// 6) OSS NAME은 다르나, LICENSE 는 동일
else if(!isSameOssName && isSameLicense) {
// Same binary : <OSS Name> <OSS Version> /
diffMap.put(errKey, MessageFormat.format(hasBatOssSameTlsh ? errMessageFormatSame : errMessageFormatSimilar, (hasBatOssSameTlsh ? ":" : " ("+_temp.getTlshDistance()+") :") + makeBinaryOssName(_temp.getOssName(), _temp.getOssVersion()) + " /"));
}
// 7) OSS NAME LICENSE 모두 다른 경우
else {
// Same binary : <OSS Name> <OSS Version> / <License>
diffMap.put(errKey, MessageFormat.format(hasBatOssSameTlsh ? errMessageFormatSame : errMessageFormatSimilar, (hasBatOssSameTlsh ? ":" : " ("+_temp.getTlshDistance()+") :") + makeBinaryOssName(_temp.getOssName(), _temp.getOssVersion()) + " / "+_temp.getLicense()));
}
} else {
// oss name + version + license 까지 동일하면 match info Matched message 표시
infoMap.put(errKey, basicKey + ".MATCHED");
}
}
// 기 등록된 binary 정보가 없으면
else if (checkBinaryInfoMap.containsKey(binaryName)) {
infoMap.put(errKey, basicKey + ".NEW_BINARY_OSS");
}
}
}
}
}
}
private boolean compareLicenseWithLicenseNameSort(ProjectIdentification bean, BinaryData _temp) {
String selectedLicenses = "";
if (bean.getOssComponentsLicenseList() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn()) || isEmpty(license.getLicenseName())) {
continue;
}
if (!isEmpty(selectedLicenses)) {
selectedLicenses += ",";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().trim().toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(license.getLicenseName().trim().toUpperCase());
selectedLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
selectedLicenses += license.getLicenseName();
}
}
} else if (ossComponentLicenseListMap != null && ossComponentLicenseListMap.containsKey(bean.getGridId())) {
for (ProjectIdentification license : ossComponentLicenseListMap.get(bean.getGridId())) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (!isEmpty(selectedLicenses)) {
selectedLicenses += ",";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().trim().toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(license.getLicenseName().trim().toUpperCase());
selectedLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
selectedLicenses += license.getLicenseName();
}
}
}
String regLicenses = "";
for (String s : avoidNull(_temp.getLicense()).split(",")) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(regLicenses)) {
regLicenses += ",";
}
s = s.trim();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(s.toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER.get(s.toUpperCase());
regLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
regLicenses += s;
}
}
// 콤마구분 형태의 동일한 문자 객체를 sorting 하여 비교 한다.
List<String> compare1 = Arrays.asList(selectedLicenses.trim().toUpperCase().split(","));
List<String> compare2 = Arrays.asList(avoidNull(regLicenses).toUpperCase().split(","));
Collections.sort(compare1);
Collections.sort(compare2);
String diff1 = "";
String diff2 = "";
for (String s : compare1) {
if (!isEmpty(diff1)) {
diff1 += ",";
}
diff1 += s;
}
for (String s : compare2) {
if (!isEmpty(diff2)) {
diff2 += ",";
}
diff2 += s;
}
return diff1.equalsIgnoreCase(diff2);
}
private String makeBinaryOssName(String ossName, String ossVersion) {
String rtn = avoidNull(ossName, "-");
if (!isEmpty(ossVersion)) {
rtn += " " + ossVersion;
}
return rtn;
}
private boolean compareLicenseWithLicenseNameSort(ProjectIdentification bean, Map<String, Object> _temp) {
String selectedLicenses = "";
if (bean.getOssComponentsLicenseList() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicenseList()) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn()) || isEmpty(license.getLicenseName())) {
continue;
}
if (!isEmpty(selectedLicenses)) {
selectedLicenses += ",";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().trim().toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(license.getLicenseName().trim().toUpperCase());
selectedLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
selectedLicenses += license.getLicenseName();
}
}
} else if (ossComponentLicenseListMap != null && ossComponentLicenseListMap.containsKey(bean.getGridId())) {
for (ProjectIdentification license : ossComponentLicenseListMap.get(bean.getGridId())) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (!isEmpty(selectedLicenses)) {
selectedLicenses += ",";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(license.getLicenseName().trim().toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER
.get(license.getLicenseName().trim().toUpperCase());
selectedLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
selectedLicenses += license.getLicenseName();
}
}
}
String regLicenses = "";
String license = _temp.containsKey("license") ? (String) _temp.get("license") : "";
for (String s : avoidNull(license).split(",")) {
if (isEmpty(s)) {
continue;
}
if (!isEmpty(regLicenses)) {
regLicenses += ",";
}
s = s.trim();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(s.toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER.get(s.toUpperCase());
regLicenses += avoidNull(master.getShortIdentifier(), master.getLicenseNameTemp());
} else {
regLicenses += s;
}
}
// 콤마구분 형태의 동일한 문자 객체를 sorting 하여 비교 한다.
List<String> compare1 = Arrays.asList(selectedLicenses.trim().toUpperCase().split(","));
List<String> compare2 = Arrays.asList(avoidNull(regLicenses).toUpperCase().split(","));
Collections.sort(compare1);
Collections.sort(compare2);
String diff1 = "";
String diff2 = "";
for (String s : compare1) {
if (!isEmpty(diff1)) {
diff1 += ",";
}
diff1 += s;
}
for (String s : compare2) {
if (!isEmpty(diff2)) {
diff2 += ",";
}
diff2 += s;
}
return diff1.equalsIgnoreCase(diff2);
}
private boolean checkUsedPermissive(ProjectIdentification bean, List<ProjectIdentification> licenseList) {
if (!isEmpty(bean.getOssName()) && licenseList != null) {
for (ProjectIdentification license : licenseList) {
if (CoConstDef.FLAG_YES.equals(license.getExcludeYn())) {
continue;
}
if (!isEmpty(license.getLicenseName())
&& CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(license.getLicenseName()).toUpperCase())) {
LicenseMaster master = CoCodeManager.LICENSE_INFO_UPPER.get(license.getLicenseName().toUpperCase());
if (master != null && (CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationDisclosingSrcYn()))
|| CoConstDef.FLAG_YES.equals(avoidNull(master.getObligationNotificationYn())))) {
return true;
}
}
}
}
return false;
}
private boolean checkOROperation(List<ProjectIdentification> licenseList, OssMaster ossInfo) {
if (ossInfo != null) {
String licenseGroup = CommonFunction.makeLicenseExpression(ossInfo.getOssLicenses());
// String[] licenseGroupSplit = licenseGroup.split("OR");
List<String> andCombLicenseList = new ArrayList<>();
for (OssLicense bean : ossInfo.getOssLicenses()) {
if (andCombLicenseList.isEmpty() || "OR".equals(bean.getOssLicenseComb())) {
andCombLicenseList.add(bean.getLicenseName());
continue;
}
int seq = andCombLicenseList.size()-1;
String licenseName = andCombLicenseList.get(seq);
licenseName += " AND " + bean.getLicenseName();
andCombLicenseList.set(seq, licenseName);
}
Map<String, Object> result = new HashMap<String, Object>();
boolean returnFlag = false;
for (ProjectIdentification iden : licenseList) {
if (!licenseGroup.contains(iden.getLicenseName())) {
returnFlag = true;
break;
}
}
if (returnFlag || licenseList.size() == 1) { // OSS에 등록된 license를 사용하지 않았거나, license가 1개만 들록된 경우 dual check를 하지 않음.
return false;
}
for (String licenseName : andCombLicenseList) {
for (ProjectIdentification iden : licenseList) {
if (!licenseName.trim().contains(iden.getLicenseName().trim()) && CoConstDef.FLAG_NO.equals(iden.getExcludeYn())) {
result.put(licenseName, false);
break;
}
}
}
return andCombLicenseList.size() == result.size() ? true : false; // group의 size와 존재하지 않은 값 check size가 동일하면 true
}
return false;
}
private boolean hasOssLicenseTypeComponents(OssMaster ossInfo, List<OssComponentsLicense> licenseList) {
List<String> licenseNameList = licenseList.stream()
.map(ocl -> CoCodeManager.LICENSE_INFO.containsKey(ocl.getLicenseName())
? avoidNull(CoCodeManager.LICENSE_INFO.get(ocl.getLicenseName()).getShortIdentifier()
, CoCodeManager.LICENSE_INFO.get(ocl.getLicenseName()).getLicenseName())
: ocl.getLicenseName())
.collect(Collectors.toCollection(ArrayList::new));
return hasOssLicenseType(ossInfo, licenseNameList);
}
private boolean hasOssLicenseTypeProject(OssMaster ossInfo, List<ProjectIdentification> licenseList) {
List<String> licenseNameList = licenseList.stream()
.map(pi -> CoCodeManager.LICENSE_INFO.containsKey(pi.getLicenseName())
? avoidNull(CoCodeManager.LICENSE_INFO.get(pi.getLicenseName()).getShortIdentifier()
, CoCodeManager.LICENSE_INFO.get(pi.getLicenseName()).getLicenseName())
: pi.getLicenseName())
.collect(Collectors.toCollection(ArrayList::new));
return hasOssLicenseType(ossInfo, licenseNameList);
}
private boolean hasOssLicenseTypeSingle(OssMaster ossInfo, String licenseName) {List<String> licenseNameList = new ArrayList<String>();
String[] licenseNameSplit = licenseName.split(",");
for (int i=0; i < licenseNameSplit.length; i++) {
licenseName = avoidNull(CoCodeManager.LICENSE_INFO.get(licenseNameSplit[i]).getShortIdentifier(), licenseNameSplit[i]);
licenseNameList.add(licenseName);
}
return hasOssLicenseType(ossInfo, licenseNameList);
}
private boolean hasOssLicenseType(OssMaster ossInfo, List<String> licenseNameList) {
if (ossInfo != null) {
// License가 permissive로만 구성되어 있는지 check 함.
List<OssLicense> permissiveCheck = ossInfo.getOssLicenses()
.stream()
.filter(ol -> !CoConstDef.CD_LICENSE_TYPE_PMS.equals(ol.getLicenseType()))
.collect(Collectors.toList());
// 전체가 permissive로 이루어져 있으므로 message를 출력하지 않음.
if (permissiveCheck.size() == 0) {
return false;
}
List<OssLicense> ossLicenses = ossInfo.getOssLicenses().stream().filter(ol -> "OR".equals(ol.getOssLicenseComb())).collect(Collectors.toList());
// Single License이거나 AND로만 구성된 Multi License -> Group을 나눌 필요가 없음.
if (ossLicenses.size() == 0) {
// permissive가 아닌 licenseType이면서 사용자가 입력한 License Name중에 없는 License가 존재할 경우 message를 출력함.
ossLicenses = ossInfo.getOssLicenses()
.stream()
.filter(ol -> !CoConstDef.CD_LICENSE_TYPE_PMS.equals(ol.getLicenseType())
&& !licenseNameList.contains(ol.getLicenseName()))
.collect(Collectors.toList());
if (ossLicenses.size() > 0) {
return true;
}
}
// Multi License(AND, OR 전부 포함한 case) -> Group을 나누어 각각 check를 함.
else {
List<List<OssLicense>> groupList = new ArrayList<>();
List<OssLicense> olList = new ArrayList<>();
// OR Group별로 분리
for (OssLicense bean : ossInfo.getOssLicenses()) {
if (olList.isEmpty() || "OR".equals(bean.getOssLicenseComb())) {
olList = new ArrayList<>();
olList.add(bean);
groupList.add(olList);
continue;
}
int seq = groupList.size()-1;
olList = groupList.get(seq);
olList.add(bean);
groupList.set(seq, olList);
}
boolean errorFlag = true;
for (List<OssLicense> list : groupList) {
List<OssLicense> checkList = list.stream().filter(c -> licenseNameList.contains(c.getLicenseName())).collect(Collectors.toList());
// 현재 그룹 내에 사용된 license name이 존재하는지 check함.
if (checkList.size() == 0) {
continue; // 그룹내에 사용한 license name이 없을 경우 continue
}
list = list.stream()
.filter(ol -> !CoConstDef.CD_LICENSE_TYPE_PMS.equals(ol.getLicenseType())
&& !licenseNameList.contains(ol.getLicenseName()))
.collect(Collectors.toList());
if (list.size() == 0) {
errorFlag = false;
break;
}
}
if (errorFlag) {
return true;
}
}
}
return false;
}
private String[] getOssNames() {
List<String> names = new ArrayList<>();
for (ProjectIdentification bean : ossComponetList) {
if (CoConstDef.FLAG_YES.equals(bean.getExcludeYn()) || isEmpty(bean.getOssName())
|| names.contains(bean.getOssName().trim())) {
continue;
}
names.add(bean.getOssName().trim());
}
return names.toArray(new String[names.size()]);
}
private List<ProjectIdentification> findLicense(String gridId) {
List<ProjectIdentification> licenseList = new ArrayList<>();
if (ossComponentLicenseList != null && !ossComponentLicenseList.isEmpty()) {
boolean breakFlag = false;
for (List<ProjectIdentification> list : ossComponentLicenseList) {
for (ProjectIdentification bean : list) {
String key = gridId + "-";
if (avoidNull(bean.getGridId()).startsWith(key)) {
licenseList.add(bean);
breakFlag = true;
}
}
if (breakFlag) {
break;
}
}
} else if (ossComponentLicenseListMap != null && ossComponentLicenseListMap.containsKey(gridId)) {
licenseList = ossComponentLicenseListMap.get(gridId);
}
return licenseList;
}
@SuppressWarnings("unchecked")
@Override
public void setAppendix(String key, Object obj) {
if (!isEmpty(key)) {
switch (key) {
case "mainList":
case "bomList":
ossComponetList = CommonFunction.replaceOssVersionNA((List<ProjectIdentification>) obj);
break;
case "subList":
ossComponentLicenseList = (List<List<ProjectIdentification>>) obj;
break;
case "subListMap":
ossComponentLicenseListMap = (Map<String, List<ProjectIdentification>>) obj;
break;
case "noticeBinaryList":
noticeBinaryList = (List<String>) obj;
break;
case "existsResultBinaryName":
existsResultBinaryNameList = (List<String>) obj;
break;
case "projectId":
projectId = (String) obj;
break;
default:
break;
}
}
}
@Override
protected String treatment(String paramvalue) {
return paramvalue;
}
public void setProcType(String type) {
PROC_TYPE = type;
}
public void setValidLevel(int level) {
LEVEL = level;
}
public void setIgnoreExcludeData(boolean ignore) {
ignoreExcludeDataFlag = ignore;
}
public boolean isCheckForAdmin() {
return checkForAdmin;
}
public void setCheckForAdmin(boolean checkForAdmin) {
this.checkForAdmin = checkForAdmin;
}
}
| 116,758 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ProjectService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/ProjectService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.*;
public interface ProjectService extends HistoryConfig{
public Map<String, Object> getProjectList(Project project);
void updateReviewer(Project project);
void updateReject(Project project);
public String getCategoryCode(String code, String gubun);
public Project getProjectDetail(Project project);
public Map<String, List<Project>> getModelList(String prjId);
public void registProject(Project project);
public void deleteProject(Project project);
public List<ProjectIdentification> getOssNames(ProjectIdentification identification);
public List<ProjectIdentification> getOssVersions(String ossName);
public Map<String, Object> getOssIdLicenses(ProjectIdentification identification);
public String getDivision(Project project);
public void registComponentsThird(String prjId, String identificationSubStatusPartner, List<OssComponents> ossComponents, List<PartnerMaster> thirdPartyList);
public List<Project> getProjectNameList(Project project);
public List<Project> getProjectModelNameList();
public Map<String, String> getCategoryCodeToJson(String code); //카테고리 코드 Json형태를 위한 List로 가공
public boolean existProjectData(Project project);
public void registSrcOss(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense, Project project);
public void registSrcOss(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense, Project project, String refDiv);
public void registOss(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense, String refId, String refDiv);
public Map<String, List<String>> nickNameValid(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense);
public void registBom(String prjId, String merge, List<ProjectIdentification> projectIdentification, List<ProjectIdentification> checkGridBomList);
public void checkProjectReviewer(Project project);
public Map<String, Object> updateProjectStatus(Project project) throws Exception;
public List<ProjectIdentification> getBomListExcel(ProjectIdentification bom);
List<Project> getModelListExcel(Project project);
void registReadmeContent(Project project);
void registVerifyContents(Project project);
Map<String, Object> getPartnerList(PartnerMaster partnerMaster);
Map<String, Object> getIdentificationProject(Project project);
void registComponentsBat(String prjId, String identificationSubStatusBat, List<ProjectIdentification> ossComponents,
List<List<ProjectIdentification>> ossComponentsLicense, boolean prjYn);
Map<String, Object> getIdentificationGridList(ProjectIdentification identification);
Map<String, Object> getIdentificationGridList(ProjectIdentification identification, boolean multiUIFlag);
Map<String, Object> getPartnerOssList(OssComponents ossComponents);
Map<String, Object> getIdentificationProjectSearch(ProjectIdentification projectIdentification);
String getReviewerList(String adminYn);
String getAdminUserList();
Map<String, Object> getIdentificationThird(OssComponents ossComponents);
List<Project> getProjectVersionList(Project project);
void updateSubStatus(Project project);
List<UploadFile> selectAndroidFileDetail(Project project);
void updateProjectIdentificationConfirm(Project project);
public Map<String, Object> getOssIdCheck(ProjectIdentification projectIdentification);
String checkChangedIdentification(String prjId, List<ProjectIdentification> partyData,
List<ProjectIdentification> srcData, List<List<ProjectIdentification>> srcSubData,
List<ProjectIdentification> batData, List<List<ProjectIdentification>> batSubData, String applicableParty, String applicableSrc, String applicableBat);
Map<String, Object> applySrcAndroidModel(List<ProjectIdentification> list, List<String> noticeBinaryList) throws IOException;
Map<String, Map<String, String>> getProjectDownloadExpandInfo(Project param);
Project getProjectBasicInfo(String prjId);
void cancelFileDel(Project project);
List<OssComponents> selectOssComponentsListByComponentIds(OssComponents param);
void updateProjectMaster(Project project);
Map<String, Object> getFileInfo(ProjectIdentification identification);
Map<String, Object> get3rdMapList(Project project);
List<Project> getWatcherList(Project project);
List<ProjectIdentification> convertOssNickName(List<ProjectIdentification> ossComponents);
List<List<ProjectIdentification>> convertLicenseNickName(List<List<ProjectIdentification>> ossComponentsLicense);
String addWatcher(Project project);
void removeWatcher(Project project);
List<Project> copyWatcher(Project project);
boolean existsWatcher(Project project);
String getPartnerFormatName(String partnerId, boolean onlyName);
void updateIdentificationConfirmSkipPackaing(Project project);
public void insertProjectModel(Project project);
public void updatePublicYn(Project project);
Map<String, Object> getProjectToAddList(OssComponents ossComponents);
Map<String, Object> getAddList(Project project);
boolean existsAddList(Project project);
void insertAddList(List<Project> project);
public OssNotice setCheckNotice(Project project);
Map<String, Object> identificationSubGrid(ProjectIdentification identification);
List<ProjectIdentification> setMergeGridData(List<ProjectIdentification> gridData);
List<ProjectIdentification> setMergeGridDataByAndroid(List<ProjectIdentification> gridData);
String checkValidData(Map<String, Object> map);
String makeNoticeFileContents(Map<String, Object> paramMap);
String makeSupplementFileId(String contents, Project project);
String makeZipFileId(Map<String, Object>paramMap, Project project);
public List<Map<String, String>> getBomCompare(List<ProjectIdentification> beforeBomList, List<ProjectIdentification> afterBomList, String flag) throws Exception;
public void deleteStatisticsMostUsedInfo(Project project);
public void addPartnerData(Project project);
public void insertCopyConfirmStatusBomList(Project project, ProjectIdentification identification);
public List<String> getPackageFileList(Project project, String filePath);
public List<ProjectIdentification> selectIdentificationGridList(ProjectIdentification identification);
public void updateCopyConfirmStatusProjectStatus(Project project);
void copySrcAndroidNoticeFile(Project project);
public Map<String, List<Project>> updateProjectDivision(Project project);
public void updateComment(Project project);
public String checkOssNicknameList(ProjectIdentification identification);
public void updateFileId(Project project);
public void deleteProjectRefFiles(Project projectInfo);
public void deleteUploadFile(Project project);
public Map<String, Object> getSecurityGridList(Project project);
public void registSecurity(String prjId, String tabName, List<OssComponents> ossComponents);
public List<Project> getProjectIdList(Project project);
public Map<String, Object> getExportDataForSBOMInfo(OssNotice ossNotice);
public boolean checkReqEntrySecurity(Project project, String tabMenu);
public void copySecurityDataForProject(Project project);
public Map<String, Object> checkSelectDownloadFile(Project project);
public List<OssComponents> getDependenciesDataList(Project project);
void registDepOss(List<ProjectIdentification> ossComponents, List<List<ProjectIdentification>> ossComponentsLicense, Project project);
}
| 8,024 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
OssService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/OssService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.*;
public interface OssService extends HistoryConfig{
String registOssMaster(OssMaster ossMaster);
void deleteOssMaster(OssMaster ossMaster);
Map<String,Object> getOssMasterList(OssMaster ossMaster);
Map<String,Object> getOssLicenseList(OssMaster ossMaster);
List<OssMaster> getOssNameList();
OssMaster getOssMasterOne(OssMaster ossMaster);
Map<String, Object> getOssPopupList(OssMaster ossMaster);
Map<String, Object> ossMergeCheckList(OssMaster ossMaster);
Map<String, OssMaster> getBasicOssInfoList (OssMaster ossMaster);
Map<String, OssMaster> getBasicOssInfoList (OssMaster ossMaster, boolean useUpperKey);
OssMaster checkExistsOss(OssMaster param);
OssMaster checkExistsOssNickname(OssMaster param);
OssMaster checkExistsOssNickname2(OssMaster param);
Map<String, OssMaster> getBasicOssInfoListById(OssMaster _param);
String checkExistOssConf(String ossId);
OssMaster getOssInfo(String ossId, boolean isMailFormat);
OssMaster getOssInfo(String ossId, String ossName, boolean isMailFormat);
List<Vulnerability> getOssVulnerabilityList(Vulnerability vulnParam);
List<OssMaster> getOssListByName(OssMaster bean);
String[] getOssNickNameListByOssName(String ossName);
void updateLicenseDivDetail(OssMaster bean);
OssMaster getLastModifiedOssInfoByName(OssMaster bean);
Map<String, Object> checkVdiff(Map<String, Object> reqMap);
String[] checkNickNameRegOss(String ossName, String[] ossNicknames);
void checkOssLicenseAndObligation(OssMaster ossBean);
void updateLicenseTypeAndObligation(OssMaster ossBean);
void deleteOssWithVersionMerege(OssMaster ossMaster) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException ;
Map<String, Object> checkExistsOssDownloadLocation(OssMaster ossMaster);
Map<String, Object> checkExistsOssHomepage(OssMaster ossMaster);
Map<String, Object> checkExistsOssDownloadLocationWithOssName(OssMaster param);
Map<String, Object> checkExistsOssHomepageWithOssName(OssMaster param);
void registOssDownloadLocation(OssMaster ossMaster);
int checkExistsOssByname(OssMaster bean);
List<ProjectIdentification> checkOssName(List<ProjectIdentification> list);
Map<String, Object> saveOssCheckName(ProjectIdentification paramBean, String targetName);
Map<String, Object> saveOssNickname(ProjectIdentification paramBean);
Map<String, Object> saveOss(OssMaster ossBean);
Map<String, Object> saveOssAnalysisList(OssMaster ossBean, String key);
Map<String, Object> getOssAnalysisList(OssMaster ossBean);
int getAnalysisListPage(int rows, String prjId);
Map<String, Object> startAnalysis(String prjId, String fileId, String userName);
OssAnalysis getNewestOssInfo(OssAnalysis bean);
OssAnalysis getNewestOssInfo2(OssAnalysis bean);
Map<String, Object> updateAnalysisComplete(OssAnalysis bean) throws Exception;
OssAnalysis getAutoAnalysisSuccessOssInfo(String referenceOssId);
List<ProjectIdentification> checkOssNameData(List<ProjectIdentification> componentData, Map<String, String> validMap, Map<String, String> diffMap);
List<OssMaster> getOssListBySync(OssMaster bean);
List<String> getOssListSyncCheck(List<OssMaster> selectOssList, List<OssMaster> standardOssList);
void syncOssMaster(OssMaster syncBean, boolean declaredLicenseCheckFlag, boolean detectedLicenseCheckFlag, boolean downloadLocationCheckFlag);
OssMaster makeEmailSendFormat(OssMaster beforeBean);
String checkOssVersionDiff(OssMaster ossMaster);
Map<String, List<OssMaster>> updateOssNameVersionDiff(OssMaster ossMaster);
List<OssLicense> checkLicenseId(List<OssLicense> list);
OssMaster getSaveSesstionOssInfoByName(OssMaster ossMaster);
List<Vulnerability> getOssVulnerabilityList2(OssMaster ossMaster);
List<String> getOssNicknameListWithoutOwn(OssMaster ossMaster, List<String> checkList, List<String> duplicatedList);
Map<String, Object> sendMailForSaveOss(Map<String, Object> resMap);
List<String> getDeactivateOssList();
Map<String, Object> getOssDataMap(String gridId, boolean status, String msg);
Map<String, Object> saveOssURLNickname(ProjectIdentification paramBean);
List<String> selectVulnInfoForOss(OssMaster ossMaster);
List<String> checkExistsVendorProductMatchOss(OssMaster ossMaster);
int checkOssVersionDiff(String ossName);
boolean checkOssTypeForAnalysisResult(OssAnalysis ossAnalysis);
Map<String, Object> getCheckOssNameAjax(ProjectIdentification paramBean, String targetName);
Map<String, Object> getCheckOssLicenseAjax(ProjectIdentification paramBean, String targetName);
String getOssAnalysisStatus(String prjId);
void deleteOssAnalysis(String prjId);
void setVdiffInfoForSentMail(String ossName, CoMail mailBean);
}
| 5,057 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
DashboardService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/DashboardService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Map;
import oss.fosslight.domain.CommentsHistory;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Project;
public interface DashboardService {
Map<String,Object> getDashboardJobsList(Project project);
Map<String,Object> getDashboardCommentsList(CommentsHistory commentsHistory);
Map<String,Object> getDashboardOssList(OssMaster ossMaster);
Map<String,Object> getDashboardLicenseList(LicenseMaster licenseMaster);
void readConfirmAll(CommentsHistory commentsHistory);
}
| 732 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SelfCheckService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/SelfCheckService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.History;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssNotice;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.Vulnerability;
public interface SelfCheckService extends HistoryConfig{
public Map<String, Object> getProjectList(Project project);
public Project getProjectDetail(Project project);
public void registProject(Project project);
public void deleteProject(Project project);
public void registSrcOss(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense, Project project);
public void registSrcOss(List<ProjectIdentification> ossComponent, List<List<ProjectIdentification>> ossComponentLicense, Project project, String refDiv);
Map<String, Object> getIdentificationGridList(ProjectIdentification identification);
List<Vulnerability> getAllVulnListWithProject(String prjId);
void addWatcher(Project project);
void removeWatcher(Project project);
List<Project> copyWatcher(Project project);
boolean existsWatcher(Project project);
public OssNotice setCheckNotice(Project project);
public OssNotice selectOssNoticeOne(String prjId);
public List<OssComponents> getVerifyOssList(Project projectMaster);
public Map<String, Object> getVerificationOne(Project project);
public Project getProjectBasicInfo(String prjId);
public boolean getNoticeHtmlFile(OssNotice ossNotice) throws IOException;
public boolean getNoticeHtmlFile(OssNotice ossNotice, String contents) throws IOException;
public String getNoticeHtml(OssNotice ossNotice) throws IOException;
public History work(Object param);
public String getNoticeTextFileForPreview(OssNotice ossNotice, boolean isConfirm) throws IOException;
public void registOssNotice(OssNotice ossNotice) throws Exception;
public List<OssComponents> setMergeGridData(List<OssComponents> gridData);
public Map<String, Object> getNoticeHtmlInfo(OssNotice ossNotice);
public String getNoticeHtmlFileForPreview(OssNotice ossNotice) throws IOException;
public String getNoticeTextFileForPreview(OssNotice ossNotice) throws IOException;
public boolean existProjectData(Project project);
public Map<String, Object> getExportDataForSBOMInfo(OssNotice ossNotice);
public Map<String, Object> checkSelectDownloadFile(Project project);
public boolean checkUserPermissions(Project project, String userId);
}
| 2,794 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SearchService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/SearchService.java | /*
* Copyright (c) 2021 Suram Kim
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.Vulnerability;
public interface SearchService extends HistoryConfig {
void saveProjectSearchFilter(Project project, String userId);
Project getProjectSearchFilter(String userId);
void saveLicenseSearchFilter(LicenseMaster licenseMaster, String userId);
LicenseMaster getLicenseSearchFilter(String userId);
void saveOssSearchFilter(OssMaster ossMaster, String userId);
OssMaster getOssSearchFilter(String userId);
void saveSelfCheckSearchFilter(Project project, String userId);
Project getSelfCheckSearchFilter(String userId);
void savePartnerSearchFilter(PartnerMaster partnerMaster, String userId);
void saveVulnerabilitySearchFilter(Vulnerability vulnerability, String userId);
PartnerMaster getPartnerSearchFilter(String userId);
Object getSearchFilter(String type, String userId);
void saveSearchFilter(Map<String, Object> params, String userId);
}
| 1,286 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CacheService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/CacheService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Set;
import oss.fosslight.domain.LicenseMaster;
public interface CacheService {
Set<String> getLicenseNames();
Set<String> getLicenseUpperNames();
LicenseMaster getLicenseInfo(String licenseName);
LicenseMaster getLicenseInfoById(String licenseId);
}
| 420 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ApiVulnerabilityService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/ApiVulnerabilityService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import java.util.Map;
public interface ApiVulnerabilityService {
public List<Map<String, Object>> selectNvdList(String product, String version, String id);
public List<Map<String, Object>> selectMaxScoreNvdInfo(String product, String version);
}
| 400 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
AutoIdService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/AutoIdService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.domain.BinaryData;
import oss.fosslight.repository.BinaryDataMapper;
import oss.fosslight.util.TlshUtil;
@Service
public class AutoIdService {
@Autowired private BinaryDataMapper binaryDataMapper;
@Cacheable(value="tlshFindOssInfoCache", key="{#root.methodName, #binaryName, #checkSum, #tish}")
public List<BinaryData> findOssInfoWithBinaryName(String binaryName, String checkSum, String tlsh) {
List<BinaryData> dbDataList = binaryDataMapper.getBinaryListWithNameAndChecksum(binaryName, checkSum);
// check sum이 동일한 정보가 존재하는 경우는 모두 반환한다.
if(dbDataList != null && !dbDataList.isEmpty()) {
for(BinaryData item : dbDataList) {
item.setDownloadlocation(CommonFunction.getOssDownloadLocation(item.getOssName(), item.getOssVersion()));
}
return dbDataList;
}
// checksum이 동일한 binary 정보가 없는경우, distance를 비교한다.
dbDataList = binaryDataMapper.selectBinaryDataListWithBinaryName(binaryName);
if(!dbDataList.isEmpty()) {
for(BinaryData item : dbDataList) {
item.setDownloadlocation(CommonFunction.getOssDownloadLocation(item.getOssName(), item.getOssVersion()));
}
List<BinaryData> list = new ArrayList<>();
// tlsh distance를 비교하여 근접값을 찾는다.
BinaryData binaryData = findCloseBatOssWithTlshDistance(tlsh, dbDataList);
if(binaryData != null) {
list.add(binaryData);
return list;
}
}
return null;
}
/**
* tlsh distance가 가장 가까운 binary 정보를 찾는다.
* @param tish
* @param dbDataList
* @return
*/
private BinaryData findCloseBatOssWithTlshDistance(String tlsh, List<BinaryData> dbDataList) {
int currentDistance = 999999;
BinaryData currentBinaryBean = null;
for(BinaryData bean : dbDataList) {
if("0".equals(tlsh)) {
if("0".equals(bean.getTlshCheckSum())) {
return bean;
}
} else {
int _distance = TlshUtil.compareTlshDistance(tlsh, bean.getTlshCheckSum());
if(_distance <= 120 && _distance > -1 && _distance < currentDistance) {
currentDistance = _distance;
currentBinaryBean = bean;
}
}
}
if(currentDistance <= 120) {
return currentBinaryBean;
}
return null;
}
}
| 2,655 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ConfigurationService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/ConfigurationService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.HashMap;
import oss.fosslight.domain.Configuration;
public interface ConfigurationService {
public void updateDefaultSetting(Configuration configuration);
// public void updateDefaultLocale(Configuration configuration);
}
| 382 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/VulnerabilityService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.Vulnerability;
public interface VulnerabilityService {
HashMap<String, Object> getVulnerabilityList(Vulnerability vulnerability, boolean exportFlag);
HashMap<String, Object> getVulnerabilityAutoComplete();
List<String> getVulnerabilityVersionAutoComplete(String name);
Map<String, Object> getVulnListByOssName(OssMaster bean);
Map<String, Object> getCveInfo(String cveId);
List<String> getPatchLinkForNvdData(String cveId);
List<Vulnerability> getSecurityVulnListByOssName(OssMaster bean);
List<Map<String, Object>> getCpeInfoAndRange(String cveId, String ossName);
Vulnerability selectNotFixedCveInfo(OssMaster bean);
boolean getCpeMatchForCpeInfoCnt(Map<String, Object> paramMap);
}
| 1,005 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
PartnerService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/PartnerService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.OssMaster;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.T2Users;
public interface PartnerService extends HistoryConfig{
public Map<String, Object> getPartnerMasterList(PartnerMaster partnerMaster);
public Map<String, Object> getPartnerStatusList(PartnerMaster partnerMaster);
public int updateReviewer(PartnerMaster vo);
public List<PartnerMaster> getPartnerNameList(PartnerMaster partnerMaster);
public void registPartnerMaster(PartnerMaster partnerMaster, List<ProjectIdentification> ossComponents, List<List<ProjectIdentification>> ossComponentsLicense);
public PartnerMaster getPartnerMasterOne(PartnerMaster partnerMaster);
public void deletePartnerMaster(PartnerMaster partnerMaster);
public List<T2Users> getUserList(T2Users t2Users);
public void changeStatus(PartnerMaster partnerMaster, boolean isCoReviewer);
public List<PartnerMaster> getPartnerSwNmList(PartnerMaster partnerMaster);
public List<PartnerMaster> getPartnerSwVerList(PartnerMaster partnerMaster);
public void updatePartnerConfirm(PartnerMaster partnerMaster);
public List<PartnerMaster> getPartnerDuplication(PartnerMaster partnerMaster);
public String checkViewOnly(String partnerId);
public void addWatcher(PartnerMaster project);
public void removeWatcher(PartnerMaster project);
public List<PartnerMaster> copyWatcher(PartnerMaster project);
public List<String> getInvateWatcherList(String prjId);
public void updatePublicYn(PartnerMaster partnerMaster);
public boolean existsWatcher(PartnerMaster project);
public Map<String, Object> getPartnerValidationList(PartnerMaster partnerMaster);
public Map<String, Object> getPartnerValidationList(PartnerMaster partnerMaster, boolean coReview);
public Map<String, Object> getFilterdList(Map<String, Object> paramMap);
public Map<String, Object> getIdentificationGridList(ProjectIdentification identification);
public int updateDivision(String partnerId, String division);
public Map<String, List<PartnerMaster>> updatePartnerDivision(PartnerMaster partnerMaster);
public void updateDescription(PartnerMaster partnerMaster);
public List<PartnerMaster> getPartnerIdList(PartnerMaster partnerMaster);
public Map<String, Object> getExportDataForSbomInfo(PartnerMaster partnerMaster);
public Map<String, Object> checkSelectDownloadFile(PartnerMaster partnerMaster);
} | 2,750 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2RolesService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/T2RolesService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import oss.fosslight.domain.T2Roles;
public interface T2RolesService {
public List<T2Roles> getAllRoles();
public List<T2Roles> getAllRolesAndSecuredResourcesRole();
public T2Roles getRoles(T2Roles role);
public T2Roles getRolesAndSecuredResourcesRole(T2Roles roles);
@Transactional
public int modifyRolesAndSecuredResourcesRole(T2Roles roles);
@Transactional
public int registRolesAndSecuredResourcesRole(T2Roles roles);
@Transactional
public int deleteRolesAndSecuredResourcesRole(String[] roleIds);
}
| 772 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2SecuredResourcesService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/T2SecuredResourcesService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import oss.fosslight.domain.T2SecuredResources;
public interface T2SecuredResourcesService {
public List<T2SecuredResources> getAllSecuredResources();
public List<T2SecuredResources> getAllSecuredResourcesAndSecuredResourcesRoles();
public T2SecuredResources getSecuredResources(T2SecuredResources securedResources);
public T2SecuredResources getSecuredResources(String resourceId);
public T2SecuredResources getSecuredResourcesAndSecuredResourcesRoles(String resourceId);
public int modifySecuredResource(T2SecuredResources securedResource);
public int registSecuredResource(T2SecuredResources securedResource);
public int deleteSecuredResourcesAndSecuredResourcesRole(String[] resourceIds);
}
| 895 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
HistoryService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/HistoryService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Map;
import oss.fosslight.domain.History;
public interface HistoryService {
public void storeData(History history);
public History getData(History history);
public Map<String, Object> getList(History history);
public Map<String, Object> getAsToBeHistoryDataByGrid(History history);
}
| 458 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CodeService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/CodeService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import oss.fosslight.domain.T2Code;
import oss.fosslight.domain.T2CodeDtl;
public interface CodeService {
Map<String, Object> getCodeList(T2Code vo) throws Exception;
ArrayList<T2CodeDtl> getCodeDetailList(T2CodeDtl vo) throws Exception;
void setCode(T2Code vo) throws Exception;
void setCodeDetails(List<T2CodeDtl> dtlList, String cdNo) throws Exception;
public boolean isExists(T2Code vo);
List<T2Code> getcodeList(T2Code t2Code);
List<T2Code> getcodeNmList(T2Code t2Code);
}
| 708 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2UserService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/T2UserService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import com.google.gson.JsonObject;
import oss.fosslight.domain.T2Users;
@Service
public interface T2UserService extends UserDetailsService {
public List<T2Users> getAllUsers(T2Users t2Users);
public T2Users getUser(T2Users user);
public List<T2Users> getAuthorityUsers(String authority);
public T2Users getUserAndAuthorities(T2Users user);
public JsonObject selectDuplicateId(String userId);
public int addNewUsers(T2Users t2Users);
public int changEnabled(T2Users t2Users);
public int updateUsers(T2Users t2Users);
public int modifyUserRoles(T2Users member);
public String getPassword(T2Users user);
public Map<String,Object> getUserList(T2Users vo);
public void setUser(T2Users vo) throws Exception;
public void modUser(List<T2Users> vo);
public List<T2Users> getUserListExcel() throws Exception;
public boolean checkDuplicateId(T2Users vo);
public List<T2Users> getReviwer();
public List<T2Users> selectAllUsers();
public List<T2Users> getAllUsersDivision();
public boolean checkAdAccounts(Map<String, String> userInfo, String idKey, String pwKey, String filter);
public List<T2Users> checkEmail(String email);
public List<T2Users> getUserListByName(String name);
public T2Users getLoginUserInfo();
public boolean isLeavedMember(String userId);
public T2Users checkApiUserAuth(String _token);
public T2Users checkApiUserAuthAndSetSession(String _token);
public T2Users changeSession(String userId);
public boolean procToken(T2Users vo);
public boolean checkPassword(String rawPassword, T2Users bean);
public boolean existUserIdOrEmail(String userId);
public int updateUserNameDivision(T2Users userInfo);
public String[] checkUserInfo(T2Users userInfo);
public boolean isAdmin(String _token);
}
| 2,115 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ComplianceService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/ComplianceService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Map;
import oss.fosslight.domain.Project;
public interface ComplianceService {
public Map<String, Object> getModelList(Project project);
}
| 299 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
FileService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/FileService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oss.fosslight.domain.T2File;
import oss.fosslight.domain.UploadFile;
public interface FileService {
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile);
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile, String inputFileName);
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile, String inputFileName, String fileId);
public List<UploadFile> uploadNoticeXMLFile(HttpServletRequest req, T2File registFile, String oldFileId, String prjId);
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile, String inputFileName, boolean randomNm, String filePath);
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile, String inputFileName, String fileId, boolean randomNm, String filePath);
public List<UploadFile> uploadFile(HttpServletRequest req, T2File registFile, String inputFileName, String fileId, boolean randomNm, String filePath, boolean isOrigFile);
public T2File selectFileInfo(String fileSeq);
public String registFileWithFileName(String filePath, String fileName);
public String registFileDownload(String filePath, String fileName, String logiFileName);
public T2File selectFileInfoById(String fileSeq);
public String copyFileInfo(String orgFileId);
public T2File selectFileInfoByLogiName(T2File bean);
public List<UploadFile> uploadWgetFile(HttpServletRequest req, T2File registFile, Map<Object, Object> map, boolean isOrigFile);
public String setClearFiles(Map<Object, Object> map);
public void deleteFiles(String url, List<T2File> uploadFileInfo, String prjId, T2File vulDOCFileInfo);
public List<UploadFile> setReusePackagingFile(String refFileSeq);
public void deletePhysicalFile(T2File t2File, String flag);
public String copyPhysicalFile(String fileId);
}
| 2,119 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityHistoryService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/VulnerabilityHistoryService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.Map;
import oss.fosslight.domain.VulnerabilityHistory;
public interface VulnerabilityHistoryService {
Map<String, Object> getVulnerabilityHistoryList(VulnerabilityHistory vulnerabilityHistory);
}
| 355 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
LicenseService.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/service/LicenseService.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.service;
import java.util.List;
import java.util.Map;
import oss.fosslight.config.HistoryConfig;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssMaster;
public interface LicenseService extends HistoryConfig{
int selectLicenseMasterTotalCount(LicenseMaster licenseMaster);
Map<String,Object> getLicenseMasterList(LicenseMaster licenseMaster);
LicenseMaster getLicenseMasterOne(LicenseMaster licenseMaster); // 라이센스 단일
List<OssMaster> checkExistsUsedOss(String licenseId);
LicenseMaster checkExistsLicense(LicenseMaster param);
List<LicenseMaster> getLicenseMasterListExcel(LicenseMaster license); // 라이센스 리스트 엑셀용
String registLicenseMaster(LicenseMaster licenseMaster); // 라이센스 등록
int deleteLicenseMaster(LicenseMaster licenseMaster); // 라이센스 삭제
void deleteDistributeLicense(LicenseMaster bean, boolean distributionFlag);
void registNetworkServerLicense(String licenseId, String type);
List<OssMaster> updateOssLicenseType(String licenseId);
boolean distributeLicense(String licenseId, boolean distributionFlag);
List<LicenseMaster> getLicenseNameList(); // 라이센스 자동완성
void sendLicenseTypeChangedMail(String licenseId, LicenseMaster beforeBean, LicenseMaster afterBean, String comment);
void registLicenseWebPage(LicenseMaster licenseMaster);
String webPageStringFormat(String[] webpages);
LicenseMaster getLicenseId(LicenseMaster licenseMaster);
Map<String, Object> getLicenseDataMap(String gridId, boolean status, String msg);
Map<String, Object> saveLicense(LicenseMaster licenseMaster);
void deleteLicenseMasterForRestriction(LicenseMaster licenseMaster);
}
| 1,919 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.