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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
BatWatcher.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/BatWatcher.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
/**
* The Class batMaster.
*/
public class BatWatcher extends ComBean implements Serializable{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 5429990726160434346L;
/** The bat id. */
private String batId;
/** The division. */
private String division;
/** The user id. */
private String userId;
/** The user id. */
private String userName;
private String email;
private String useYn;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Gets the division.
*
* @return the division
*/
public String getDivision() {
return division;
}
/**
* Sets the division.
*
* @param division the new division
*/
public void setDivision(String division) {
this.division = division;
}
/**
* Gets the user id.
*
* @return the user id
*/
public String getUserId() {
return userId;
}
/**
* Sets the user id.
*
* @param userId the new user id
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Gets the bat id.
*
* @return the bat id
*/
public String getBatId() {
return batId;
}
/**
* Sets the bat id.
*
* @param batId the new bat id
*/
public void setBatId(String batId) {
this.batId = batId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUseYn() {
return useYn;
}
public void setUseYn(String useYn) {
this.useYn = useYn;
}
} | 1,827 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
T2Roles.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/T2Roles.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.config.AppConstBean;
@Setter
@Getter
public class T2Roles implements Serializable{
private static final long serialVersionUID = 1L;
private String authority; // 권한
private String roleName; // 권한 명
private String description; // 권한 설명
private String createDate; // 등록일
private String modifyDate; // 수정일
private List<T2SecuredResourcesRole> securedResourcesRole; // 권한에 맵핑된 리소스
public void setupDefaultRoleData(){
this.authority = AppConstBean.SECURITY_ROLE_DEFAULT;
this.roleName = "모든 사용자가 가지는 기본 역할";
this.description = "모든 사용자가 가지는 기본 역할. 삭제 불가능.";
this.setCreateDate();
this.setModifyDate();
}
public void setCreateDate() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(CoConstDef.DATABASE_FORMAT_DATE_ALL);
this.createDate = sdf.format(now);
}
public void setModifyDate(){
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(CoConstDef.DATABASE_FORMAT_DATE_ALL);
this.modifyDate = sdf.format(now);
}
} | 1,486 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
Statistics.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/Statistics.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Setter @Getter
public class Statistics extends ComBean implements Serializable {
private static final long serialVersionUID = 1L;
private String[] colorArray; // 추후 관리가 필요함
private List<String> titleArray;
private ArrayList<ArrayList<Integer>> dataArray = new ArrayList<ArrayList<Integer>>();
private String chartType;
private String categoryType;
private String isRawData;
private String updateType;
private List<String> noneUser;
private List<String> excludedTarget;
// STT : Status, REV : Reviewer, DST : Distribution Type
private String divisionNo;
private String divisionNm;
private int divisionOrder;
private String titleNm;
private String[] divisionNums;
private int category0Cnt = -1;
private int category1Cnt = -1;
private int category2Cnt = -1;
private int category3Cnt = -1;
private int category4Cnt = -1;
private int category5Cnt = -1;
private int category6Cnt = -1;
private int category7Cnt = -1;
private int category8Cnt = -1;
private int total;
public void addCategoryCnt(int categoryCnt, int idx) {
if (this.dataArray.size() == idx) {
this.dataArray.add(new ArrayList<Integer>());
}
this.dataArray.get(idx).add(categoryCnt);
}
/**
* MOST USED OSS & License CHART
* */
private int pieSize;
private String columnName;
private int columnCnt;
private int diffMonthCnt;
private int categorySize;
/**
* UPDATED OSS & License CHART
* */
private List<String> categoryList;
public void addCategoryList(String columnName) {
if (this.categoryList == null) {
this.categoryList = new ArrayList<String>();
}
this.categoryList.add(columnName);
}
public void setTotal() {
int total = 0;
total += this.category0Cnt > 0 ? this.category0Cnt : 0;
total += this.category1Cnt > 0 ? this.category1Cnt : 0;
total += this.category2Cnt > 0 ? this.category2Cnt : 0;
total += this.category3Cnt > 0 ? this.category3Cnt : 0;
total += this.category4Cnt > 0 ? this.category4Cnt : 0;
total += this.category5Cnt > 0 ? this.category5Cnt : 0;
total += this.category6Cnt > 0 ? this.category6Cnt : 0;
total += this.category7Cnt > 0 ? this.category7Cnt : 0;
total += this.category8Cnt > 0 ? this.category8Cnt : 0;
this.total = total;
}
}
| 2,580 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
VulnerabilityHistory.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/VulnerabilityHistory.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class VulnerabilityHistory extends ComBean implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -3663117731731226112L;
String ossId;
String ossName;
String ossVersion;
String cveId;
String cvssScore;
String cveIdTo;
String cvssScoreTo;
String regDt;
}
| 570 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
Dashboard.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/Dashboard.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
public class Dashboard extends ComBean implements Serializable {
private static final long serialVersionUID = 9018255826730935058L;
private String id;
private String name;
private String status;
private String review;
private String time;
private String type;
private String version;
private String license;
private String identitier;
private String website;
private String ossNoticeDueDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getIdentitier() {
return identitier;
}
public void setIdentitier(String identitier) {
this.identitier = identitier;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getOssNoticeDueDate() {
return ossNoticeDueDate;
}
public void setOssNoticeDueDate(String ossNoticeDueDate) {
this.ossNoticeDueDate = ossNoticeDueDate;
}
}
| 2,222 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
History.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/domain/History.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.domain;
import java.io.Serializable;
public class History extends ComBean implements Serializable {
private static final long serialVersionUID = 3832152613376387438L;
private String idx; // index
private String hKey; // master seq
private String hTitle; // 제목
private String hType; // 이벤트 종류
private String hTypeNm; // 이벤트 종류 이름
private String hComment; // 수정사유
private String hEtc; // 비고
private String hAction; // CUD 액션
private Object hData; // Data
public History() {
super();
}
public History(String idx) {
super();
this.idx = idx;
}
public String getIdx() {
return idx;
}
public void setIdx(String idx) {
this.idx = idx;
}
public String gethKey() {
return hKey;
}
public void sethKey(String hKey) {
this.hKey = hKey;
}
public String gethTitle() {
return hTitle;
}
public void sethTitle(String hTitle) {
this.hTitle = hTitle;
}
public String gethType() {
return hType;
}
public void sethType(String hType) {
this.hType = hType;
}
public String gethComment() {
return hComment;
}
public void sethComment(String hComment) {
this.hComment = hComment;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String gethAction() {
return hAction;
}
public void sethAction(String hAction) {
this.hAction = hAction;
}
public Object gethData() {
return hData;
}
public void sethData(Object hData) {
this.hData = hData;
}
public String gethEtc() {
return hEtc;
}
public void sethEtc(String hEtc) {
this.hEtc = hEtc;
}
public String gethTypeNm() {
return hTypeNm;
}
public void sethTypeNm(String hTypeNm) {
this.hTypeNm = hTypeNm;
}
}
| 1,895 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
FileUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/FileUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.Part;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import oss.fosslight.common.CommonFunction;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FileUtil {
private static final String ILLEGAL_EXP = "[:\\\\/%*?:|\"<>]";
/**
* 외부에서 생성자를 호출하지 못하도록 접근제어자 private 으로 설정
*/
private FileUtil(){}
/**
* Part 에서 File Name을 추출하여 리턴한다.
*
* @param javax.servlet.http.Part
* @return File Name(Type String)
*/
public static String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
public static File writeFile(MultipartFile multipart, String fPath, String fName) {
File file = null;
if (multipart != null && fPath != null && fName != null) {
try {
file = new File(fPath+ "/" + fName);
multipart.transferTo(file);
} catch (Exception e) {
log.error(e.getMessage(), e);
log.info("Failed transfer From Multipart, retry with input stream");
try {
FileUtils.copyInputStreamToFile(multipart.getInputStream(), file);
} catch (IOException e1) {
log.error(e.getMessage(), e);
}
}
}
return file;
}
public static boolean transferTo(MultipartFile multipart, File file) {
if (multipart != null && file != null) {
try {
multipart.transferTo(file);
return true;
} catch (Exception e) {
// local개발환경(window)에서는 상대 path를 사용하면 에러가 발생할 수 있다.
log.debug("Failed transfer From Multipart, retry with input stream");
try {
FileUtils.copyInputStreamToFile(multipart.getInputStream(), file);
return true;
} catch (IOException e1) {
log.error(e.getMessage(), e);
}
}
}
return false;
}
public static boolean moveTo(String srcFilePath, String copyFilePath, String copyFileName) {
if (!StringUtil.isEmpty(srcFilePath) && !StringUtil.isEmpty(copyFilePath)) {
try {
Path srcFile = Paths.get(srcFilePath);
Path copyPath = Paths.get(copyFilePath);
if (!StringUtil.isEmpty(copyFileName)) {
if (!Files.exists(copyPath)) {
Files.createDirectory(copyPath);
}
copyPath = copyPath.resolve(copyFileName);
}
Files.move(srcFile, copyPath);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return false;
}
public static boolean writeFile(String filePath, String fileName, String contents) {
BufferedWriter fw = null;
try {
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
// BufferedWriter 와 FileWriter를 조합하여 사용 (속도 향상)
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath + "/" + fileName), Charset.forName("UTF8")));
fw.write(contents);
fw.flush();
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
} finally {
if (fw != null) {
try {
fw.close();
} catch (Exception e) {}
}
}
return true;
}
public static boolean writeReviewReportFile(String filePath, String fileName, String contents) {
try {
File dir = new File(filePath);
if (!dir.exists()) {
dir.mkdirs();
}
ByteArrayInputStream inputStream = PdfUtil.html2pdf(contents);
FileUtils.copyInputStreamToFile(inputStream, new File(filePath + "/" + fileName));
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
return true;
}
/**
* 파일 이름이 유효한지 확인한다.
*
* @param fileName 파일의 이름, Path를 제외한 순수한 파일의 이름..
* @return
*/
public static boolean isValidFileName(String fileName) {
if (fileName == null || fileName.trim().length() == 0) {
return false;
}
return !Pattern.compile(ILLEGAL_EXP).matcher(fileName).find();
}
/**
* 파일 이름에 사용할 수 없는 캐릭터를 바꿔서 유효한 파일로 만든다.
*
* @param fileName 파일 이름, Path를 제외한 순수한 파일의 이름..
* @param replaceStr 파일 이름에 사용할 수 없는 캐릭터의 교체 문자
* @return
*/
public static String makeValidFileName(String fileName, String replaceStr) {
if (fileName == null || fileName.trim().length() == 0 || replaceStr == null) {
return String.valueOf(System.currentTimeMillis());
}
return fileName.replaceAll(ILLEGAL_EXP, replaceStr).replaceAll("\t", "").trim();
}
public static void zip(String inputFolder, String filePath, String zipName, String zipRootEntryName) throws Exception {
// 압축파일을 저장할 파일을 선언한다.
File file = new File(filePath + File.separator + zipName);
try (
FileOutputStream fileOutputStream = new FileOutputStream(file);
// ZipOutputStream 선언
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
) {
// 압축할 대상이 있는 폴더를 파일로 선언한다.
File inputFile = new File(inputFolder);
// 압축을 할 대상이 file이면 zipFile 메소드를,
// 폴더이면 zipFolder 메소드를 호출한다.
if (inputFile.isFile()) {
zipFile(zipOutputStream, inputFile, "");
} else if (inputFile.isDirectory()) {
zipFolder(zipOutputStream, inputFile, "", zipRootEntryName);
}
} catch (Exception e) {
throw e;
}
}
public static void zipFolder(ZipOutputStream zipOutputStream, File inputFile, String parentName, String zipEntryName) throws Exception {
String myName = parentName + inputFile.getName() + File.separator;
if (zipEntryName != null && zipEntryName.trim().length() > 0) {
myName = zipEntryName + File.separator;
}
// ZipEntry를 생성 후 zip 메소드에서 인자값으로 받은 파일의 구성 정보를 생성한다.
ZipEntry folderZipEntry = new ZipEntry (myName);
zipOutputStream.putNextEntry (folderZipEntry);
// zip 메소드에서 인자값으로 전달받은 파일의 구성파일들을 list형식으로 저장한다.
File[] contents = inputFile.listFiles();
// inputFolder의 구성파일이 파일이면 zipFile 메소드를 호출하고,
// 폴더일 경우 현재 zipFolder 메소드를 재귀호출
if (contents != null) {
for (File file : contents) {
if (file.isFile()) {
zipFile(zipOutputStream, file, myName);
} else if (file.isDirectory()) {
zipFolder(zipOutputStream, file, myName, "");
}
zipOutputStream.closeEntry ();
}
}
}
public static void zipFile(ZipOutputStream zipOutputStream, File inputFile, String parentName) throws Exception {
ZipEntry zipEntry = new ZipEntry (parentName + inputFile.getName());
try (
FileInputStream fileInputStream = new FileInputStream(inputFile);
){
// ZipEntry생성 후 zip 메소드에서 인자값으로 전달받은 파일의 구성 정보를 생성한다.
zipOutputStream.putNextEntry (zipEntry);
byte[] buf = new byte[4096];
int byteRead;
// 압축대상 파일을 설정된 사이즈만큼 읽어들인다.
// buf의 size는 원하는대로 설정가능하다.
while ((byteRead = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, byteRead);
}
} catch (Exception e) {
throw e;
}
}
public static boolean copyFile(String srcFilePath, String copyFilePath, String copyFileName) {
if (!StringUtil.isEmpty(srcFilePath) && !StringUtil.isEmpty(copyFilePath)) {
try {
File dir = new File(copyFilePath);
if (!dir.exists()) {
dir.mkdirs();
}
Path srcFile = Paths.get(srcFilePath);
Path copyPath = Paths.get(copyFilePath);
if (!StringUtil.isEmpty(copyFileName)) {
copyPath = copyPath.resolve(copyFileName);
}
Files.copy(srcFile, copyPath);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
return false;
}
/**
* Downloads a file from a URL
* @param fileURL HTTP URL of the file to be downloaded
* @param saveDir path of the directory to save the file
* @throws Exception
*/
public static void downloadFile(String fileURL, String saveDir)
throws Exception {
HttpURLConnection httpConn = null;
FileOutputStream outputStream = null;
InputStream inputStream = null;
URL url = new URL(fileURL);
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// opens input stream from the HTTP connection
inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
if (!Files.exists(Paths.get(saveDir))) {
Files.createDirectories(Paths.get(saveDir));
}
// opens an output stream to save into file
outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} else {
throw new Exception("No file to download. Server replied HTTP code: " + responseCode);
}
} finally {
if (httpConn != null) {
try {
httpConn.disconnect();
} catch (Exception e) {}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {}
}
}
}
/**
* 압축풀기 메소드
* @param zipFileName 압축파일
* @param directory 압축 풀 폴더
*/
public static void decompress(String zipFileName, String directory) throws IOException {
File zipFile = new File(zipFileName);
FileInputStream fis = null;
ZipInputStream zis = null;
ZipEntry zipentry = null;
try {
fis = new FileInputStream(zipFile);
zis = new ZipInputStream(fis);
while ((zipentry = zis.getNextEntry ()) != null) {
String filename = zipentry.getName();
File file = new File(directory, filename);
if (zipentry.isDirectory()) {
file.mkdirs();
} else {
createFile(file, zis);
}
}
} finally {
if (zis != null) {
zis.close();
}
if (fis != null) {
fis.close();
}
}
}
/**
* 파일 만들기 메소드
* @param file 파일
* @param zis Zip스트림
*/
public static void createFile(File file, ZipInputStream zis) throws IOException {
FileOutputStream fos = null;
File parentDir = new File(file.getParent());
if (!parentDir.exists()) {
parentDir.mkdirs();
}
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[256];
int size = 0;
while ((size = zis.read(buffer)) > 0) {
fos.write(buffer, 0, size);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {}
}
}
}
public static void backupRawData(String sourceFilePath, String destPath) {
try {
// zip 파일 백업
Path zipPath = Paths.get(sourceFilePath);
Path movePath = Paths.get(destPath);
if (!Files.exists(movePath)) {
Files.createDirectories(movePath);
}
if (Files.exists(zipPath)) {
Files.move(zipPath, movePath.resolve(zipPath.getFileName() + "_" + CommonFunction.getCurrentDateTime("yyyyMMddHHmmss")));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
| 14,312 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
YamlUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/YamlUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.google.common.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.config.AppConstBean;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.service.FileService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SelfCheckService;
@PropertySources(value = {@PropertySource(value=AppConstBean.APP_CONFIG_PROPERTIES_PATH)})
@Slf4j
public class YamlUtil extends CoTopComponent {
private static String writepath = CommonFunction.emptyCheckProperty("export.template.path", "/template");
private static FileService fileService = (FileService) getWebappContext().getBean(FileService.class);
private static ProjectService projectService = (ProjectService) getWebappContext().getBean(ProjectService.class);
private static SelfCheckService selfCheckService = (SelfCheckService) getWebappContext().getBean(SelfCheckService.class);
public static String makeYaml(String type, String dataStr) throws Exception {
String downloadFileId = "";
switch(type) {
case CoConstDef.CD_DTL_COMPONENT_ID_SRC: // OSS Name, OSS version, License, Download location, Homepage, Copyright,Exclude 가 동일한 경우 Merge. > Source Name or Path, Binary Name, Binary Name or Source Path, Comment
case CoConstDef.CD_DTL_COMPONENT_ID_BIN: // OSS Name, OSS version, License, Download location, Homepage, Copyright,Exclude 가 동일한 경우 Merge. > Source Name or Path, Binary Name, Binary Name or Source Path, Comment
case CoConstDef.CD_DTL_COMPONENT_ID_ANDROID: // Source Path, OSS Name, OSS version, License, Download location, Homepage, Copyright, Exclude 가 동일한 경우 Merge > Binary Name, Comment
case CoConstDef.CD_DTL_COMPONENT_ID_BOM: // Merge 없음
downloadFileId = makeYamlIdentification(dataStr, type);
break;
case CoConstDef.CD_DTL_COMPONENT_PARTNER: // OSS Name, OSS version, License, Download location, Homepage, Copyright,Exclude 가 동일한 경우 Merge. > Source Name or Path, Binary Name, Binary Name or Source Path, Comment
downloadFileId = makeYamlPartner(dataStr, type);
break;
default:
// self-check // OSS Name, OSS version, License, Download location, Copyright,Exclude 가 동일한 경우 Merge. > Binary Name or Source Path
downloadFileId = makeYamlSelfCheck(dataStr, type);
break;
}
return downloadFileId;
}
private static String makeYamlIdentification(String dataStr, String type) throws Exception {
Type projectType = new TypeToken<Project>(){}.getType();
Project projectBean = (Project) fromJson(dataStr, projectType);
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv(type);
_param.setReferenceId(projectBean.getPrjId());
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
_param.setMerge(CoConstDef.FLAG_NO);
}
Map<String, Object> map = projectService.getIdentificationGridList(_param, true);
List<ProjectIdentification> list = (List<ProjectIdentification>) map.get(CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type) ? "rows" : "mainData");
String jsonStr = "";
if (list != null) {
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
jsonStr = toJson(checkYamlFormat(projectService.setMergeGridData(list), type));
} else {
jsonStr = toJson(checkYamlFormat(setMergeData(list, type)));
}
}
// fosslight_sbom_info_[date]_prj-[ID].yaml
String fileName = "fosslight_sbom_info_" + CommonFunction.getCurrentDateTime() + "_prj-" + projectBean.getPrjId();
return makeYamlFileId(fileName, convertJSON2YAML(jsonStr));
}
private static String makeYamlPartner(String dataStr, String typeCode) throws Exception {
Type partnerType = new TypeToken<PartnerMaster>(){}.getType();
PartnerMaster partnerBean = (PartnerMaster) fromJson(dataStr, partnerType);
// partner > OSS List
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
_param.setReferenceId(partnerBean.getPartnerId());
Map<String, Object> map = projectService.getIdentificationGridList(_param, true);
List<ProjectIdentification> list = new ArrayList<>();
list = (List<ProjectIdentification>) map.get("mainData");
String jsonStr = "";
if (list != null) {
jsonStr = toJson(checkYamlFormat(setMergeData(list, typeCode)));
}
// fosslight_sbom_info_[date]_3rd-[ID].yaml
String fileName = "fosslight_sbom_info_" + CommonFunction.getCurrentDateTime() + "_3rd-" + partnerBean.getPartnerId();
return makeYamlFileId(fileName, convertJSON2YAML(jsonStr));
}
private static String makeYamlSelfCheck(String dataStr, String typeCode) throws Exception {
Type projectType = new TypeToken<Project>(){}.getType();
Project projectBean = (Project) fromJson(dataStr, projectType);
// partner > OSS List
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv("10");
_param.setReferenceId(projectBean.getPrjId());
Map<String, Object> map = selfCheckService.getIdentificationGridList(_param);
List<ProjectIdentification> list = new ArrayList<>();
list = (List<ProjectIdentification>) map.get("mainData");
String jsonStr = "";
if (list != null) {
jsonStr = toJson(checkYamlFormat(setMergeData(list, typeCode)));
}
// fosslight_sbom_info_[date]_self-[ID].yaml
String fileName = "fosslight_sbom_info_" + CommonFunction.getCurrentDateTime() + "_self-" + projectBean.getPrjId();
return makeYamlFileId(fileName, convertJSON2YAML(jsonStr));
}
private static LinkedHashMap<String, List<Map<String, Object>>> checkYamlFormat(List<ProjectIdentification> list) {
return checkYamlFormat(list, "");
}
public static LinkedHashMap<String, List<Map<String, Object>>> checkYamlFormat(List<ProjectIdentification> list, String typeCode) {
LinkedHashMap<String, List<Map<String, Object>>> result = new LinkedHashMap<>();
for (ProjectIdentification bean : list) {
List<Map<String, Object>> ossNameResult = new ArrayList<>();
LinkedHashMap<String, Object> yamlFormat = new LinkedHashMap<>();
if (!isEmpty(bean.getOssVersion())) {
yamlFormat.put("version", bean.getOssVersion());
} else{
yamlFormat.put("version", "");
}
if (isEmpty(typeCode)) {
if (!isEmpty(bean.getBinaryName())) {
String binaryNameStr = bean.getBinaryName();
yamlFormat.put("source name or path", binaryNameStr.contains("\n") ? binaryNameStr.split("\n") : binaryNameStr);
} else if (!isEmpty(bean.getFilePath())) {
String filePathStr = bean.getFilePath();
yamlFormat.put("source name or path", filePathStr.contains("\n") ? filePathStr.split("\n") : filePathStr);
}
}
String licenseNameStr = bean.getLicenseName();
yamlFormat.put("license", licenseNameStr.contains(",") ? licenseNameStr.split(",") : licenseNameStr);
if (!isEmpty(bean.getDownloadLocation())) {
yamlFormat.put("download location", bean.getDownloadLocation());
}
if (!isEmpty(bean.getHomepage())) {
yamlFormat.put("homepage", bean.getHomepage());
}
if (!isEmpty(bean.getCopyrightText())) {
String copyrightStr = bean.getCopyrightText();
yamlFormat.put("copyright text", copyrightStr.contains("\n") ? Arrays.asList(copyrightStr.split("\n")) : copyrightStr);
}
if (CoConstDef.FLAG_YES.equals(avoidNull(bean.getExcludeYn(), CoConstDef.FLAG_NO))) {
yamlFormat.put("exclude", true);
}
if (!isEmpty(bean.getComments())) {
yamlFormat.put("comment", bean.getComments());
}
String ossNameStr = bean.getOssName();
if (ossNameStr.length() == 0) {
ossNameStr = "-";
}
if (result.containsKey(ossNameStr)) {
ossNameResult = result.get(ossNameStr);
}
ossNameResult.add(yamlFormat);
result.put(ossNameStr, ossNameResult);
}
return result;
}
public static String convertJSON2YAML(String jsonStr) {
return convertJSON2YAML(jsonStr, "");
}
public static String convertJSON2YAML(String jsonStr, String suffix) {
String yamlStr = "";
try {
if (!isEmpty(jsonStr)) {
JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonStr);
// save it as YAML
yamlStr = new YAMLMapper().writeValueAsString(jsonNodeTree);
yamlStr = yamlStr.replaceAll("---","").trim();
// 접두사 존재시 추가
if (!isEmpty(suffix)) {
yamlStr = suffix + yamlStr;
}
}
} catch (Exception e) {
yamlStr = "Failure";
}
return yamlStr;
}
public static String convertYAML2JSON(String yamlStr) {
String jsonStr = "";
try {
if (!isEmpty(yamlStr)) {
ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
Object obj = yamlReader.readValue(yamlStr, Object.class);
ObjectMapper jsonWriter = new ObjectMapper();
jsonStr = jsonWriter.writeValueAsString(obj);
}
} catch (Exception e) {
jsonStr = "Failure";
}
return jsonStr;
}
private static String makeYamlFileId(String targetName, String yamlStr) throws IOException {
UUID randomUUID = UUID.randomUUID();
String fileName = CommonFunction.replaceSlashToUnderline(targetName);
String logiFileName = fileName + "_" + randomUUID+".yaml";
String filePath = writepath+"/download/";
FileOutputStream outFile = null;
try {
if (!Files.exists(Paths.get(filePath))) {
Files.createDirectories(Paths.get(filePath));
}
outFile = new FileOutputStream(filePath + logiFileName);
FileUtil.writeFile(filePath, logiFileName, yamlStr);
// db 등록
return fileService.registFileDownload(filePath, fileName + ".yaml", logiFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (Exception e2) {}
}
}
return null;
}
private static List<ProjectIdentification> setMergeData(List<ProjectIdentification> list, String typeCode) {
List<ProjectIdentification> tempData = new ArrayList<ProjectIdentification>();
List<ProjectIdentification> resultGridData = new ArrayList<ProjectIdentification>();
String groupColumn = "";
boolean ossNameEmptyFlag = false;
Collections.sort(list, new Comparator<ProjectIdentification>() {
@Override
public int compare(ProjectIdentification before, ProjectIdentification after) {
String key = makeMergeKey(before, typeCode);
String key2 = makeMergeKey(after, typeCode);
return key.compareTo(key2);
}
});
for (ProjectIdentification info : list) {
if (isEmpty(groupColumn)) {
groupColumn = makeMergeKey(info, typeCode);
}
if ("-".equals(groupColumn)) {
if ("NA".equals(info.getLicenseType())) {
ossNameEmptyFlag = true;
}
}
if (groupColumn.equals(makeMergeKey(info, typeCode)) // 같은 groupColumn이면 데이터를 쌓음
&& !ossNameEmptyFlag) { // 단, OSS Name: - 이면서, License Type: Proprietary이 아닌 경우 Row를 합치지 않음.
tempData.add(info);
} else { // 다른 grouping
setMergeData(tempData, resultGridData);
groupColumn = makeMergeKey(info, typeCode);
tempData.clear();
tempData.add(info);
}
ossNameEmptyFlag = false; // 초기화
}
setMergeData(tempData, resultGridData); // bom data의 loop가 끝났지만 tempData에 값이 있다면 해당 값도 merge를 함.
return resultGridData;
}
public static void setMergeData(List<ProjectIdentification> tempData, List<ProjectIdentification> resultGridData){
if (tempData.size() > 0) {
Collections.sort(tempData, new Comparator<ProjectIdentification>() {
@Override
public int compare(ProjectIdentification o1, ProjectIdentification o2) {
if (o1.getLicenseName().length() >= o2.getLicenseName().length()) { // license name이 같으면 bomList조회해온 순서 그대로 유지함. license name이 다르면 순서변경
return 1;
}else {
return -1;
}
}
});
ProjectIdentification rtnBean = null;
for (ProjectIdentification temp : tempData) {
if (rtnBean == null) {
rtnBean = temp;
continue;
}
String key = temp.getOssName() + "-" + temp.getLicenseType();
if ("--NA".equals(key)) {
if (!rtnBean.getLicenseName().contains(temp.getLicenseName())) {
resultGridData.add(rtnBean);
rtnBean = temp;
continue;
}
}
// 동일한 oss name과 version일 경우 license 정보를 중복제거하여 merge 함.
for (String licenseName : temp.getLicenseName().split(",")) {
boolean equalFlag = false;
for (String rtnLicenseName : rtnBean.getLicenseName().split(",")) {
if (rtnLicenseName.equals(licenseName)) {
equalFlag = true;
break;
}
}
if (!equalFlag) {
rtnBean.setLicenseName(rtnBean.getLicenseName() + "," + licenseName);
}
}
// 3RD Tab, SRC Tab, BIN Tab > Source Name or Path, Binary Name, Binary Name or Source Path, Comment
// BINANDROID Tab > Binary Name, Comment
// SELFCHECK > Binary Name or Source Path
// binaryName > merge & distinct
String binaryNameStr = avoidNull(rtnBean.getBinaryName()) + "\n" + avoidNull(temp.getBinaryName());
rtnBean.setBinaryName(String.join("\n", Arrays.asList(binaryNameStr.split("\n")).stream()
.filter(CommonFunction.distinctByKey(p -> p.trim().toUpperCase()))
.collect(Collectors.toList())));
// filePath > merge & distinct
String filePathStr = avoidNull(rtnBean.getFilePath()) + "\n" + avoidNull(temp.getFilePath());
rtnBean.setFilePath(String.join("\n", Arrays.asList(filePathStr.split("\n")).stream()
.filter(CommonFunction.distinctByKey(p -> p.trim().toUpperCase()))
.collect(Collectors.toList())));
// comment > merge & distinct
String commentsStr = avoidNull(rtnBean.getComments()) + "\n" + avoidNull(temp.getComments());
rtnBean.setComments(String.join("\n", Arrays.asList(commentsStr.split("\n")).stream()
.filter(CommonFunction.distinctByKey(p -> p.trim().toUpperCase()))
.collect(Collectors.toList())));
}
resultGridData.add(rtnBean);
}
}
private static String makeMergeKey(ProjectIdentification bean, String typeCode) {
String mergeKey = "";
// 3RD Tab, SRC Tab, BIN Tab > OSS Name, OSS version, License, Download location, Homepage, Copyright,Exclude 가 동일한 경우 Merge.
// BINANDROID Tab > Source Path, OSS Name, OSS version, License, Download location, Homepage, Copyright, Exclude 가 동일한 경우 Merge.
// SELFCHECK > OSS Name, OSS version, License, Download location, Copyright,Exclude 가 동일한 경우 Merge.
switch(typeCode) {
case CoConstDef.CD_DTL_COMPONENT_PARTNER:
case CoConstDef.CD_DTL_COMPONENT_ID_SRC:
case CoConstDef.CD_DTL_COMPONENT_ID_BIN:
mergeKey = bean.getOssName() + "_" + bean.getOssVersion() + "_" + bean.getLicenseName() + "_" + bean.getDownloadLocation() + "_" + bean.getHomepage() + "_" + bean.getCopyrightText() + "_" + bean.getExcludeYn();
break;
case CoConstDef.CD_DTL_COMPONENT_ID_ANDROID:
mergeKey = bean.getBinaryName() + "_" + bean.getOssName() + "_" + bean.getOssVersion() + "_" + bean.getLicenseName() + "_" + bean.getDownloadLocation() + "_" + bean.getHomepage() + "_" + bean.getCopyrightText() + "_" + bean.getExcludeYn();
break;
default: // selfcheck
mergeKey = bean.getOssName() + "_" + bean.getOssVersion() + "_" + bean.getLicenseName() + "_" + bean.getDownloadLocation() + "_" + bean.getCopyrightText() + "_" + bean.getExcludeYn();
break;
}
return mergeKey;
}
}
| 16,762 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
RequestUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/RequestUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.common.CommonFunction;
@Slf4j
public class RequestUtil {
/**
* Gets the rest template.
*
* @param context the context
* @return the rest template
*/
public static RestTemplate getRestTemplate(final HttpClientContext context) {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(5000); // milliseconds
RestTemplate restOperations = new RestTemplate(factory);
restOperations.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
if (context.getAttribute(HttpClientContext.COOKIE_STORE) == null) {
context.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
Builder builder = RequestConfig.custom()
// .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
// .setAuthenticationEnabled(false)
.setRedirectsEnabled(false);
context.setRequestConfig(builder.build());
}
return context;
}
});
return restOperations;
}
/**
* Gets the headers.
*
* @return the headers
*/
public static HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept-Encoding", "gzip, deflate, sdch");
headers.set("Connection", "keep-alive");
headers.set("Accept-Language", "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
headers.set("Accept", "text/html,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
headers.set("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36");
return headers;
}
/**
* POST 요청.
*
* @param url the url
* @param parts the parts
* @param charset the charset
* @return the string
*/
public static String post(String url, MultiValueMap<String, Object> parts, String charset) {
log.debug("url:{}, param:{}, charset:{}", new Object[] { url, parts, charset });
HttpClientContext context = HttpClientContext.create();
RestTemplate restOperations = RequestUtil.getRestTemplate(context);
restOperations.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(charset)));
HttpHeaders headers = RequestUtil.getHeaders();
ResponseEntity<String> exchange = restOperations.exchange(url, HttpMethod.POST,
new HttpEntity<MultiValueMap<String, Object>>(parts, headers), String.class);
String body = exchange.getBody();
HttpStatus statusCode = exchange.getStatusCode();
if (statusCode != HttpStatus.OK) {
log.warn("%s - status : {}", url, statusCode);
}
return body;
}
/**
* Post.
*
* @param url the url
* @param parts the parts
* @return the string
*/
public static String post(String url, MultiValueMap<String, Object> parts) {
return post(url, parts, "UTF-8");
}
/**
* Gets 요청.
*
* @param url the url
* @return the string
*/
public static String get(String url, String charset) {
HttpClientContext context = HttpClientContext.create();
RestTemplate restOperations = RequestUtil.getRestTemplate(context);
restOperations.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName(charset)));
HttpHeaders headers = RequestUtil.getHeaders();
ResponseEntity<String> exchange = restOperations.exchange(url, HttpMethod.GET, new HttpEntity<Object>(headers),
String.class);
HttpStatus statusCode = exchange.getStatusCode();
if (statusCode != HttpStatus.OK) {
log.warn("{} - status : {}", url, statusCode);
}
return exchange.getBody();
}
/**
* Gets the.
*
* @param url the url
* @param params the params
* @param convertCamelCase the convert camel case
* @return the json object
*/
public static String get(String url, Map<String, Object> params, boolean convertCamelCase) {
return get(url, params, "UTF-8", convertCamelCase, null);
}
/**
* Gets the.
*
* @param url the url
* @param params the params
* @param charSet the char set
* @param convertCamelCase the convert camel case
* @param ignoreParams the ignore params
* @return the json object
*/
public static String get(String url, Map<String, Object> params, String charSet, boolean convertCamelCase, String[] ignoreParams) {
String result = "";
try {
String query = ParameterStringBuilder.getParamsString(params, convertCamelCase, ignoreParams);
result = get(url + (CommonFunction.isEmpty(query) ? "" : "?") + query, charSet);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
}
return result;
}
/**
* URL을 호출한 결과값을 String으로 반환한다.
*
* @param strUrl url of string
* @param body the body
* @param charSet the char set
* @return the URL response to string by post
* @throws Exception the exception
*/
public static String getURLResponseToStringByPost(String strUrl, String body, String charSet) throws Exception {
String result = null;
StringBuffer buff = new StringBuffer();
DataOutputStream out = null;
BufferedReader in = null;
InputStreamReader ins = null;
try {
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(30000);
out = new DataOutputStream(conn.getOutputStream());
out.write(body.getBytes(charSet));
out.flush();
out.close();
ins = new InputStreamReader(conn.getInputStream(), charSet);
in = new BufferedReader(ins);
String read;
while ((read = in.readLine()) != null) {
buff.append(read + "\n");
}
result = buff.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignored) {
throw new Exception(ignored);
}
}
if (ins != null) {
try {
ins.close();
} catch (Exception ignored) {
throw new Exception(ignored);
}
}
}
return result;
}
/**
* The Class ParameterStringBuilder.
*/
public static class ParameterStringBuilder {
/**
* Gets the params string.
*
* @param params the params
* @param convertCamelCase the convert camel case
* @param ignoreParams the ignore params
* @return the params string
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
public static String getParamsString(Map<String, Object> params, boolean convertCamelCase, String[] ignoreParams)
throws UnsupportedEncodingException {
List<String> ignoreParamList = new ArrayList<>();
if (ignoreParams != null) {
for (String s : Arrays.asList(ignoreParams)) {
// 대소문자무시
ignoreParamList.add(s.toUpperCase());
}
}
StringBuilder result = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String _key = entry.getKey();
if (ignoreParamList.contains(_key.toUpperCase())) {
continue;
}
if (entry.getValue() == null) {
continue;
}
if (convertCamelCase) {
_key = StringUtil.convert2CamelCase(_key);
}
result.append(_key);
result.append("=");
result.append((String) entry.getValue());
result.append("&");
}
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
}
/**
* Post.
*
* @param url the url
* @param params the params
* @param ignoreParams the ignore params
* @return the json object
*/
public static String post(String url, Map<String, Object> params, String[] ignoreParams) {
return post(url, params, false, ignoreParams);
}
/**
* Post.
*
* @param url the url
* @param params the params
* @param convertCamalCase the convert camal case
* @param ignoreParams the ignore params
* @return the json object
*/
public static String post(String url, Map<String, Object> params, boolean convertCamalCase, String[] ignoreParams) {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
List<String> ignoreParamList = new ArrayList<>();
if (ignoreParams != null) {
for (String s : Arrays.asList(ignoreParams)) {
ignoreParamList.add(s.toUpperCase());
}
}
if (params != null) {
for (String _k : params.keySet()) {
if (ignoreParamList.contains(_k.toUpperCase())) {
continue;
}
Object _v = params.get(_k);
if (_v == null) {
continue;
}
if (convertCamalCase) {
_k = StringUtil.convert2CamelCase(_k);
}
if (_v instanceof List<?> || _v instanceof String) {
parts.add(_k, _v);
} else if (_v instanceof String[]) {
//2019-06-04 Javaroid 배열로 값을 전송하기 위한 처리. 고객 그룹 등록 등 일괄 처리를 위한 작업 때문에 추가하였다.
String[] _value = (String[])_v;
for (String value : _value) {
parts.add(_k, value);
}
} else {
parts.add(_k, _v + "");
}
}
}
return post(url, parts);
}
public static String simpleGet(String url) throws Exception {
//http client
CloseableHttpClient httpClient = null;
BufferedReader reader = null;
String rtn = "";
try {
httpClient = createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "charset=UTF-8");
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
rtn = response.toString();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (Exception e) {}
}
}
return rtn;
}
private static CloseableHttpClient createDefault() {
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(5000).setSocketTimeout(5000).setConnectTimeout(5000)
.build();
return HttpClients.custom().setDefaultRequestConfig(config).build();
}
}
| 11,955 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CompressUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/CompressUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CompressUtil {
public static void compressGZIP(File input, File output, boolean deleteInputFile) throws IOException {
try (
GzipCompressorOutputStream out = new GzipCompressorOutputStream(new FileOutputStream(output));
) {
IOUtils.copy(new FileInputStream(input), out);
} catch (Exception e){
throw e;
}
if (deleteInputFile) {
try {
input.deleteOnExit();
} catch(Exception e) {
}
}
}
public static void decompressGZIP(File input, File output, boolean deleteInputFile) {
GzipCompressorInputStream zin = null;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(input);
zin = new GzipCompressorInputStream(in);
out = new FileOutputStream(output);
IOUtils.copy(in, out);
if (deleteInputFile) {
try {
input.deleteOnExit();
} catch(Exception e) {
}
}
} catch(Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
if (zin != null) {
try {
zin.close();
} catch (Exception e) {}
}
if (out != null) {
try {
out.close();
} catch (Exception e2) {}
}
}
}
public static void decompressTarGZ(File tarFile, String dest) throws IOException {
File dir = new File(dest);
if (!dir.exists()) {
dir.mkdirs();
}
try (
TarArchiveInputStream tarIn = new TarArchiveInputStream(
new GzipCompressorInputStream(
new BufferedInputStream(
new FileInputStream(tarFile)
)
)
);
) {
TarArchiveEntry tarEntry = tarIn.getNextTarEntry ();
while (tarEntry != null) {
File destPath = new File(dest, tarEntry.getName());
if (tarEntry.isDirectory()) { // tar.gz의 하위 file이 dir일 경우 dir 생성
destPath.mkdirs();
} else { // tar.gz의 하위 file이 dir가 아닐경우 file로 생성
destPath.createNewFile();
byte [] btoRead = new byte[1024];
try (
BufferedOutputStream bout =
new BufferedOutputStream(new FileOutputStream(destPath));
){
int len = 0;
while ((len = tarIn.read(btoRead)) != -1){
bout.write(btoRead,0,len);
}
btoRead = null;
} catch(Exception e) {
throw e;
}
}
tarEntry = tarIn.getNextTarEntry ();
}
} catch (Exception e) {
throw e;
}
}
}
| 3,488 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
OssComponentUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/OssComponentUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.domain.LicenseMaster;
import oss.fosslight.domain.OssComponents;
import oss.fosslight.domain.OssComponentsLicense;
import oss.fosslight.domain.OssLicense;
import oss.fosslight.domain.OssMaster;
public class OssComponentUtil {
private static OssComponentUtil instance;
private boolean USE_AUTOCOMPLETE_LICENSE_TEXT = "true".equalsIgnoreCase(CommonFunction.getProperty("use.autocomplete.licensetext"));
public static OssComponentUtil getInstance () {
if (instance == null) {
instance = new OssComponentUtil();
}
return instance;
}
public void makeOssComponent(List<OssComponents> selectedData) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
makeOssComponent(selectedData, false);
}
public void makeOssComponent(List<OssComponents> selectedData, boolean replaceLikeLicense) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
makeOssComponent(selectedData, replaceLikeLicense, false);
}
public void makeOssComponent(List<OssComponents> selectedData, boolean replaceLikeLicense, boolean replaceDownloadHomepage) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// DB 확인 된 OSS list
List<OssComponents> fillList = new ArrayList<>();
// DB 에 등록되지 않은 oss list
List<OssComponents> newList = new ArrayList<>();
List<String> ossNameList = new ArrayList<>();
// ossName 정보만 취득
for (OssComponents bean : selectedData) {
if (!StringUtil.isEmpty(bean.getOssName()) && !ossNameList.contains(bean.getOssName())) {
ossNameList.add(bean.getOssName());
}
}
// Oss Master 정보 취득
OssMaster param = new OssMaster();
String[] ossNames = new String[ossNameList.size()];
param.setOssNames(ossNameList.toArray(ossNames));
Map<String, OssMaster> regData = CoCodeManager.OSS_INFO_UPPER;
Map<String, String> ossNameInfo = CoCodeManager.OSS_INFO_UPPER_NAMES;
// DB 정보를 기준으로 Merge
for (OssComponents bean : selectedData) {
String key = (bean.getOssName() + "_" + StringUtil.nvl(bean.getOssVersion())).toUpperCase();
// 분석결과서 업로드시 OSS VERSION을 N/A로 사용자가 지정한 경우, OSS VERSION이 공백인 OSS가 존재함에도 불구하고, 다른 OSS로 인식하여 멀티라이선스로 적용되지 않는 현상
// N/A인 경우 공백이 VERSION이 존재하는지 체크하고 존해할 경우 자동 치환한다.
if ("AWS IoT Device SDK for C".equals(bean.getOssName())) {
System.out.println();
}
if (regData.containsKey(key)) {
// 사용자가 입력한 oss 가 db에 존재한다면
// DB + 입력정보
fillList.addAll(mergeOssAndLicense(regData.get(key), bean, replaceDownloadHomepage));
} else if ("N/A".equalsIgnoreCase(bean.getOssVersion()) && regData.containsKey((bean.getOssName() + "_").toUpperCase())) {
bean.setOssVersion("");
fillList.addAll(mergeOssAndLicense(regData.get((bean.getOssName() + "_").toUpperCase()), bean, replaceDownloadHomepage));
} else {
// DB에서 확인되지 않은 OSS
// 라이선스별로 row 등록
for (OssComponentsLicense userLicense : bean.getOssComponentsLicense()) {
List<OssComponentsLicense> _list = new ArrayList<>();
_list.add(fillLicenseInfo(userLicense));
OssComponents newBean = (OssComponents) BeanUtils.cloneBean(bean);
newBean.setOssComponentsLicense(_list);
newList.add(newBean);
}
}
}
if (!newList.isEmpty()) {
fillList.addAll(newList);
}
if (!fillList.isEmpty()) {
selectedData.clear();
selectedData.addAll(fillList);
}
}
private List<OssComponents> mergeOssAndLicense(OssMaster master, OssComponents ossComponent, boolean replaceDownloadHomepage) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// 1. OSS Master를 기준으로 Merge 한다.
// 사용자가 입력한 라이선스가 oss 에 포함되어 있지 않을 경우
// oss 가 multi or dual 라이선스인 경우는 해당 oss의 subgrid 하단에 추가
// oss 가 single 라이선스인 경우는 해당 master 정보를 사용하지 않는다.
List<OssComponents> list = new ArrayList<>();
setOssBasicInfo(ossComponent, master, replaceDownloadHomepage);
// 멀티라이선스인 경우
if (CoConstDef.LICENSE_DIV_MULTI.equals(master.getLicenseDiv())) {
mergeOssLicenseInfo(ossComponent, master);
list.add(ossComponent);
} else if (CoConstDef.LICENSE_DIV_SINGLE.equals(master.getLicenseDiv()) && ossComponent.getOssComponentsLicense() != null && ossComponent.getOssComponentsLicense().size() > 1) {
// 싱글로 등록되어 있는 oss인데, 라이선스를 복수개 등록한 경우 별개의 row로 분할
// 사용자가 입력한 라이선스별로 별도의 row로 구성
for (OssComponentsLicense comLicense : ossComponent.getOssComponentsLicense()) {
OssComponents newBean = (OssComponents) BeanUtils.cloneBean(ossComponent);
newBean.setOssComponentsLicense(null);
newBean.addOssComponentsLicense(comLicense);
mergeOssLicenseInfo(newBean, master);
list.add(newBean);
}
} else { // 싱글라이선스인 경우
mergeOssLicenseInfo(ossComponent, master);
list.add(ossComponent);
}
return list;
}
private void setOssBasicInfo(OssComponents ossComponent, OssMaster master, boolean replaceDownloadHomepage) {
if (StringUtil.isEmpty(ossComponent.getOssId())) {
ossComponent.setOssId(master.getOssId());
}
if (!replaceDownloadHomepage) {
if (StringUtil.isEmpty(ossComponent.getDownloadLocation())) {
ossComponent.setDownloadLocation(master.getDownloadLocation());
}
if (StringUtil.isEmpty(ossComponent.getHomepage())) {
ossComponent.setHomepage(master.getHomepage());
}
if (StringUtil.isEmpty(ossComponent.getCopyrightText())) {
ossComponent.setCopyrightText(master.getCopyright());
}
}
// AND OR 연산표현식으로 변경
ossComponent.setLicenseName(CommonFunction.makeLicenseExpression(master.getOssLicenses()));
}
private void mergeOssLicenseInfo(OssComponents ossComponent, OssMaster master) {
// 2. oss license merge
List<OssComponentsLicense> subList = new ArrayList<>();
List<String> selectedLicenseList = new ArrayList<>();
if (CoConstDef.LICENSE_DIV_MULTI.equals(master.getLicenseDiv())) {
for (OssLicense subBean : master.getOssLicenses()) {
OssComponentsLicense componentLicenseBean = findOssLicense(subBean, ossComponent);
// 등록되어있는 license인 경우
if (componentLicenseBean != null && !selectedLicenseList.contains(componentLicenseBean.getLicenseId())) {
selectedLicenseList.add(componentLicenseBean.getLicenseId());
componentLicenseBean.setExcludeYn(CoConstDef.FLAG_NO);
} else {
componentLicenseBean = new OssComponentsLicense();
// full name -> short Identification
componentLicenseBean.setLicenseName(CommonFunction.getShortIdentify(subBean.getLicenseName()));
componentLicenseBean.setExcludeYn(CoConstDef.FLAG_YES);
}
componentLicenseBean.setLicenseId(subBean.getLicenseId());
componentLicenseBean.setLicensetype(subBean.getLicenseType());
componentLicenseBean.setOssLicenseComb(subBean.getOssLicenseComb());
if (USE_AUTOCOMPLETE_LICENSE_TEXT && StringUtil.isEmpty(componentLicenseBean.getLicenseText())) {
componentLicenseBean.setLicenseText(subBean.getOssLicenseText());
}
if (StringUtil.isEmpty(componentLicenseBean.getCopyrightText())) {
componentLicenseBean.setCopyrightText(subBean.getOssCopyright());
}
subList.add(componentLicenseBean);
}
// DB에 등록되지 않은 라이선스가 포함된 경우 마지막 row로 추가
subList.addAll(getCustomLicense(master, ossComponent));
} else {
OssComponentsLicense componentLicenseBean = findOssLicense(master.getOssLicenses().get(0), ossComponent);
// 등록되어있는 license인 경우
if (componentLicenseBean != null && !selectedLicenseList.contains(componentLicenseBean.getLicenseId())) {
selectedLicenseList.add(componentLicenseBean.getLicenseId());
// DB에 등록되지 않은 라이선스가 포함된 경우 마지막 row로 추가
subList.add(fillLicenseInfo(componentLicenseBean));
} else {
// ossmaster DB에 등록되지 않은 라이선스가 포함된 경우 마지막 row로 추가
subList.addAll(getCustomLicense(master, ossComponent));
}
}
// permissve 기준에 따라 exclude 처리
excludedLicense(selectedLicenseList, subList);
ossComponent.setOssComponentsLicense(subList);
}
private OssComponentsLicense fillLicenseInfo(OssComponentsLicense componentLicenseBean) {
if (CoCodeManager.LICENSE_INFO.containsKey(componentLicenseBean.getLicenseName())) {
LicenseMaster license = CoCodeManager.LICENSE_INFO.get(componentLicenseBean.getLicenseName());
if (StringUtil.isEmpty(componentLicenseBean.getLicenseId())) {
componentLicenseBean.setLicenseId(license.getLicenseId());
}
if (USE_AUTOCOMPLETE_LICENSE_TEXT && StringUtil.isEmpty(componentLicenseBean.getLicenseText())) {
componentLicenseBean.setLicenseText(license.getLicenseText());
}
}
return componentLicenseBean;
}
private List<OssComponentsLicense> getCustomLicense(OssMaster master, OssComponents ossComponent) {
// DB에 등록되지 않은 customer가 입력한 라이선스가 있을 경우, 해당 OSS의 마지막 row로 추가
List<OssComponentsLicense> returnList = new ArrayList<>();
List<String> ossMasterLicenseIdList = new ArrayList<>();
for (OssLicense liBean : master.getOssLicenses()) {
ossMasterLicenseIdList.add(liBean.getLicenseId());
}
for (OssComponentsLicense bean : ossComponent.getOssComponentsLicense()) {
boolean addflag = true;
// 닉네임, short identify 모두 비교
if (CoCodeManager.LICENSE_INFO.containsKey(bean.getLicenseName())) {
String selectedLicenseId = CoCodeManager.LICENSE_INFO.get(bean.getLicenseName()).getLicenseId();
if (ossMasterLicenseIdList.contains(selectedLicenseId)) {
addflag = false;
}
} else {
// 미등록 라이선스
}
if (addflag && !StringUtil.isEmpty(bean.getLicenseName())) {
bean.setEditable(CoConstDef.FLAG_YES);
returnList.add(fillLicenseInfo(bean));
}
}
return returnList;
}
private OssComponentsLicense findOssLicense(OssLicense dbData, OssComponents userDataList) {
for (OssComponentsLicense bean : userDataList.getOssComponentsLicense()) {
String selectedLicenseId = "";
// 대소문자 구분으로 인한 문제로, 만약 일치하는 라이선스가 있을 경우
// 사용자 입력 라이선스 명을 DB 명으로 변경한다.
String inputLicenseName = bean.getLicenseName().trim();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(inputLicenseName.toUpperCase())) {
bean.setLicenseName(CoCodeManager.LICENSE_INFO_UPPER.get(inputLicenseName.toUpperCase()).getLicenseName());
}
// 확인 가능한 라이선스 이면
if (CoCodeManager.LICENSE_INFO.containsKey(bean.getLicenseName())) {
LicenseMaster licenseMaster = CoCodeManager.LICENSE_INFO.get(bean.getLicenseName());
List<String> compareList = new ArrayList<>();
compareList.add(licenseMaster.getLicenseName());
if (!StringUtil.isEmpty(licenseMaster.getShortIdentifier())) {
compareList.add(licenseMaster.getShortIdentifier());
}
if (licenseMaster.getLicenseNicknameList() != null && !licenseMaster.getLicenseNicknameList().isEmpty()) {
compareList.addAll(licenseMaster.getLicenseNicknameList());
}
if (compareList.contains(bean.getLicenseName())) {
selectedLicenseId = licenseMaster.getLicenseId();
}
}
// 라이선스가 라이선스 마스터에 등록되어 있어야하고, oss에 포함되는 라이선스이어야만 반환
if (selectedLicenseId.equals(dbData.getLicenseId())) {
bean.setLicenseId(dbData.getLicenseId());
return bean;
}
}
return null;
}
private void excludedLicense(List<String> selectedLicenseList, List<OssComponentsLicense> allList) {
// 1. 사용자가 선택 입력한 라이선스를 제외하고 모두 exclude 처리
boolean isfirst = true;
List<String> isSelectedDuplicatedLicenseCheckList = new ArrayList<>();
for (OssComponentsLicense bean : allList) {
boolean onSelected = CoConstDef.FLAG_YES.equals(bean.getEditable()) || selectedLicenseList.contains(bean.getLicenseId());
// license id가 없다는 것은 사용자가 등록되지 않은 라이선스를 입력한 경우 => license master에 존재하는 경우 license id를 설정하기 때문에, Editable flag로 판단한다.
// 복수개의 라이선스가 설정되어 있고(OSS는 DB에 존재한다는 뜻), 처음이 아닌경우 OR 조건으로 추가한다.
if ( CoConstDef.FLAG_YES.equals(bean.getEditable())) {
if (!isfirst && StringUtil.isEmpty(bean.getOssLicenseComb())) {
bean.setOssLicenseComb("OR");
}
}
if (!onSelected || isSelectedDuplicatedLicenseCheckList.contains(bean.getLicenseId()) || CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
bean.setExcludeYn(CoConstDef.FLAG_YES);
} else {
if (null != bean.getLicenseId()) {
isSelectedDuplicatedLicenseCheckList.add(bean.getLicenseId());
}
bean.setExcludeYn(CoConstDef.FLAG_NO);
}
isfirst = false;
}
}
}
| 14,442 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
TlshUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/TlshUtil.java | package oss.fosslight.util;
import com.trendmicro.tlsh.Tlsh;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TlshUtil {
public static int compareTlshDistance(String tlsh1, String tlsh2) {
try {
Tlsh tlshTest1 = Tlsh.fromTlshStr(tlsh1);
Tlsh tlshTest2 = Tlsh.fromTlshStr(tlsh2);
return tlshTest1.totalDiff(tlshTest2, true);
} catch (IllegalArgumentException iae) {
// 임시로 illegalArgumentException이 발생을 하면 비교를 실패한 것으로 간주하고 -1을 리턴하도록 변경함.
// 추후 tlsh 4.5.0 version에서 처리가 가능할 경우 재검토 필요함.
// Tlsh tlshTest1 = getTlsh(tlsh1);
// Tlsh tlshTest2 = getTlsh(tlsh2);
//
// return tlshTest1.totalDiff(tlshTest2, true);
log.error(iae.getMessage(), iae);
return -1;
}
}
} | 805 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
SPDXUtil2.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/SPDXUtil2.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.File;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spdx.tools.SpdxConverter;
public class SPDXUtil2 {
static final Logger logger = LoggerFactory.getLogger("DEFAULT_LOG");
public static void convert(String prjId, String inputFilePath, String outputFilePath) throws Exception {
// 기존 파일 변환 결과 파일이 존재하는 경우 삭제
File inputFile = Paths.get(outputFilePath).toFile();
inputFile.deleteOnExit();
logger.debug("SPDX format convert ("+prjId+") :" + inputFilePath + " => " + outputFilePath);
try {
SpdxConverter.convert(inputFilePath, outputFilePath);
} catch (Exception e) {
logger.warn(e.getMessage(), e);
throw e;
}
}
}
| 896 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CsvUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/CsvUtil.java | /*
* Copyright (c) 2021 Dongmin Kang
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import oss.fosslight.CoTopComponent;
import oss.fosslight.config.AppConstBean;
import oss.fosslight.service.FileService;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@PropertySources(value = {@PropertySource(value= AppConstBean.APP_CONFIG_PROPERTIES_PATH)})
public class CsvUtil extends CoTopComponent {
// Service
private static FileService fileService = (FileService) getWebappContext().getBean(FileService.class);
public static Workbook csvFileToExcelWorkbook(File file, String readType) throws IOException{
CSVParser parser = new CSVParserBuilder()
.withSeparator('\t')
.build();
CSVReader csvReader = new CSVReaderBuilder(new FileReader(file))
.withCSVParser(parser)
.build();
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(readType);
int rowIdx = 0;
String [] nextLine;
while ((nextLine = csvReader.readNext()) != null) {
int cellIdx = 0;
Row row = sheet.createRow(rowIdx);
for (String token : nextLine) {
Cell cell = row.createCell(cellIdx); cellIdx++;
cell.setCellValue(token);
}
rowIdx++;
}
return wb;
}
}
| 1,729 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ExcelDownLoadUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/ExcelDownLoadUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.SheetVisibility;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.cyclonedx.BomGeneratorFactory;
import org.cyclonedx.CycloneDxSchema;
import org.cyclonedx.exception.GeneratorException;
import org.cyclonedx.model.Bom;
import org.cyclonedx.model.Component;
import org.cyclonedx.model.Dependency;
import org.cyclonedx.model.ExternalReference;
import org.cyclonedx.model.License;
import org.cyclonedx.model.LicenseChoice;
import org.cyclonedx.model.Metadata;
import org.cyclonedx.model.OrganizationalContact;
import org.cyclonedx.model.OrganizationalEntity;
import org.cyclonedx.model.Tool;
import org.cyclonedx.model.vulnerability.Vulnerability.Source;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.opencsv.CSVWriter;
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.config.AppConstBean;
import oss.fosslight.controller.ProjectController;
import oss.fosslight.domain.BinaryAnalysisResult;
import oss.fosslight.domain.LicenseMaster;
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.OssNotice;
import oss.fosslight.domain.PartnerMaster;
import oss.fosslight.domain.Project;
import oss.fosslight.domain.ProjectIdentification;
import oss.fosslight.domain.Statistics;
import oss.fosslight.domain.T2Users;
import oss.fosslight.domain.Vulnerability;
import oss.fosslight.repository.OssMapper;
import oss.fosslight.repository.ProjectMapper;
import oss.fosslight.repository.SelfCheckMapper;
import oss.fosslight.service.BinaryDataHistoryService;
import oss.fosslight.service.ComplianceService;
import oss.fosslight.service.FileService;
import oss.fosslight.service.LicenseService;
import oss.fosslight.service.OssService;
import oss.fosslight.service.PartnerService;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.SelfCheckService;
import oss.fosslight.service.StatisticsService;
import oss.fosslight.service.T2UserService;
import oss.fosslight.service.VerificationService;
import oss.fosslight.service.VulnerabilityService;
import oss.fosslight.validation.T2CoValidationResult;
import oss.fosslight.validation.custom.T2CoProjectValidator;
import org.spdx.library.SpdxVerificationHelper;
@PropertySources(value = {@PropertySource(value=AppConstBean.APP_CONFIG_PROPERTIES_PATH)})
@Slf4j
public class ExcelDownLoadUtil extends CoTopComponent {
private static String downloadpath = "";
private static String writepath = CommonFunction.emptyCheckProperty("export.template.path", "/template");
// Service
private static PartnerService partnerService = (PartnerService) getWebappContext().getBean(PartnerService.class);
private static LicenseService licenseService = (LicenseService) getWebappContext().getBean(LicenseService.class);
private static ProjectService projectService = (ProjectService) getWebappContext().getBean(ProjectService.class);
private static T2UserService userService = (T2UserService) getWebappContext().getBean(T2UserService.class);
private static OssService ossService = (OssService) getWebappContext().getBean(OssService.class);
private static FileService fileService = (FileService) getWebappContext().getBean(FileService.class);
private static SelfCheckService selfCheckService = (SelfCheckService) getWebappContext().getBean(SelfCheckService.class);
private static VerificationService verificationService = (VerificationService) getWebappContext().getBean(VerificationService.class);
private static BinaryDataHistoryService binaryDataHistoryService = (BinaryDataHistoryService) getWebappContext().getBean(BinaryDataHistoryService.class);
private static VulnerabilityService vulnerabilityService = (VulnerabilityService) getWebappContext().getBean(VulnerabilityService.class);
private static ComplianceService complianceService = (ComplianceService) getWebappContext().getBean(ComplianceService.class);
private static StatisticsService statisticsService = (StatisticsService) getWebappContext().getBean(StatisticsService.class);
private static ProjectService prjService = (ProjectService) getWebappContext().getBean(ProjectService.class);
// Mapper
private static ProjectMapper projectMapper = (ProjectMapper) getWebappContext().getBean(ProjectMapper.class);
private static OssMapper ossMapper = (OssMapper) getWebappContext().getBean(OssMapper.class);
private static SelfCheckMapper selfCheckMapper = (SelfCheckMapper) getWebappContext().getBean(SelfCheckMapper.class);
// Controller
private static ProjectController projectController = (ProjectController) getWebappContext().getBean(ProjectController.class);
private static final int MAX_RECORD_CNT = 99999;
private static final int MAX_RECORD_CNT_LIST = Integer.parseInt(CoCodeManager.getCodeExpString(CoConstDef.CD_EXCEL_DOWNLOAD, CoConstDef.CD_MAX_ROW_COUNT))+1;
private static String getReportExcelPost (String prjId, String type) throws IOException, InvalidFormatException {
Workbook wb = null;
Sheet sheet1 = null;
FileInputStream inFile=null;
// download file name
String downloadFileName = "fosslight_report"; // Default
try {
//cover
// Android Model의 Report에만 vulnerability score를 추가 표시하기 위해 type이 null인 경우 Android model 여부를 사전에 확인할 필요가 있음
Project projectInfo = new Project();
projectInfo.setPrjId(prjId);
projectInfo = projectService.getProjectDetail(projectInfo);
if (isEmpty(type) && CoConstDef.FLAG_YES.equals(projectInfo.getAndroidFlag())) {
type = CoConstDef.CD_DTL_COMPONENT_ID_ANDROID;
}
inFile= new FileInputStream(new File(downloadpath+"/ProjectReport.xlsx"));
wb = WorkbookFactory.create(inFile);
{
if (!isEmpty(projectInfo.getNoticeTypeEtc())) {
wb.setSheetName(6, "BIN (" + CoCodeManager.getCodeString(CoConstDef.CD_PLATFORM_GENERATED, projectInfo.getNoticeTypeEtc()) + ")");
}
sheet1 = wb.getSheetAt(0);
reportSheet(wb, sheet1, projectInfo);
}
//fosslight_report_[date]_prj-[ID].xlsx
downloadFileName += "_" + CommonFunction.getCurrentDateTime() + "_prj-" + StringUtil.deleteWhitespaceWithSpecialChar(prjId);
ProjectIdentification ossListParam = new ProjectIdentification();
ossListParam.setReferenceId(prjId);
//3rdparty
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_PARTNER.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER, wb.getSheetAt(2), projectService.getIdentificationGridList(ossListParam), projectInfo);
}
//dep
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_DEP.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_DEP, wb.getSheetAt(3), projectService.getIdentificationGridList(ossListParam), projectInfo);
}
//src
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_SRC.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_SRC);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_SRC, wb.getSheetAt(4), projectService.getIdentificationGridList(ossListParam), projectInfo);
}
//BIN
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BIN);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_BIN, wb.getSheetAt(5), projectService.getIdentificationGridList(ossListParam), projectInfo);
}
//BIN(ANDROID)
if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_ANDROID, wb.getSheetAt(6), projectService.getIdentificationGridList(ossListParam), projectInfo);
}
//bom
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_BOM);
ossListParam.setMerge(CoConstDef.FLAG_NO);
Map<String, Object> map = projectService.getIdentificationGridList(ossListParam);
map.replace("rows", projectService.setMergeGridData((List<ProjectIdentification>) map.get("rows")));
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_BOM, wb.getSheetAt(7), map, projectInfo);
}
// model
// OSS Report를 출력을 시작한 대상이 BOM Tab, platform generated인 경우에 대해서는 Model Info를 출력하도록 수정.
if (isEmpty(type) || CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type)) {
Map<String, List<Project>> modelMap = projectService.getModelList(prjId);
if (modelMap != null) {
List<Project> modelList = modelMap.get("rows");
if (modelList != null && !modelList.isEmpty()) {
reportProjectModelSheet(sheet1, wb.getSheetAt(1), modelList, projectInfo);
}
}
}
wb.setSheetVisibility(8, SheetVisibility.VERY_HIDDEN);
} catch(Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName);
}
private static void reportProjectModelSheet(Sheet coverSheet, Sheet modelSheet, List<Project> modelList, Project projectInfo) {
List<String[]> rows = new ArrayList<>();
int modelCnt = 1;
for (Project bean : modelList) {
List<String> params = new ArrayList<>();
params.add(String.valueOf(modelCnt++));
params.add(bean.getModelName()); // model name
params.add(CommonFunction.makeCategoryFormat(projectInfo.getDistributeTarget(), bean.getCategory())); // category name
params.add(CommonFunction.formatDateSimple(bean.getReleaseDate()));
rows.add(params.toArray(new String[params.size()]));
}
makeSheet(modelSheet, rows, 2);
}
private static void reportIdentificationSheet(String type, Sheet sheet, Map<String, Object> listMap, Project projectInfo) {
reportIdentificationSheet(type, sheet, listMap, projectInfo, false);
}
/**
* 분석결과서 Export 처리
* 화면(초길표시)와 동일하게 정렬하기 위해서 validation을 수행한다.
* @param type
* @param sheet
* @param listMap
* @param projectInfo
* @param isSelfCheck
*/
@SuppressWarnings("unchecked")
private static void reportIdentificationSheet(String type, Sheet sheet, Map<String, Object> listMap, Project projectInfo, boolean isSelfCheck) {
List<ProjectIdentification> list = null;
if (listMap != null && (listMap.containsKey("mainData") || listMap.containsKey("rows") )) {
list = (List<ProjectIdentification>) listMap.get(listMap.containsKey("mainData") ? "mainData" : "rows");
List<String[]> rows = new ArrayList<>();
//Excell export sort
T2CoProjectValidator pv = new T2CoProjectValidator();
if (!CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
pv.setAppendix("mainList", list);
if (CoConstDef.CD_DTL_COMPONENT_ID_SRC.equals(type) || CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_SOURCE);
if (CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BIN);
}
pv.setAppendix("projectId", avoidNull(projectInfo.getPrjId()));
// sub grid
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) listMap.get("subData"));
} else if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_ANDROID);
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) listMap.get("subData"));
Project prjInfo = projectService.getProjectBasicInfo(projectInfo.getPrjId());
List<String> noticeBinaryList = null;
List<String> existsBinaryName = null;
if (prjInfo != null) {
if (!isEmpty(prjInfo.getSrcAndroidNoticeFileId())) {
noticeBinaryList = CommonFunction.getNoticeBinaryList(
fileService.selectFileInfoById(prjInfo.getSrcAndroidNoticeFileId()));
}
if (!isEmpty(prjInfo.getSrcAndroidResultFileId())) {
existsBinaryName = CommonFunction.getExistsBinaryNames(
fileService.selectFileInfoById(prjInfo.getSrcAndroidResultFileId()));
}
}
if (noticeBinaryList != null) {
pv.setAppendix("noticeBinaryList", noticeBinaryList);
}
if (existsBinaryName != null) {
pv.setAppendix("existsResultBinaryName", existsBinaryName);
}
} else if ((CoConstDef.CD_DTL_COMPONENT_ID_BAT.equals(type) || CoConstDef.CD_DTL_COMPONENT_BAT.equals(type))) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BAT);
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) listMap.get("subData"));
} else if (CoConstDef.CD_DTL_COMPONENT_PARTNER.equals(type)) {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_PARTNER);
pv.setAppendix("subListMap", (Map<String, List<ProjectIdentification>>) listMap.get("subData"));
}
} else {
pv.setProcType(pv.PROC_TYPE_IDENTIFICATION_BOM_MERGE);
pv.setAppendix("bomList", list);
}
T2CoValidationResult vr = pv.validate(new HashMap<>());
list = (List<ProjectIdentification>) CommonFunction.identificationSortByValidInfo(list, vr.getValidMessageMap(), vr.getDiffMessageMap(), vr.getInfoMessageMap(), false);
// exclude 된 라이선스는 제외한다. (bom은 제외되어 있음)
for (ProjectIdentification bean : list) {
if (bean.getComponentLicenseList() != null && !bean.getComponentLicenseList().isEmpty()) {
List<ProjectIdentification> newLicenseList = new ArrayList<>();
for (ProjectIdentification licenseBean : bean.getComponentLicenseList()) {
if (!CoConstDef.FLAG_YES.equals(licenseBean.getExcludeYn())) {
newLicenseList.add(licenseBean);
}
}
bean.setComponentLicenseList(newLicenseList);
}
}
// self check인 경우 oss_id가 있는 경우, 부가 정보를 추가해서 export한다.
if (isSelfCheck) {
Map<String, OssMaster> regOssInfoMapWithOssId = null;
OssMaster _ossParam = new OssMaster();
for (ProjectIdentification bean : list) {
if (!isEmpty(bean.getOssId())) {
_ossParam.addOssIdList(bean.getOssId());
}
}
if (_ossParam.getOssIdList() != null && !_ossParam.getOssIdList().isEmpty()) {
regOssInfoMapWithOssId = ossService.getBasicOssInfoListById(_ossParam);
}
}
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
list.sort(Comparator.comparing(ProjectIdentification::getGroupingColumn));
}
String currentGroupKey = null;
for (ProjectIdentification bean : list) {
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
if (currentGroupKey != null && currentGroupKey.equals(bean.getGroupingColumn())) {
for (String[] editRow : rows) {
if (!isEmpty(bean.getOssName()) && !bean.getOssName().equals("-")
&& editRow[1].equals(bean.getOssName()) && editRow[2].equals(bean.getOssVersion())) {
String referenceDiv = editRow[8];
String referenceDivChk = bean.getRefDiv();
if (!isEmpty(referenceDivChk)) {
switch (avoidNull(referenceDivChk)) {
case CoConstDef.CD_DTL_COMPONENT_ID_PARTNER:
referenceDivChk = "3rd";
break;
case CoConstDef.CD_DTL_COMPONENT_ID_DEP:
referenceDivChk = "DEP";
break;
case CoConstDef.CD_DTL_COMPONENT_ID_SRC:
referenceDivChk = "SRC";
break;
case CoConstDef.CD_DTL_COMPONENT_ID_BIN:
referenceDivChk = "BIN";
break;
default:
break;
}
if (!referenceDiv.contains(referenceDivChk)) {
referenceDiv = referenceDiv + "," + referenceDivChk;
editRow[8] = referenceDiv;
break;
}
}
}
}
continue;
} else {
currentGroupKey = bean.getGroupingColumn();
}
}
// bom의 경우
if (bean.getOssComponentsLicenseList() != null && !bean.getOssComponentsLicenseList().isEmpty()) {
boolean isMainRow = true;
List<String> params = new ArrayList<>();
// main 정보
params.add(isMainRow ? ( CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type) ? bean.getRefComponentIdx() : bean.getComponentIdx() ) : "");
params.add(bean.getOssName()); // OSS Name
params.add(bean.getOssVersion()); // OSS Version
params.add(bean.getLicenseName()); // LICENSE
params.add(isMainRow ? bean.getDownloadLocation() : ""); // download url
params.add(isMainRow ? bean.getHomepage() : ""); // home page url
params.add(isMainRow ? bean.getCopyrightText() : "");
String licenseTextUrl = "";
for (String licenseName : bean.getLicenseName().split(",")) {
String licenseUrl = CommonFunction.getLicenseUrlByName(licenseName.trim());
if (isEmpty(licenseUrl)) {
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
licenseUrl = CommonFunction.makeLicenseInternalUrl(CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(licenseName).toUpperCase()), distributionFlag);
}
if (!isEmpty(licenseUrl)) {
if (!isEmpty(licenseTextUrl)) {
licenseTextUrl += ", ";
}
licenseTextUrl += licenseUrl;
}
}
params.add(licenseTextUrl); //license text => license homepage
String refSrcTab = "";
String thirdKey = "3rd";
String[] refDivs = bean.getRefDiv().split("[,]");
for (String refDiv : refDivs) {
switch (avoidNull(refDiv)) {
case CoConstDef.CD_DTL_COMPONENT_ID_PARTNER:
if (!isEmpty(refSrcTab)) refSrcTab += ",";
refSrcTab += thirdKey;
break;
case CoConstDef.CD_DTL_COMPONENT_ID_DEP:
if (!isEmpty(refSrcTab)) refSrcTab += ",";
refSrcTab += "DEP";
break;
case CoConstDef.CD_DTL_COMPONENT_ID_SRC:
if (!isEmpty(refSrcTab)) refSrcTab += ",";
refSrcTab += "SRC";
break;
case CoConstDef.CD_DTL_COMPONENT_ID_BIN:
if (!isEmpty(refSrcTab)) refSrcTab += ",";
refSrcTab += "BIN";
break;
default:
break;
}
}
if (refSrcTab.contains(thirdKey)) {
String[] thirdIds = avoidNull(bean.getRefPartnerId(), "").split(",");
List<String> thirdNames = new ArrayList<String>();
for (String thirdId : thirdIds) {
String thirdPartyName = projectService.getPartnerFormatName(thirdId, true);
if (!isEmpty(thirdPartyName) && !thirdNames.contains(thirdKey + "-" + thirdPartyName)) {
thirdNames.add(thirdKey + "-" + thirdPartyName);
}
}
if (thirdNames.size() > 0) {
String thirdName = String.join(",", thirdNames);
refSrcTab = refSrcTab.replace(thirdKey, thirdName);
}
}
// from
params.add(isMainRow ? refSrcTab : "");
// main 정보 (license 정보 후처리)
// params.add(isMainRow ? bean.getFilePath() : ""); // path
// vulnerability
params.add(isMainRow ? (new BigDecimal(avoidNull(bean.getCvssScore(), "0.0")).equals(new BigDecimal("0.0")) ? "" : bean.getCvssScore()) : "");
// dependencies
// params.add(isMainRow ? (isEmpty(bean.getDependencies()) ? "" : bean.getDependencies()) : "");
// notice
params.add(isMainRow ? ( (CoConstDef.CD_DTL_OBLIGATION_NOTICE.equals(bean.getObligationType()) || CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : "") : "");
// source code
params.add(isMainRow ? ( (CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : "") : "");
// Restriction
params.add(isMainRow ? (isEmpty(bean.getRestriction()) ? "" : bean.getRestriction()) : "");
addColumnWarningMessage(type, bean, vr, params);
rows.add(params.toArray(new String[params.size()]));
} else {
// exclude 제외
if ((CoConstDef.CD_DTL_COMPONENT_ID_PARTNER.equals(type) && CoConstDef.FLAG_YES.equals(bean.getExcludeYn()))) {
continue;
}
List<String> params = new ArrayList<>();
// main 정보
//params.add(isSelfCheck ? bean.getComponentIdx() : bean.getComponentId()); //ID
params.add(isSelfCheck ? bean.getComponentIdx() : bean.getComponentIdx());
// TODO 3rd party 이름 가져올 수 있나?
if (CoConstDef.CD_DTL_COMPONENT_ID_PARTNER.equals(type)) {
params.add(projectService.getPartnerFormatName(bean.getRefPartnerId(), false)); //3rd Party
}
if (CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type) ) {
params.add(bean.getBinaryName()); // Binary Name
}
if (!CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)) {
params.add(bean.getFilePath()); // path
}
if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type)) {
params.add(bean.getBinaryNotice()); // notice
}
params.add(bean.getOssName()); // OSS Name
params.add(bean.getOssVersion()); // OSS Version
String licenseNameList = "";
if (bean.getComponentLicenseList() != null) {
for ( ProjectIdentification project : bean.getComponentLicenseList()) {
if (!isEmpty(licenseNameList)) {
licenseNameList += ",";
}
LicenseMaster lm = CoCodeManager.LICENSE_INFO_UPPER.get(project.getLicenseName().toUpperCase());
if (lm != null) {
licenseNameList += (!isEmpty(lm.getShortIdentifier()) ? lm.getShortIdentifier() : lm.getLicenseName());
}else {
licenseNameList += project.getLicenseName();
}
}
}
params.add(licenseNameList); // license
params.add(bean.getDownloadLocation()); // download url
params.add(bean.getHomepage()); // home page url
params.add(bean.getCopyrightText());
if (!(CoConstDef.CD_DTL_COMPONENT_ID_PARTNER.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_DEP.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_SRC.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type))
|| isSelfCheck) {
String licenseTextUrl = "";
for (String licenseName : licenseNameList.split(",")) {
String licenseUrl = CommonFunction.getLicenseUrlByName(licenseName.trim());
if (isEmpty(licenseUrl)) {
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
licenseUrl = CommonFunction.makeLicenseInternalUrl(CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(licenseName).toUpperCase()), distributionFlag);
}
if (!isEmpty(licenseUrl)) {
if (!isEmpty(licenseTextUrl)) {
licenseTextUrl += ", ";
}
licenseTextUrl += licenseUrl;
}
}
params.add(licenseTextUrl);
}
if (CoConstDef.CD_DTL_COMPONENT_PARTNER.equals(type)) {
// params.add(""); // check list > Modified or not
params.add((new BigDecimal(avoidNull(bean.getCvssScore(), "0.0")).equals(new BigDecimal("0.0")) ? "" : bean.getCvssScore())); // Vuln
}
if (!CoConstDef.CD_DTL_COMPONENT_ID_PARTNER.equals(type) && !isSelfCheck) { // selfcheck에서는 출력하지 않음.
if ( CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
params.add("Exclude");
} else {
params.add("");
}
}
// Comment
String _comm = "";
if (!isSelfCheck
&& (CoConstDef.CD_DTL_COMPONENT_ID_DEP.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_SRC.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_BIN.equals(type)
|| CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type))) {
_comm = avoidNull(bean.getComments().trim());
params.add(_comm);
}
// Vulnerability
if (CoConstDef.CD_DTL_COMPONENT_ID_ANDROID.equals(type)) {
params.add(new BigDecimal(avoidNull(bean.getCvssScore(), "0.0")).equals(new BigDecimal("0.0")) ? "" : bean.getCvssScore()); // Vuln
params.add(isEmpty(bean.getRestriction()) ? "" : bean.getRestriction());
}
if (isSelfCheck){
params.add((new BigDecimal(avoidNull(bean.getCvssScore(), "0.0")).equals(new BigDecimal("0.0")) ? "" : bean.getCvssScore())); // Vuln
boolean errRowFlag = false;
for (String errCd : vr.getErrorCodeMap().keySet()) {
if (errCd.contains(bean.getComponentId())) {
errRowFlag = true;
break;
}
}
if (errRowFlag) {
// notice
params.add("");
// source code
params.add("");
}else {
// notice
params.add(( (CoConstDef.CD_DTL_OBLIGATION_NOTICE.equals(bean.getObligationType()) || CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : ""));
// source code
params.add(( (CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : ""));
}
// Restriction
params.add((isEmpty(bean.getRestriction()) ? "" : bean.getRestriction()));
}
if (CoConstDef.CD_DTL_COMPONENT_PARTNER.equals(type)){
params.add(isEmpty(bean.getComments()) ? "" : bean.getComments());
// notice
params.add(( (CoConstDef.CD_DTL_OBLIGATION_NOTICE.equals(bean.getObligationType()) || CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : ""));
// source code
params.add(( (CoConstDef.CD_DTL_OBLIGATION_DISCLOSURE.equals(bean.getObligationType())) ? "O" : ""));
// Restriction
params.add((isEmpty(bean.getRestriction()) ? "" : bean.getRestriction()));
}
if (isSelfCheck){
if (bean.getExcludeYn().equals(CoConstDef.FLAG_YES)) {
params.add("Exclude");
} else {
params.add("");
}
}
if (CoConstDef.CD_DTL_COMPONENT_ID_DEP.equals(type)){
if (!isEmpty(bean.getDependencies())) {
params.add(bean.getDependencies());
} else {
params.add("");
}
}
addColumnWarningMessage(type, bean, vr, params);
rows.add(params.toArray(new String[params.size()]));
}
}
//시트 만들기
if (!rows.isEmpty()) {
int startIdx = isSelfCheck ? 1 : 2;
try {
Font font = WorkbookFactory.create(true).createFont();
if (isSelfCheck) {
makeSheetAddWarningMsg(sheet, rows, startIdx, false, font);
} else {
makeSheetAddWarningMsg(sheet, rows, startIdx, true, font);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
private static void addColumnWarningMessage(String type, ProjectIdentification bean, T2CoValidationResult vr, List<String> params) {
String message = "";
if (!vr.getValidMessageMap().isEmpty()) {
String gridId = "";
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
gridId = bean.getComponentId();
} else {
gridId = bean.getGridId();
}
for (String key : vr.getValidMessageMap().keySet()) {
if (key.contains(".") && gridId.equals(key.split("[.]")[1])) {
if (!isEmpty(message)) {
message += "/";
}
message += warningMsgCode((key.split("[.]")[0]).toUpperCase()) + vr.getValidMessageMap().get(key) + "(FONT_RED)";
}
}
}
if (!vr.getDiffMessageMap().isEmpty()) {
String gridId = "";
if (CoConstDef.CD_DTL_COMPONENT_ID_BOM.equals(type)) {
gridId = bean.getComponentId();
} else {
gridId = bean.getGridId();
}
for (String key : vr.getDiffMessageMap().keySet()) {
if (key.contains(".") && gridId.equals(key.split("[.]")[1])) {
if (!isEmpty(message)) {
message += "/";
}
message += warningMsgCode((key.split("[.]")[0]).toUpperCase()) + vr.getDiffMessageMap().get(key) + "(FONT_BLUE)";
}
}
}
params.add(isEmpty(message) ? "" : message);
}
private static String warningMsgCode(String key) {
String warningMsgCode = "";
switch(key) {
case "OSSNAME" :
case "OSS NAME" :
case "OSS NAME ( OPEN SOURCE SOFTWARE NAME )":
case "OSS COMPONENT":
case "PACKAGE NAME":
warningMsgCode = "(ON) ";
break;
case "OSSVERSION" :
case "PACKAGE VERSION":
warningMsgCode = "(OV) ";
break;
case "LICENSE" :
case "LICENSENAME" :
case "LICENSE NAME" :
warningMsgCode = "(L) ";
break;
case "DOWNLOADLOCATION" :
case "PACKAGE DOWNLOAD LOCATION":
warningMsgCode = "(D) ";
break;
case "HOMEPAGE" :
case "OSS WEBSITE":
case "HOME PAGE":
warningMsgCode = "(H) ";
break;
case "SOURCENAMEORPATH" :
case "SOURCECODEPATH" :
case "SOURCE NAME OR PATH" :
case "SOURCE CODE PATH" :
warningMsgCode = "(S) ";
break;
case "BINARYNAME" :
case "BINARYNAMEORSOURCEPATH" :
case "BINARY NAME" :
case "BINARY NAME OR SOURCE PATH" :
warningMsgCode = "(B) ";
break;
default :
break;
}
return warningMsgCode;
}
/**
*
* @param sheet
* @param rows
* @용도 시트 만들기
*/
private static void makeSheet(Sheet sheet, List<String[]> rows) {
int startRow= 1;
int startCol = 0;
int endCol = 0;
int templateRowNum = 1;
if (rows.isEmpty()){
}else{
endCol = rows.get(0).length-1;
}
int shiftRowNum = rows.size();
Row templateRow = sheet.getRow(templateRowNum);
Cell templateCell = templateRow.getCell(0);
CellStyle style = templateCell.getCellStyle();
startRow = templateRow.getRowNum();
for (int i = startRow; i < startRow+shiftRowNum; i++){
String[] rowParam = rows.get(i-startRow);
Row row = sheet.createRow(i);
for (int colNum=startCol; colNum<=endCol; colNum++){
Cell cell=row.createCell(colNum);
cell.setCellStyle(style);
cell.setCellValue(rowParam[colNum]);
}
}
}
private static void makeSheet(Sheet sheet, List<String[]> rows, int templateRowNum) {
makeSheet(sheet, rows, templateRowNum, false);
}
private static void makeSheet(Sheet sheet, List<String[]> rows, int templateRowNum, boolean useLastCellComment) {
int startRow= 1;
int startCol = 0;
int endCol = 0;
if (rows.isEmpty()){
}else{
endCol = rows.get(0).length-1;
}
int shiftRowNum = rows.size();
Row templateRow = sheet.getRow(templateRowNum);
startRow = templateRow.getRowNum();
Row styleTemplateRow = sheet.getRow(startRow);
Cell templateCell = styleTemplateRow.getCell(0);
CellStyle style = templateCell.getCellStyle();
for (int i = startRow; i < startRow + shiftRowNum; i++) {
String[] rowParam = rows.get(i - startRow);
Row row = sheet.getRow(i);
if (row == null) {
row = sheet.createRow(i);
}
for (int colNum = startCol; colNum <= endCol; colNum++) {
Cell cell = row.getCell(colNum);
if (cell == null) {
cell = row.createCell(colNum);
}
// comment의 경우 줄바꿈 처리
if (useLastCellComment && colNum == endCol) {
CellStyle cs = style;
cs.setWrapText(true);
cell.setCellStyle(cs);
} else {
cell.setCellStyle(style);
}
// 수식 삭제
if (CellType.FORMULA == cell.getCellType()) {
cell.setCellType(CellType.BLANK);
}
String cellValue = avoidNull(rowParam[colNum]);
cell.setCellValue(cellValue);
cell.setCellType(CellType.STRING);
}
}
}
private static void makeSheetAddWarningMsg(Sheet sheet, List<String[]> rows, int templateRowNum, boolean useLastCellComment, Font font) {
int startRow= 1;
int startCol = 0;
int endCol = 0;
if (rows.isEmpty()){
}else{
endCol = rows.get(0).length-1;
}
int shiftRowNum = rows.size();
Row templateRow = sheet.getRow(templateRowNum);
startRow = templateRow.getRowNum();
Row styleTemplateRow = sheet.getRow(startRow);
Cell templateCell = styleTemplateRow.getCell(0);
CellStyle style = templateCell.getCellStyle();
for (int i = startRow; i < startRow + shiftRowNum; i++) {
String[] rowParam = rows.get(i - startRow);
Row row = sheet.getRow(i);
if (row == null) {
row = sheet.createRow(i);
}
for (int colNum = startCol; colNum <= endCol; colNum++) {
Cell cell = row.getCell(colNum);
if (cell == null) {
cell = row.createCell(colNum);
}
// comment의 경우 줄바꿈 처리
if ((useLastCellComment && colNum == endCol - 1) || colNum == endCol) {
CellStyle cs = style;
cs.setWrapText(true);
cell.setCellStyle(cs);
} else {
cell.setCellStyle(style);
}
// 수식 삭제
if (CellType.FORMULA == cell.getCellType()) {
cell.setCellType(CellType.BLANK);
}
// warning message의 경우 색상 처리
if (colNum == endCol) {
String cellValue = avoidNull(rowParam[colNum]);
String richTextStr = cellValue.replaceAll("[(]FONT_RED[)]", "").replaceAll("[(]FONT_BLUE[)]", "").replaceAll("[/]", System.lineSeparator());
RichTextString messageStr = new XSSFRichTextString(richTextStr);
{
String[] messageArr = cellValue.split("/");
int startIndex = 0;
for (int j=0; j<messageArr.length; j++) {
String message = "";
if (messageArr[j].contains("(FONT_RED)")) {
message = messageArr[j].split("[(]FONT_RED[)]")[0];
font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());
messageStr.applyFont(startIndex, startIndex + message.length(), font);
} else if (messageArr[j].contains("(FONT_BLUE)")){
message = messageArr[j].split("[(]FONT_BLUE[)]")[0];
font.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
messageStr.applyFont(startIndex, startIndex + message.length(), font);
}
startIndex = startIndex + message.length() + System.lineSeparator().length();
}
}
cell.setCellValue(messageStr);
} else {
String cellValue = avoidNull(rowParam[colNum]);
cell.setCellValue(cellValue);
}
cell.setCellType(CellType.STRING);
}
}
}
private static void makeSheet2(Sheet sheet, List<String[]> rows) {
int startRow= 2;
int startCol = 0;
int endCol = 0;
int templateRowNum = 2;
if (rows.isEmpty()) {
} else {
endCol = rows.get(0).length-1;
}
int shiftRowNum = rows.size();
Row templateRow = sheet.getRow(templateRowNum);
Cell templateCell = templateRow.getCell(0);
CellStyle style = templateCell.getCellStyle();
startRow = templateRow.getRowNum();
for (int i = startRow; i < startRow+shiftRowNum; i++){
String[] rowParam = rows.get(i-startRow);
Row row = sheet.createRow(i);
for (int colNum=startCol; colNum<=endCol; colNum++){
Cell cell=row.createCell(colNum);
cell.setCellStyle(style);
cell.setCellValue(rowParam[colNum]);
cell.setCellType(CellType.STRING);
}
}
}
private static void makeChartSheet(Sheet sheet, List<String[]> rows) {
int startRow= 0;
int startCol = 0;
int endCol = 0;
if (rows.isEmpty()) {
} else {
endCol = rows.get(0).length-1;
}
int shiftRowNum = rows.size();
for (int i = startRow; i < startRow + shiftRowNum; i++) {
String[] rowParam = rows.get(i - startRow);
Row row = sheet.getRow(i);
if (row == null) {
row = sheet.createRow(i);
}
for (int colNum = startCol; colNum <= endCol; colNum++) {
Cell cell = row.getCell(colNum);
if (cell == null) {
cell = row.createCell(colNum);
}
// 수식 삭제
if (CellType.FORMULA == cell.getCellType()) {
cell.setCellType(CellType.BLANK);
}
cell.setCellValue(avoidNull(rowParam[colNum]));
cell.setCellType(CellType.STRING);
}
}
}
/**
*
* @param sheet
* @param rows
* @용도 시트 만들기
*/
private static void reportSheet(Workbook wb,Sheet sheet, Project project) {
// About the report
// Creator
Cell authorCell = sheet.getRow(1).getCell(1);
authorCell.setCellType(CellType.STRING);
authorCell.setCellValue(avoidNull(project.getPrjUserName(), project.getCreator()));
// Division of Creator
Cell divisionrCell = sheet.getRow(2).getCell(1);
divisionrCell.setCellType(CellType.STRING);
divisionrCell.setCellValue(avoidNull(project.getPrjDivisionName()));
// Report Creation Date
Cell dateCell = sheet.getRow(3).getCell(1);
dateCell.setCellType(CellType.STRING);
dateCell.setCellValue(CommonFunction.formatDate(project.getCreatedDate()));
// About the project
// Project Name
Cell nameCell = sheet.getRow(6).getCell(1);
nameCell.setCellType(CellType.STRING);
nameCell.setCellValue(project.getPrjName());
// version
Cell versionCell = sheet.getRow(7).getCell(1);
versionCell.setCellType(CellType.STRING);
versionCell.setCellValue(avoidNull(project.getPrjVersion()));
// Software Type
Cell softwareType = sheet.getRow(8).getCell(1);
softwareType.setCellType(CellType.STRING);
softwareType.setCellValue(CoConstDef.COMMON_SELECTED_ETC.equals(project.getOsType()) ? project.getOsTypeEtc() : CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, project.getOsType()));
// Distribution Type
Cell distributionType = sheet.getRow(9).getCell(1);
distributionType.setCellType(CellType.STRING);
distributionType.setCellValue(CoCodeManager.getCodeString(CoConstDef.CD_DISTRIBUTION_TYPE, project.getDistributionType()));
// Network Service Only?
Cell networkServiceOnly = sheet.getRow(10).getCell(1);
networkServiceOnly.setCellType(CellType.STRING);
networkServiceOnly.setCellValue(project.getNetworkServerType());
// About OSC Process
// Distribution Site
Cell distributionSite = sheet.getRow(13).getCell(1);
distributionSite.setCellType(CellType.STRING);
distributionSite.setCellValue(CoCodeManager.getCodeString(CoConstDef.CD_DISTRIBUTE_CODE, project.getDistributeTarget()));
// Notice Type
String noticeTypeStr = CoCodeManager.getCodeString(CoConstDef.CD_NOTICE_TYPE, project.getNoticeType());
if (!isEmpty(project.getNoticeTypeEtc())) {
noticeTypeStr += " (" +CoCodeManager.getCodeString(CoConstDef.CD_PLATFORM_GENERATED, project.getNoticeTypeEtc()) + ")";
}
Cell noticeType = sheet.getRow(14).getCell(1);
noticeType.setCellType(CellType.STRING);
noticeType.setCellValue(noticeTypeStr);
// Comment
Cell comment = sheet.getRow(15).getCell(1);
comment.setCellType(CellType.STRING);
comment.setCellValue(CommonFunction.html2text(project.getComment()));
}
/**
*
* @param licenseList
* @return
* @throws Exception
* @용도 license 엑셀
*/
private static String getLicenseExcel(List<LicenseMaster> licenseList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/LicenseList.xlsx"));
try {wb = new XSSFWorkbook(inFile);} catch (IOException e) {log.error(e.getMessage());}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "LicenseList");
List<String[]> rows = new ArrayList<>();
for (int i = 0; i < licenseList.size(); i++){
LicenseMaster param = licenseList.get(i);
String[] rowParam = {
param.getLicenseId()
, param.getLicenseName()
, param.getShortIdentifier()
, convertLineSeparator(param.getLicenseNicknameList())
, param.getLicenseType()
, param.getRestrictionStr()
, CommonFunction.makeLicenseObligationStr(param.getObligationChecks())
, param.getWebpage()
, param.getDescription() // user guide
, param.getAttribution()
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"LicenseList");
}
private static String convertLineSeparator(List<String> list) {
String rtn = "";
if (list != null) {
for (String s : list) {
if (!isEmpty(s)) {
if (!isEmpty(rtn)) {
rtn += "\r\n";
}
rtn += s;
}
}
}
return rtn;
}
/**
*
* @param partner
* @return
* @throws Exception
* @용도 oss 엑셀 파일
*/
private static String getOssExcel(List<OssMaster> oss) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/OssList.xlsx"));
try {wb = new XSSFWorkbook(inFile);} catch (IOException e) {log.error(e.getMessage());}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "ossList");
List<String[]> rows = new ArrayList<>();
for (int i = 0; i < oss.size(); i++){
OssMaster param = oss.get(i);
String[] rowParam = {
param.getOssId()
, param.getOssName()
, convertPipeToLineSeparator(param.getOssNickname())
, param.getOssVersion()
, CommonFunction.makeOssTypeStr(param.getOssType())
, param.getLicenseName()
, param.getLicenseType()
, CoCodeManager.getCodeString(CoConstDef.CD_OBLIGATION_TYPE, param.getObligationType())
, param.getHomepage()
, param.getDownloadLocation()
, param.getCopyright()
, param.getAttribution()
, param.getCvssScore()
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"OssList");
}
private static String convertPipeToLineSeparator(String nick) {
String rtn = "";
if (!isEmpty(nick)) {
for (String s : nick.split("\\|")) {
if (!isEmpty(s)) {
if (!isEmpty(rtn)) {
rtn += "\r\n";
}
rtn += s;
}
}
}
return rtn;
}
/**
*
* @param projectList
* @return
* @throws Exception
* @용도 Project 엑셀
*/
private static String getProjectExcel(List<Project> projectList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/ProjectList.xlsx"));
try {
wb = new XSSFWorkbook(inFile);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "ProjectList");
Project expParam = new Project();
for (Project p : projectList) {
expParam.addPrjIdList(p.getPrjId());
}
Map<String, Map<String, String>> projectExpandInfo = projectService.getProjectDownloadExpandInfo(expParam);
List<String[]> rows = new ArrayList<>();
List<String> customNvdMaxScoreInfoList = new ArrayList<>();
Map<String, OssMaster> ossInfoMap = CoCodeManager.OSS_INFO_UPPER;
for (int i = 0; i < projectList.size(); i++){
Project param = projectList.get(i);
Map<String, String> expandInfo = projectExpandInfo.get(param.getPrjId());
String nvdMaxScore = "";
List<String> nvdMaxScoreInfoList = projectMapper.findIdentificationMaxNvdInfo(param.getPrjId(), param.getReferenceDiv());
List<String> nvdMaxScoreInfoList2 = projectMapper.findIdentificationMaxNvdInfoForVendorProduct(param.getPrjId(), param.getReferenceDiv());
if (nvdMaxScoreInfoList != null && !nvdMaxScoreInfoList.isEmpty()) {
String conversionCveInfo = CommonFunction.checkNvdInfoForProduct(ossInfoMap, nvdMaxScoreInfoList);
if (conversionCveInfo != null) {
customNvdMaxScoreInfoList.add(conversionCveInfo);
}
}
if (nvdMaxScoreInfoList2 != null && !nvdMaxScoreInfoList2.isEmpty()) {
customNvdMaxScoreInfoList.addAll(nvdMaxScoreInfoList2);
}
if (customNvdMaxScoreInfoList != null && !customNvdMaxScoreInfoList.isEmpty()) {
String conversionCveInfo = CommonFunction.getConversionCveInfoForList(customNvdMaxScoreInfoList);
if (conversionCveInfo != null) {
String[] conversionCveData = conversionCveInfo.split("\\@");
nvdMaxScore = conversionCveData[3];
}
}
customNvdMaxScoreInfoList.clear();
String[] rowParam = {
param.getPrjId()
, param.getStatus()
, param.getPrjName()
, param.getPrjVersion()
, CoConstDef.COMMON_SELECTED_ETC.equals(avoidNull(param.getOsType(), CoConstDef.COMMON_SELECTED_ETC)) ? param.getOsTypeEtc() : CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, param.getOsType())
, param.getDistributionType()
, param.getIdentificationStatus()
, getExpandProjectInfo(expandInfo, "PARTNER_CNT")
, getExpandProjectInfo(expandInfo, "SRC_CNT")
, getExpandProjectInfo(expandInfo, "BAT_CNT")
, getExpandProjectInfo(expandInfo, "BOM_CNT") + "(" + getExpandProjectInfo(expandInfo, "DISCLOSE_CNT") + ")"
, param.getVerificationStatus()
, getExpandProjectInfo(expandInfo, "NOTICE_TYPE")
, getExpandProjectInfo(expandInfo, "NOTICE_FILE_NAME")
, getExpandProjectInfo(expandInfo, "PACKAGE_FILE_NAME")
, param.getDestributionStatus()
, getExpandProjectInfo(expandInfo, "DISTRIBUTE_TARGET")
, getExpandProjectInfo(expandInfo, "DISTRIBUTE_NAME")
, getExpandProjectInfo(expandInfo, "DISTRIBUTE_MASTER_CATEGORY")
, getExpandProjectInfo(expandInfo, "MODEL_INFO")
, getExpandProjectInfo(expandInfo, "DISTRIBUTE_DEPLOY_TIME")
, nvdMaxScore
, param.getDivision()
, param.getCreator()
, CommonFunction.formatDate(param.getCreatedDate())
, param.getReviewer()
};
rows.add(rowParam);
}
//시트 만들기
makeSheet2(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"ProjectList");
}
private static String getExpandProjectInfo(Map<String, String> map, String target) {
String rtnStr = "";
if (map != null && map.containsKey(target)) {
rtnStr = avoidNull(String.valueOf(map.get(target)));
switch (target) {
case "NOTICE_TYPE":
rtnStr = CoCodeManager.getCodeString(CoConstDef.CD_NOTICE_TYPE, rtnStr);
break;
case "DISTRIBUTE_TARGET":
rtnStr = CoCodeManager.getCodeString(CoConstDef.CD_DISTRIBUTE_CODE, rtnStr);
break;
case "DISTRIBUTE_DEPLOY_TIME":
if (!isEmpty(rtnStr)) {
rtnStr = CommonFunction.formatDate(rtnStr);
}
break;
case "DISTRIBUTE_MASTER_CATEGORY":
if (!isEmpty(rtnStr)) {
rtnStr = StringUtil.leftPad(rtnStr, 6, "0");
rtnStr = CommonFunction.makeCategoryFormat(String.valueOf(map.get("DISTRIBUTE_TARGET")), rtnStr.substring(0, 3), rtnStr.substring(3));
}
break;
case "MODEL_INFO":
if (!isEmpty(rtnStr)) {
// T3.CATEGORY, '@',T3.SUBCATEGORY, '@',T3.MODEL_NAME, '@', T3.RELEASE_DATE
String[] modelInfos = rtnStr.split("\\|");
rtnStr = "";
int modelSeq = 0;
for (String model : modelInfos) {
if (!isEmpty(rtnStr)) {
rtnStr += "\n";
}
if (rtnStr.length() > 32000) {
break;
}
String tmp = "";
String[] _tmpArr = model.split("@");
if (_tmpArr != null && _tmpArr.length == 4) {
// category
if (!isEmpty(_tmpArr[0]) && !isEmpty(_tmpArr[1])) {
rtnStr += CommonFunction.makeCategoryFormat(String.valueOf(map.get("DISTRIBUTE_TARGET")), _tmpArr[0], _tmpArr[1]);
}
tmp += ", ";
tmp += _tmpArr[2];
tmp += ", ";
if (!isEmpty(_tmpArr[3])) {
tmp += CommonFunction.formatDateSimple(_tmpArr[3]);
}
rtnStr += tmp;
modelSeq++;
}
}
if (modelInfos.length-modelSeq > 0) {
rtnStr += "and " + (modelInfos.length-modelSeq);
}
}
break;
default:
break;
}
}
return rtnStr;
}
private static String getPartnerExcelId(List<PartnerMaster> ossList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/3rdList.xlsx"));
wb = new XSSFWorkbook(inFile);
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "3rdList");
if (ossList != null && !ossList.isEmpty()) {
List<String[]> rows = new ArrayList<>();
for (PartnerMaster bean : ossList) {
List<String> params = new ArrayList<>();
// main 정보
params.add(bean.getPartnerId()); //ID
params.add(bean.getPartnerName());
params.add(bean.getSoftwareName());
params.add(bean.getSoftwareVersion());
params.add(CoCodeManager.getCodeString(CoConstDef.CD_IDENTIFICATION_STATUS, bean.getStatus()));
params.add(CoCodeManager.getCodeString(CoConstDef.CD_PARTNER_DELIVERY_FORM, bean.getDeliveryForm()));
params.add(bean.getDescription());
params.add(bean.getFileName());
params.add(bean.getFileName2());
params.add(bean.getDivision());
params.add(bean.getCreator());
params.add(CommonFunction.formatDate(bean.getCreatedDate()));
rows.add(params.toArray(new String[params.size()]));
}
//시트 만들기
makeSheet(sheet, rows);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"PartnerList");
}
private static String getModelStatusExcelId(List<Project> project, Project fileData) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/complianceStatus.xlsx"));
wb = new XSSFWorkbook(inFile);
if (fileData != null){
sheet = wb.getSheetAt(0);
int idx = 1;
List<String[]> rows = new ArrayList<>();
int modelListLength = fileData.getModelListInfo().size();
int productGroupsLength = fileData.getProductGroups().size();
List<String> productGroups = fileData.getProductGroups();
List<String> modelInfo = fileData.getModelListInfo();
int length = productGroupsLength > modelListLength ? productGroupsLength : modelListLength;
for (int i = 0 ; i < length ; i++){
List<String> params = new ArrayList<>();
// main 정보
params.add(Integer.toString(idx++)); // No
params.add(productGroupsLength > 0 && productGroupsLength > i ? productGroups.get(i) : ""); // Product Group
params.add(modelListLength > 0 && modelListLength > i ? modelInfo.get(i) : ""); // Model(Software) Name
rows.add(params.toArray(new String[params.size()]));
}
//시트 만들기
makeSheet2(sheet, rows);
}
if (project != null && !project.isEmpty()) {
sheet = wb.getSheetAt(1);
int idx = 1;
List<String[]> rows = new ArrayList<>();
for (Project bean : project) {
List<String> params = new ArrayList<>();
// main 정보
params.add(Integer.toString(idx++)); // No
params.add(bean.getModelName()); // Model(Software) Name
params.add(bean.getPrjId()); // Project ID
params.add(bean.getStatus()); // Status
params.add(bean.getDistributionType()); // Distribution Type
params.add(bean.getDestributionStatus()); // Distribution Status
String distributionDate = avoidNull(bean.getDistributeDeployTime(), "");
params.add(isEmpty(bean.getPrjId()) ? "" : CommonFunction.formatDate(distributionDate)); // Distribute Time
params.add(isEmpty(bean.getPrjId()) ? CoConstDef.FLAG_NO : CoConstDef.FLAG_YES); // Result
params.add(""); // Comment
rows.add(params.toArray(new String[params.size()]));
}
//시트 만들기
makeSheet(sheet, rows);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"Model Status");
}
private static String getPartnerModelExcelId(List<PartnerMaster> ossList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/complianceStatus.xlsx"));
wb = new XSSFWorkbook(inFile);
sheet = wb.getSheetAt(2);
if (ossList != null && !ossList.isEmpty()) {
int idx = 1;
List<String[]> rows = new ArrayList<>();
for (PartnerMaster bean : ossList) {
List<String> params = new ArrayList<>();
// main 정보
params.add(Integer.toString(idx++)); // No
params.add(bean.getPartnerId()); // 3rd Party ID
params.add(CoCodeManager.getCodeString(CoConstDef.CD_IDENTIFICATION_STATUS, bean.getStatus())); // Status
params.add(bean.getPartnerName()); // 3rd Party Name
params.add(bean.getSoftwareName()); // software Name
params.add(bean.getSoftwareVersion()); // software Version
params.add(bean.getPrjId()); // Used Project ID
params.add(CommonFunction.formatDate(bean.getCreatedDate())); // Created Date
params.add(""); // Comment
rows.add(params.toArray(new String[params.size()]));
}
//시트 만들기
makeSheet(sheet, rows);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"3rd Party List");
}
/**
*
* @param batList
* @return
* @throws Exception
* @용도 user 엑셀
*/
private static String getUserExcelId(List<T2Users> userList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/UserList.xlsx"));
wb = new XSSFWorkbook(inFile);
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "UserList");
List<String[]> rows = new ArrayList<>();
for (int i = 0; i < userList.size(); i++){
T2Users param = userList.get(i);
String[] rowParam = {
String.valueOf(i+1)
, param.getUserId()
, param.getEmail()
, param.getUserName()
, param.getDivision()
, param.getCreatedDate()
, param.getUseYn()
, param.getAuthority()
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb, "UserList");
}
private static String getModelExcel(List<Project> modelList, String distributionType) throws Exception {
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
List<String[]> rows = null;
try {
inFile= new FileInputStream(new File(downloadpath+ (CoConstDef.CD_DISTRIBUTE_SITE_SKS.equals(distributionType) ? "/SKS_ModelList.xlsx" : "/ModelList.xlsx") ));
wb = WorkbookFactory.create(inFile);
String mainModelCode = CoConstDef.CD_DISTRIBUTE_SITE_SKS.equals(distributionType) ? CoConstDef.CD_MODEL_TYPE2 : CoConstDef.CD_MODEL_TYPE;
// category sheet 생성
sheet = wb.getSheetAt(1);
rows = new ArrayList<>();
int idx = 1;
for (String mCode : CoCodeManager.getCodes(mainModelCode)) {
String sCode = CoCodeManager.getSubCodeNo(mainModelCode, mCode);
for (String subCode : CoCodeManager.getCodes(sCode)) {
String categoryName = CoCodeManager.getCodeString(mainModelCode, mCode);
String subCategoryName = CoCodeManager.getCodeString(sCode, subCode);
String[] rowParam = {
Integer.toString(idx++)
, categoryName
, subCategoryName
, categoryName + " > " + subCategoryName
, mCode
, subCode
};
rows.add(rowParam);
}
}
makeSheet(sheet, rows);
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "ModelList");
rows = new ArrayList<>();
if (modelList != null) {
for (int i = 0; i < modelList.size(); i++){
Project param = modelList.get(i);
String main = StringUtil.substring(param.getCategory(), 0, 3);
String sub = StringUtil.substring(param.getCategory(), 3);
String mainStr = CoCodeManager.getCodeString(mainModelCode, main);
String subStr = CoCodeManager.getCodeString(CoCodeManager.getSubCodeNo(mainModelCode, main), sub);
param.setCategory(mainStr+" > "+subStr);
String[] rowParam = {
param.getModelName()
, param.getCategory()
, param.getReleaseDate()
, ""
};
rows.add(rowParam);
}
}
if (rows.size() > 0) {
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("'Category List'!$D$2:$D$1048576");
CellRangeAddressList addressList = new CellRangeAddressList(1, rows.size(), 1, 1);
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
if (validation instanceof XSSFDataValidation) {
validation.setSuppressDropDownArrow(true);
} else {
// If the Datavalidation contains an instance of the
// HSSFDataValidation
// class then 'true' should be passed to the
// setSuppressDropDownArrow()
// method and the call to setShowErrorBox() is not
// necessary.
validation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(validation);
}
//시트 만들기
makeSheet(sheet, rows);
wb.setActiveSheet(0);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,CoConstDef.CD_DISTRIBUTE_SITE_SKS.equals(distributionType) ? "SKS_ModelList" : "ModelList");
}
private static String makeExcelFileId(Workbook wb, String target) throws IOException {
return makeExcelFileId(wb, target, "xlsx");
}
private static String makeExcelFileId(Workbook wb, String target, String exp) throws IOException {
UUID randomUUID = UUID.randomUUID();
String fileName = CommonFunction.replaceSlashToUnderline(target);
String logiFileName = fileName + "_" + randomUUID+"."+exp;
String excelFilePath = writepath+"/download/";
FileOutputStream outFile = null;
try {
if (!Files.exists(Paths.get(excelFilePath))) {
Files.createDirectories(Paths.get(excelFilePath));
}
outFile = new FileOutputStream(excelFilePath + logiFileName);
wb.write(outFile);
// db 등록
return fileService.registFileDownload(excelFilePath, fileName + "."+exp, logiFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (Exception e2) {}
}
}
return null;
}
private static String makeCsvFileId(String target, List<String[]> datas) throws IOException {
UUID randomUUID = UUID.randomUUID();
String fileName = CommonFunction.replaceSlashToUnderline(target)+"_"+CommonFunction.getCurrentDateTime();
String logiFileName = fileName + "_" + randomUUID+".csv";
String excelFilePath = writepath+"/download/";
CSVWriter cw = null;
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.EXCEL;
FileOutputStream outFile = null;
try {
fileWriter = new FileWriter(excelFilePath + logiFileName);
if (!Files.exists(Paths.get(excelFilePath))) {
Files.createDirectories(Paths.get(excelFilePath));
}
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
for (String[] row : datas) {
csvFilePrinter.printRecord(Arrays.asList(row));
}
fileWriter.flush();
// db 등록
return fileService.registFileDownload(excelFilePath, fileName + ".csv", logiFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (Exception e2) {}
}
if (cw != null) {
try {
cw.close();
} catch (Exception e2) {}
}
if (fileWriter != null) {
try {
fileWriter.close();
} catch (Exception e2) {}
}
if (csvFilePrinter != null) {
try {
csvFilePrinter.close();
} catch (Exception e2) {}
}
}
return null;
}
private static String makeAnalysisListExcelFileId(Workbook wb, String target, String exp, String prjId) throws IOException {
UUID randomUUID = UUID.randomUUID();
String fileName = CommonFunction.replaceSlashToUnderline(target)+"_"+CommonFunction.getCurrentDateTime();
String logiFileName = fileName + "_" + randomUUID+"."+exp;
String analysisSavePath = CommonFunction.emptyCheckProperty("autoanalysis.input.path", "/autoanalysis/input/dev") + "/" + prjId;
FileOutputStream outFile = null;
try {
if (!Files.exists(Paths.get(analysisSavePath))) {
Files.createDirectories(Paths.get(analysisSavePath));
}
outFile = new FileOutputStream(analysisSavePath + "/" + logiFileName);
wb.write(outFile);
// db 등록
return fileService.registFileDownload(analysisSavePath, fileName + "." + exp, logiFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (Exception e2) {}
}
}
return null;
}
public static String getExcelDownloadId(String type, String dataStr, String filepath) throws Exception {
return getExcelDownloadId(type, dataStr, filepath, null);
}
@SuppressWarnings({ "unchecked", "serial" })
public static String getExcelDownloadId(String type, String dataStr, String filepath, String extParam) throws Exception {
downloadpath = filepath;
String downloadId = null;
switch (type) {
case "verification":
downloadId = makeVerificationExcel((List<ProjectIdentification>) fromJson(dataStr, new TypeToken<List<ProjectIdentification>>(){}.getType()));
break;
case "project" : //Project List
// status, publicYn 조건 추가로 data 가공
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> projectMap = new HashMap<String, Object>();
projectMap = mapper.readValue((String) dataStr, new TypeReference<Map<String, Object>>(){});
if (projectMap != null){
if (projectMap.get("statuses") != null) {
String statuses = String.valueOf(projectMap.get("statuses"));
if (!isEmpty(statuses)){
String[] arrStatuses = statuses.split(",");
projectMap.put("arrStatuses", arrStatuses);
}
}
projectMap.put("publicYn", (isEmpty(String.valueOf(projectMap.get("publicYn")))?CoConstDef.FLAG_YES:String.valueOf(projectMap.get("publicYn"))));
dataStr = mapper.writeValueAsString(projectMap);
}
Type projectType = new TypeToken<Project>(){}.getType();
Project project = (Project) fromJson(dataStr, projectType);
List<String> watcherList = new ArrayList<>();
String[] watchers = project.getWatchers();
for (String watcher : watchers) {
if (!isEmpty(watcher)) watcherList.add(watcher);
}
project.setWatchers(watcherList.toArray(new String[watcherList.size()]));
project.setStartIndex(0);
project.setPageListSize(MAX_RECORD_CNT);
project.setExcelDownloadFlag(CoConstDef.FLAG_YES);
Map<String, Object> prjMap = projectService.getProjectList(project);
if (isMaximumRowCheck((int) prjMap.get("records"))){
downloadId = getProjectExcel((List<Project>) prjMap.get("rows"));
}
break;
case "report" : //project report
case "bom" : //project bom
downloadId = getReportExcelPost(dataStr, null);
break;
case "dep" : //DEP List
downloadId = getReportExcelPost(dataStr, CoConstDef.CD_DTL_COMPONENT_ID_DEP);
break;
case "src" : //SRC List
downloadId = getReportExcelPost(dataStr, CoConstDef.CD_DTL_COMPONENT_ID_SRC);
break;
case "bin" : //bin List
downloadId = getReportExcelPost(dataStr, CoConstDef.CD_DTL_COMPONENT_ID_BIN);
break;
case "binAndroid" : //bin android List
downloadId = getReportExcelPost(dataStr, CoConstDef.CD_DTL_COMPONENT_ID_ANDROID);
break;
case "license" : //License List
Type licenseType = new TypeToken<LicenseMaster>(){}.getType();
LicenseMaster license = (LicenseMaster) fromJson(dataStr, licenseType);
license.setStartIndex(0);
license.setPageListSize(MAX_RECORD_CNT);
List<LicenseMaster> licenseList = licenseService.getLicenseMasterListExcel(license);
if (isMaximumRowCheck(licenseService.selectLicenseMasterTotalCount(license))){
downloadId = getLicenseExcel(licenseList);
}
break;
case "oss" : //Oss List
Type ossType = new TypeToken<OssMaster>(){}.getType();
OssMaster oss = (OssMaster) fromJson(dataStr, ossType);
oss.setStartIndex(0);
oss.setPageListSize(MAX_RECORD_CNT);
Map<String,Object> ossMap = ossService.getOssMasterList(oss);
downloadId = getOssExcel((List<OssMaster>) ossMap.get("rows"));
break;
case "model" : //project model
Type modelType = new TypeToken<List<Project>>(){}.getType();
List<Project> modelList = (List<Project>) fromJson(dataStr, modelType);
downloadId = getModelExcel(modelList, extParam);
break;
case "selfCheckList" :
downloadId = getSelfCheckListExcelPost(dataStr, null);
break;
case "selfReport" : //selfCheck Project
downloadId = getSelftReportExcelPost(dataStr);
break;
case "partnerCheckList" :
downloadId = getPartnerChecklistReportExcelPost(dataStr);
break;
case "spdx" :
downloadId = getVerificationSPDX_SpreadSheetExcelPost(dataStr);
break;
case "spdx_sbom" :
downloadId = getSBOMSPDX_SpreadSheetExcelPost(dataStr);
break;
case "spdx_self" :
downloadId = getSelfCheckSPDX_SpreadSheetExcelPost(dataStr);
break;
case "binaryDBLog" :
Type binaryDBLogType = new TypeToken<BinaryAnalysisResult>(){}.getType();
BinaryAnalysisResult bianryDbLogBean = (BinaryAnalysisResult) fromJson(dataStr, binaryDBLogType);
Map<String, String> exceptionMap = new HashMap<>();
exceptionMap.put("binaryName", "fileName");
exceptionMap.put("filePath", "pathName");
exceptionMap.put("tlsh", "tlshCheckSum");
exceptionMap.put("parentname", "parentName");
exceptionMap.put("platformname", "platformName");
exceptionMap.put("platformversion", "platformVersion");
exceptionMap.put("updatedate", "updateDate");
exceptionMap.put("createddate", "createdDate");
String filterCondition = CommonFunction.getFilterToString(bianryDbLogBean.getFilters(), null, exceptionMap);
if (!isEmpty(filterCondition)) {
bianryDbLogBean.setFilterCondition(filterCondition);
}
bianryDbLogBean.setSidx("actionId");
bianryDbLogBean.setSord("desc");
bianryDbLogBean.setPageListSize(MAX_RECORD_CNT_LIST);
Map<String, Object> bianryDbLogMap = binaryDataHistoryService.getBinaryDataHistoryList(bianryDbLogBean);
if (isMaximumRowCheck((int) bianryDbLogMap.get("records"))){
downloadId = getBinaryDBLogExcel((List<BinaryAnalysisResult>) bianryDbLogMap.get("rows"));
}
break;
case "3rd" : //3rd Party List
Type partnerType = new TypeToken<PartnerMaster>(){}.getType();
PartnerMaster partner = (PartnerMaster) fromJson(dataStr, partnerType);
if (partner.getStatus() != null) {
String statuses = partner.getStatus();
if (!isEmpty(statuses)) {
String[] arrStatuses = statuses.split(",");
partner.setArrStatuses(arrStatuses);
}
}
List<String> partnerWatcherList = new ArrayList<>();
String[] partnerWatchers = partner.getWatchers();
for (String partnerWatcher : partnerWatchers) {
if (!isEmpty(partnerWatcher)) partnerWatcherList.add(partnerWatcher);
}
partner.setWatchers(partnerWatcherList.toArray(new String[partnerWatcherList.size()]));
partner.setStartIndex(0);
partner.setPageListSize(MAX_RECORD_CNT);
partner.setModelFlag(CoConstDef.FLAG_NO);
Map<String, Object> partnerList = partnerService.getPartnerMasterList(partner);
downloadId = getPartnerExcelId((List<PartnerMaster>) partnerList.get("rows"));
break;
case "3rdModel" : //3rd Party List
Type partnerModelType = new TypeToken<PartnerMaster>(){}.getType();
PartnerMaster partnerModel = (PartnerMaster) fromJson(dataStr, partnerModelType);
if (partnerModel.getStatus() != null) {
String statuses = partnerModel.getStatus();
if (!isEmpty(statuses)) {
String[] arrStatuses = statuses.split(",");
partnerModel.setArrStatuses(arrStatuses);
}
}
partnerModel.setStartIndex(0);
partnerModel.setPageListSize(MAX_RECORD_CNT);
partnerModel.setModelFlag(CoConstDef.FLAG_YES);
Map<String, Object> partnerModelList = partnerService.getPartnerStatusList(partnerModel);
if (isMaximumRowCheck((int) partnerModelList.get("records"))){
downloadId = getPartnerModelExcelId((List<PartnerMaster>) partnerModelList.get("rows"));
}
break;
case "modelStatus":
Type ProjectModelType = new TypeToken<Project>(){}.getType();
Project ProjectModel = (Project) fromJson(dataStr, ProjectModelType);
if (!isEmpty(ProjectModel.getModelName())){
String[] modelNames = ProjectModel.getModelName().split(",");
String[] productGroups = ProjectModel.getProductGroup().split(",");
List<String> modelListInfo = new ArrayList<String>();
List<String> productGroupListInfo = new ArrayList<String>();
for (String modelName : modelNames){
modelListInfo.add(modelName);
}
for (String productGroup : productGroups){
productGroupListInfo.add(productGroup);
}
ProjectModel.setModelListInfo(modelListInfo);
ProjectModel.setProductGroups(productGroupListInfo);
ProjectModel.setPageListSize(MAX_RECORD_CNT_LIST);
Map<String, Object> map = complianceService.getModelList(ProjectModel);
if (isMaximumRowCheck((int) map.get("records"))){
downloadId = getModelStatusExcelId((List<Project>) map.get("rows"), ProjectModel);
}
} else {
downloadId = getModelStatusExcelId(null, null);
}
break;
case "vulnerability" : //vulnerability 2018-07-26 choye 추가
Type vulnerabilityType = new TypeToken<Vulnerability>(){}.getType();
Vulnerability vulnerability = (Vulnerability) fromJson(dataStr, vulnerabilityType);
vulnerability.setSidx("cveId");
vulnerability.setPageListSize(MAX_RECORD_CNT_LIST);
Map<String, Object> vulnerabilityMap = vulnerabilityService.getVulnerabilityList(vulnerability, true);
if (isMaximumRowCheck((int) vulnerabilityMap.get("records"))){
downloadId = getVulnerabilityExcel((List<Vulnerability>) vulnerabilityMap.get("rows"));
}
break;
case "vulnerabilityPopup": //export in vulnerability popup
Type ossMaster = new TypeToken<OssMaster>(){}.getType();
OssMaster bean = (OssMaster) fromJson(dataStr, ossMaster);
bean.setPageListSize(MAX_RECORD_CNT_LIST);
Map<String, Object> vulnerabilityPopupMap = vulnerabilityService.getVulnListByOssName(bean);
if (isMaximumRowCheck((int) vulnerabilityPopupMap.get("records"))){
downloadId = getVulnerabilityExcel((List<Vulnerability>) vulnerabilityPopupMap.get("rows"));
}
break;
case "autoAnalysis":
OssMaster ossBean = new OssMaster();
ossBean.setPrjId(dataStr);
ossBean.setStartAnalysisFlag(CoConstDef.FLAG_YES);
ossBean.setPageListSize(MAX_RECORD_CNT);
Map<String, Object> analysisList = ossService.getOssAnalysisList(ossBean);
downloadId = getAnalysisListExcel((List<OssAnalysis>) analysisList.get("rows"), (String) ossBean.getPrjId());
break;
case "user" : //UserManagement List
List<T2Users> userList = userService.getUserListExcel();
downloadId = getUserExcelId(userList);
break;
case "bomcompare" :
downloadId = getBomCompareExcelId(dataStr);
break;
case "security":
Type prj = new TypeToken<Project>(){}.getType();
Project param = (Project) fromJson(dataStr, prj);
Map<String, Object> result = projectService.getSecurityGridList(param);
Project projectMaster = projectService.getProjectDetail(param);
downloadId = getSecurityExcelId(result, projectMaster, param.getCode());
break;
case "cycloneDXJson" :
case "cycloneDXXml" :
downloadId = getCycloneDXFileId(type, dataStr, extParam.equals("verify") ? true : false);
break;
default:
break;
}
return downloadId;
}
@SuppressWarnings("unchecked")
private static String getSecurityExcelId(Map<String, Object> result, Project projectMaster, String code) throws IOException {
List<OssComponents> securityGridList = null;
switch (code) {
case "total" : securityGridList = (List<OssComponents>) result.get("totalList");
break;
case "fixed" : securityGridList = (List<OssComponents>) result.get("fixedList");
break;
default : securityGridList = (List<OssComponents>) result.get("notFixedList");
break;
}
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
// download file name
String downloadFileName = "fosslight_security"; // Default
downloadFileName += "_" + CommonFunction.getCurrentDateTime() + "_prj-" + StringUtil.deleteWhitespaceWithSpecialChar(projectMaster.getPrjId());
try {
inFile= new FileInputStream(new File(downloadpath+"/Security.xlsx"));
wb = WorkbookFactory.create(inFile);
CreationHelper creationHelper = wb.getCreationHelper();
CellStyle style = wb.createCellStyle();
CellStyle hyperLinkStyle = wb.createCellStyle();
Font hyperLinkFont = wb.createFont();
hyperLinkFont.setUnderline(Font.U_SINGLE);
hyperLinkFont.setColor(IndexedColors.BLUE.getIndex());
hyperLinkStyle.setFont(hyperLinkFont);
sheet = wb.getSheetAt(7);
if (securityGridList != null){
List<String[]> rowInfoData = new ArrayList<>();
List<String[]> rowDatas = new ArrayList<>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String now_dt = format.format(now);
String[] rowInfoParam = {
now_dt
, projectMaster.getPrjName()
, projectMaster.getPrjVersion()
, projectMaster.getPrjUserName()
, CoCodeManager.getCodeString(CoConstDef.CD_USER_DIVISION, projectMaster.getDivision())
};
rowInfoData.add(rowInfoParam);
int num = 1;
for (OssComponents bean : securityGridList) {
String[] rowParam = {
String.valueOf(num++)
, bean.getOssName()
, bean.getOssVersion()
, bean.getCveId()
, bean.getPublDate()
, bean.getCvssScore()
, bean.getVulnerabilityResolution()
};
rowDatas.add(rowParam);
}
makeSecuritySheet(creationHelper, sheet, style, hyperLinkStyle, rowInfoData, rowDatas);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb, downloadFileName);
}
private static void makeSecuritySheet(CreationHelper creationHelper, Sheet sheet, CellStyle style, CellStyle hyperLinkStyle, List<String[]> infoRows, List<String[]> rows) {
int infoStartRow= 1;
int startRow= 8;
int startCol = 0;
int endCol = 0;
if (!infoRows.isEmpty()) {
endCol = infoRows.get(0).length-1;
}
int shiftRowNum = infoRows.get(0).length;
String[] rowParam = infoRows.get(0);
for (int i = infoStartRow; i < infoStartRow+shiftRowNum; i++){
Row templateRow = sheet.getRow(i);
Cell templateCell = templateRow.getCell(3);
CellStyle st = templateCell.getCellStyle();
Row row = sheet.getRow(i);
Cell cell = getCell(row, 3);
cell.setCellStyle(st);
cell.setCellValue(rowParam[i-infoStartRow]);
cell.setCellType(CellType.STRING);
}
if (!rows.isEmpty()) {
endCol = rows.get(0).length-1;
}
int rowIndex = 0;
for (int i = startRow; i < startRow+rows.size(); i++){
Row row = sheet.createRow(i);
for (int colNum=startCol; colNum<=endCol; colNum++){
Cell cell = row.createCell(colNum);
cell.setCellValue(rows.get(rowIndex)[colNum]);
cell.setCellStyle(style);
}
rowIndex++;
}
}
/**
* Binary DB excel download
* @param bianrySearchBean
* @return
* @throws IOException
* @throws InvalidFormatException
*/
private static String getBinaryDBLogExcel(List<BinaryAnalysisResult> list) throws InvalidFormatException, IOException {
Workbook wb = null;
Sheet sheet1 = null;
FileInputStream inFile=null;
// download file name
String downloadFileName = "FOSSLight-BinaryDBLog"; // Default
try {
inFile= new FileInputStream(new File(downloadpath+"/BinaryDBLog.xlsx"));
wb = WorkbookFactory.create(inFile);
sheet1 = wb.getSheetAt(0);
if (list != null){
List<String[]> rowDatas = new ArrayList<>();
for (BinaryAnalysisResult bean : list) {
String[] rowParam = {
bean.getActionId()
, bean.getActionType()
, avoidNull(bean.getBinaryName())
, avoidNull(bean.getFilePath())
, avoidNull(bean.getSourcePath())
, avoidNull(bean.getCheckSum())
, avoidNull(bean.getTlsh())
, avoidNull(bean.getOssName())
, avoidNull(bean.getOssVersion())
, avoidNull(bean.getLicense())
, avoidNull(bean.getParentname())
, avoidNull(bean.getPlatformname())
, avoidNull(bean.getPlatformversion())
, avoidNull(bean.getUpdatedate())
, avoidNull(bean.getCreatedDate())
, avoidNull(bean.getModifier())
, avoidNull(bean.getComment())
};
rowDatas.add(rowParam);
}
makeSheet(sheet1, rowDatas);
}
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName);
}
/**
* SPDX Spread sheet 생성
* @param dataStr
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
private static String getVerificationSPDX_SpreadSheetExcelPost(String dataStr) throws IOException {
Workbook wb = null;
Sheet sheetDoc = null; // Document info
Sheet sheetPackage = null; // Package Info
Sheet sheetLicense = null; // Extracted License Info
Sheet sheetPerFile = null; // Per File Info
Sheet sheetRelationships = null; // Relationships
FileInputStream inFile=null;
// download file name
String downloadFileName = "SPDXRdf-"; // Default
Type ossNoticeType = new TypeToken<OssNotice>(){}.getType();
OssNotice ossNotice = (OssNotice) fromJson(dataStr, ossNoticeType);
ossNotice.setFileType("text");
String prjId = ossNotice.getPrjId();
try {
inFile= new FileInputStream(new File(downloadpath+"/SPDXRdf_2.2.2.xls"));
wb = WorkbookFactory.create(inFile);
sheetDoc = wb.getSheetAt(0);
sheetPackage = wb.getSheetAt(1);
sheetLicense = wb.getSheetAt(3);
sheetPerFile = wb.getSheetAt(4);
sheetRelationships = wb.getSheetAt(5);
String createdTime = CommonFunction.getCurrentDateTime("yyyyMMddhhmm");
String createdTimeFull = CommonFunction.getCurrentDateTime("yyyy-MM-dd hh:mm:ss");
Date createdDateTime = DateUtil.getCurrentDate();
Project projectInfo = new Project();
projectInfo.setPrjId(prjId);
projectInfo = projectService.getProjectDetail(projectInfo);
projectInfo.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
List<OssComponents> dependenciesDataList = projectService.getDependenciesDataList(projectInfo);
Map<String, Object> relationshipsMap = new HashMap<>();
T2Users userInfo = new T2Users();
userInfo.setUserId(projectInfo.getCreator());
Map<String, Object> packageInfo = verificationService.getNoticeHtmlInfo(ossNotice);
String strPrjName = projectInfo.getPrjName();
if (!isEmpty(projectInfo.getPrjVersion())) {
strPrjName += "-" + projectInfo.getPrjVersion();
}
downloadFileName += FileUtil.makeValidFileName(strPrjName, "_").replaceAll(" ", "").replaceAll("--", "-");
List<String> packageInfoidentifierList = new ArrayList<>();
//Document Info
{
Row row = sheetDoc.getRow(1);
int cellIdx = 0;
// Spreadsheet Version
cellIdx ++;
// SPDX Version
cellIdx ++;
// Data License
cellIdx ++;
// SPDX Identifier
cellIdx++;
// License List Version
cellIdx ++;
// Document Name
Cell cellDocumentName = getCell(row, cellIdx); cellIdx++;
cellDocumentName.setCellValue(strPrjName);
// Document Namespace
Cell cellDocumentNamespace = getCell(row, cellIdx); cellIdx++;
String spdxidentifier = "SPDXRef-" + strPrjName.replaceAll(" ", "") + "-" + createdTime;
String domain = CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org/");
if (!domain.endsWith("/")) {
domain += "/";
}
cellDocumentNamespace.setCellValue(domain + spdxidentifier);
// Document Contents
cellIdx++;
//External Document References
cellIdx ++;
// Document Comment
cellIdx ++;
// Creator
Cell cellCreator = getCell(row, cellIdx); cellIdx++;
String strCreator = "Person: ";
userInfo = userService.getUser(userInfo);
strCreator += projectInfo.getCreator() + " (" + userInfo.getEmail() + ")";
cellCreator.setCellValue(strCreator);
// Created
Cell cellCreated = getCell(row, cellIdx); cellIdx++;
cellCreated.setCellValue(createdDateTime);
// Creator Comment
}
// Package Info
{
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
List<OssComponents> sourceList = (List<OssComponents>) packageInfo.get("disclosureObligationList");
boolean hideOssVersionFlag = CoConstDef.FLAG_YES.equals(ossNotice.getHideOssVersionYn());
if (sourceList != null && !sourceList.isEmpty()) {
noticeList.addAll(sourceList);
}
noticeList = verificationService.setMergeGridData(noticeList); // merge Data
int rowIdx = 1;
for (OssComponents bean : noticeList) {
Row row = sheetPackage.getRow(rowIdx);
if (row == null) {
row = sheetPackage.createRow(rowIdx);
}
String attributionText = "";
int cellIdx = 0;
// Package Name
Cell cellPackageName = getCell(row, cellIdx); cellIdx++;
cellPackageName.setCellValue(bean.getOssName());
// SPDX Identifier
Cell cellSPDXIdentifier = getCell(row, cellIdx); cellIdx++;
String ossName = bean.getOssName().replace("'", "\'"); // ossName에 '가 들어갈 경우 정상적으로 oss Info를 찾지 못하는 증상이 발생하여 현재 값으로 치환.
String relationshipsKey = (ossName + "(" + avoidNull(bean.getOssVersion()) + ")").toUpperCase();
String spdxRefId = "";
if (ossName.equals("-")) {
spdxRefId = "SPDXRef-File-" + bean.getComponentId();
cellSPDXIdentifier.setCellValue("SPDXRef-File-" + bean.getComponentId());
packageInfoidentifierList.add("SPDXRef-File-" + bean.getComponentId());
} else {
spdxRefId = "SPDXRef-Package-" + bean.getOssId();
cellSPDXIdentifier.setCellValue("SPDXRef-Package-" + bean.getOssId());
packageInfoidentifierList.add("SPDXRef-Package-" + bean.getOssId());
}
relationshipsMap.put(relationshipsKey, spdxRefId);
// Package Version
Cell cellPackageVersion = getCell(row, cellIdx); cellIdx++;
cellPackageVersion.setCellValue(hideOssVersionFlag ? "" : avoidNull(bean.getOssVersion()));
// Package FileName
cellIdx++;
// Package Supplier
Cell packageSupplier = getCell(row, cellIdx); cellIdx++;
packageSupplier.setCellValue("Person: \"\"");
// Package Originator
Cell packageOriginator = getCell(row, cellIdx); cellIdx++;
packageOriginator.setCellValue("Organization: \"\"");
// Home Page
Cell cellHomePage = getCell(row, cellIdx); cellIdx++;
cellHomePage.setCellValue(avoidNull(bean.getHomepage()));
// Package Download Location
Cell cellPackageDownloadLocation = getCell(row, cellIdx); cellIdx++;
String downloadLocation = bean.getDownloadLocation();
if (isEmpty(downloadLocation)) {
downloadLocation = "NONE";
}
// Invalid download location is output as NONE
if (SpdxVerificationHelper.verifyDownloadLocation(downloadLocation) != null) {
downloadLocation = "NONE";
}
cellPackageDownloadLocation.setCellValue(downloadLocation);
// Package Checksum
cellIdx++;
// Package Verification Code
cellIdx++;
// Verification Code Excluded Files
cellIdx++;
// Source Info
cellIdx++;
// License Declared
Cell cellLicenseDeclared = getCell(row, cellIdx); cellIdx++;
OssMaster _ossBean = null;
if (ossName.equals("-")) {
String licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = bean.getAttribution();
} else {
_ossBean = CoCodeManager.OSS_INFO_UPPER.get( (ossName + "_" + avoidNull(bean.getOssVersion())).toUpperCase());
String licenseStr = CommonFunction.makeLicenseExpression(_ossBean.getOssLicenses(), false, true);
if (licenseStr.contains("LicenseRef-")) licenseStr = CommonFunction.removeSpecialCharacters(licenseStr, false).replaceAll("\\(", "-").replaceAll("\\)", "");
if (_ossBean.getOssLicenses().size() > 1) {
licenseStr = "(" + licenseStr + ")";
}
cellLicenseDeclared.setCellValue(CommonFunction.licenseStrToSPDXLicenseFormat(licenseStr));
attributionText = avoidNull(_ossBean.getAttribution()); // oss attribution
}
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
liBean.setLicenseName(liMaster.getShortIdentifier());
} else {
liBean.setLicenseName("LicenseRef-" + liBean.getLicenseName());
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution()); // license attribution
}
if (liBean.getLicenseName().startsWith("LicenseRef-")) {
liBean.setLicenseName(CommonFunction.removeSpecialCharacters(liBean.getLicenseName(), true).replaceAll("\\(", "-").replaceAll("\\)", ""));
}
srtLicenseName += liBean.getLicenseName();
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(CommonFunction.licenseStrToSPDXLicenseFormat(srtLicenseName));
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
if (ossName.equals("-")) {
licenseInfoFromFiles.setCellValue(CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName()));
} else {
licenseInfoFromFiles.setCellValue(CommonFunction.makeLicenseFromFiles(_ossBean, true)); // Declared & Detected License Info (중복제거)
}
// License Comments
cellIdx++;
// Package Copyright Text
Cell cellPackageCopyrightText = getCell(row, cellIdx); cellIdx++;
String copyrightText = StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762);
if (copyrightText.isEmpty() || copyrightText.equals("-")) {
copyrightText = "NOASSERTION";
}
cellPackageCopyrightText.setCellValue(copyrightText);
// Summary
cellIdx++;
// Description
cellIdx++;
// Attribution Text
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(hideOssVersionFlag ? bean.getOssAttribution().replaceAll("<br>", "\n") : attributionText);
// Files Analyzed
Cell filesAnalyzed = getCell(row, cellIdx); cellIdx++;
filesAnalyzed.setCellValue("false");
// User Defined Columns...
rowIdx++;
}
}
// Extracted License Info
{
// BOM에 사용된 OSS Info중 License identifier가 설정되어 있지 않은 license 정보만 출력한다.
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
Map<String, LicenseMaster> nonIdetifierNoticeList = new HashMap<>();
for (OssComponents ocBean : noticeList) {
String ossName = ocBean.getOssName().replace("'", "\'");
List<String> licenseList = new ArrayList<>();
if (ossName.equals("-")) {
licenseList = Arrays.asList(ocBean.getLicenseName());
} else {
OssMaster _ossBean = CoCodeManager.OSS_INFO_UPPER.get((ossName + "_" + avoidNull(ocBean.getOssVersion())).toUpperCase());
licenseList = Arrays.asList(CommonFunction.makeLicenseFromFiles(_ossBean, false).split(","));
}
for (String licenseNm : licenseList) {
LicenseMaster lmBean = CoCodeManager.LICENSE_INFO.get(licenseNm);
if (lmBean != null && isEmpty(lmBean.getShortIdentifier()) && !nonIdetifierNoticeList.containsKey(lmBean.getLicenseId())) {
nonIdetifierNoticeList.put(lmBean.getLicenseId(), lmBean);
}
}
}
int rowIdx = 1;
for (LicenseMaster bean : nonIdetifierNoticeList.values()) {
int cellIdx = 0;
Row row = sheetLicense.getRow(rowIdx);
if (row == null) {
row = sheetLicense.createRow(rowIdx);
}
String _licenseName = bean.getLicenseNameTemp().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-");
// Identifier
Cell cellIdentifier = getCell(row, cellIdx); cellIdx++;
cellIdentifier.setCellValue("LicenseRef-" + _licenseName);
// Extracted Text
Cell cellExtractedText = getCell(row, cellIdx); cellIdx++;
cellExtractedText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getLicenseText()), 0, 32762) );
// License Name
Cell cellLicenseName = getCell(row, cellIdx); cellIdx++;
cellLicenseName.setCellValue(bean.getLicenseNameTemp());
// Cross Reference URLs
Cell cellCrossReferenceURLs = getCell(row, cellIdx); cellIdx++;
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
cellCrossReferenceURLs.setCellValue(avoidNull(CommonFunction.makeLicenseInternalUrl(bean, distributionFlag)));
// Comment
rowIdx ++;
}
}
// Per File Info sheet
{
// oss name이 "-" 인 case 만
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("addOssComponentList");
List<OssComponents> nonIdetifierNoticeList = new ArrayList<>();
for (OssComponents bean : noticeList) {
// set false because "Per file info sheet" is not currently output
if ("-".equals(bean.getOssName()) && false) {
nonIdetifierNoticeList.add(bean);
}
}
int rowIdx = 1;
for (OssComponents bean : nonIdetifierNoticeList) {
int cellIdx = 0;
String attributionText = "";
Row row = sheetPerFile.getRow(rowIdx);
if (row == null) {
row = sheetPerFile.createRow(rowIdx);
}
// File Name
Cell fileName = getCell(row, cellIdx); cellIdx++;
fileName.setCellValue(avoidNull(bean.getFilePath(), "./"));
// SPDX Identifier
Cell sPDXIdentifier = getCell(row, cellIdx); cellIdx++;
sPDXIdentifier.setCellValue("SPDXRef-File-" + bean.getComponentId());
// Package Identifier
cellIdx++;
// File Type(s)
Cell fileType = getCell(row, cellIdx); cellIdx++;
fileType.setCellValue("SOURCE");
// File Checksum(s)
cellIdx++;
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
liBean.setLicenseName(liMaster.getShortIdentifier());
} else {
liBean.setLicenseName("LicenseRef-" + liBean.getLicenseName());
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution());
}
liBean.setLicenseName(liBean.getLicenseName().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-"));
srtLicenseName += liBean.getLicenseName();
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(srtLicenseName);
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
licenseInfoFromFiles.setCellValue(srtLicenseName); // License Concluded 란과 동일한 값으로 표시
// License Comments
cellIdx++;
// File Copyright Text
Cell fileCopyrightText = getCell(row, cellIdx); cellIdx++;
fileCopyrightText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762) );
// Notice Text
cellIdx++;
// Artifact of Project
cellIdx++;
// Artifact of Homepage
cellIdx++;
// Artifact of URL
cellIdx++;
// Contributors
cellIdx++;
// File Comment
cellIdx++;
// File Dependencies
cellIdx++;
// Attrinbution Info
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(attributionText);
// User Defined Columns...
cellIdx++;
rowIdx ++;
}
}
// sheetRelationships
{
int rowIdx = 1;
for (String _identifierB : packageInfoidentifierList) {
int cellIdx = 0;
Row row = sheetRelationships.getRow(rowIdx);
if (row == null) {
row = sheetRelationships.createRow(rowIdx);
}
// SPDX Identifier A
Cell spdxIdentifierA = getCell(row, cellIdx); cellIdx++;
spdxIdentifierA.setCellValue("SPDXRef-DOCUMENT");
// Relationship
Cell relationship = getCell(row, cellIdx); cellIdx++;
relationship.setCellValue("DESCRIBES");
// SPDX Identifier B
Cell spdxIdentifierB = getCell(row, cellIdx); cellIdx++;
spdxIdentifierB.setCellValue(_identifierB);
rowIdx++;
}
for (OssComponents oss : dependenciesDataList) {
String key = (oss.getOssName() + "(" + oss.getOssVersion() + ")").toUpperCase();
if (relationshipsMap.containsKey(key)) {
String spdxElementId = (String) relationshipsMap.get(key);
String[] dependencies = oss.getDependencies().split(",");
for (String dependency : dependencies) {
String relatedSpdxElementKey = dependency.toUpperCase();
if (relationshipsMap.containsKey(relatedSpdxElementKey)) {
String relatedSpdxElement = (String) relationshipsMap.get(relatedSpdxElementKey);
int cellIdx = 0;
Row row = sheetRelationships.getRow(rowIdx);
if (row == null) {
row = sheetRelationships.createRow(rowIdx);
}
// SPDX Identifier A
Cell spdxIdentifierA = getCell(row, cellIdx); cellIdx++;
spdxIdentifierA.setCellValue(spdxElementId);
// Relationship
Cell relationship = getCell(row, cellIdx); cellIdx++;
relationship.setCellValue("DEPENDS_ON");
// SPDX Identifier B
Cell spdxIdentifierB = getCell(row, cellIdx); cellIdx++;
spdxIdentifierB.setCellValue(relatedSpdxElement);
rowIdx++;
}
}
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName, "xls");
}
@SuppressWarnings("unchecked")
private static String getSBOMSPDX_SpreadSheetExcelPost(String dataStr) throws IOException {
Workbook wb = null;
Sheet sheetDoc = null; // Document info
Sheet sheetPackage = null; // Package Info
Sheet sheetLicense = null; // Extracted License Info
Sheet sheetPerFile = null; // Per File Info
Sheet sheetRelationships = null; // Relationships
FileInputStream inFile=null;
// download file name
String downloadFileName = "SPDXRdf-"; // Default
String prjId = dataStr;
boolean thirdPartyCheckFlag = false;
if (prjId.startsWith("3rd_")) {
thirdPartyCheckFlag = true;
String[] prjIdSplit = dataStr.split("_");
prjId = prjIdSplit[1];
}
OssNotice ossNotice = new OssNotice();
ossNotice.setPrjId(dataStr);
ossNotice.setFileType("text");
try {
inFile= new FileInputStream(new File(downloadpath+"/SPDXRdf_2.2.2.xls"));
wb = WorkbookFactory.create(inFile);
sheetDoc = wb.getSheetAt(0);
sheetPackage = wb.getSheetAt(1);
sheetLicense = wb.getSheetAt(3);
sheetPerFile = wb.getSheetAt(4);
sheetRelationships = wb.getSheetAt(5);
String createdTime = CommonFunction.getCurrentDateTime("yyyyMMddhhmm");
String createdTimeFull = CommonFunction.getCurrentDateTime("yyyy-MM-dd hh:mm:ss");
Date createdDateTime = DateUtil.getCurrentDate();
List<OssComponents> dependenciesDataList = null;
Map<String, Object> packageInfo = null;
Map<String, Object> relationshipsMap = new HashMap<>();
String strPrjName = "";
String creator = "";
T2Users userInfo = new T2Users();
if (!thirdPartyCheckFlag) {
Project projectInfo = new Project();
projectInfo.setPrjId(prjId);
projectInfo = projectService.getProjectDetail(projectInfo);
creator = projectInfo.getCreator();
strPrjName = projectInfo.getPrjName();
if (!isEmpty(projectInfo.getPrjVersion())) {
strPrjName += "-" + projectInfo.getPrjVersion();
}
packageInfo = projectService.getExportDataForSBOMInfo(ossNotice);
projectInfo.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
dependenciesDataList = projectService.getDependenciesDataList(projectInfo);
} else {
PartnerMaster partner = new PartnerMaster();
partner.setPartnerId(prjId);
partner = partnerService.getPartnerMasterOne(partner);
creator = partner.getCreator();
strPrjName = partner.getPartnerName();
packageInfo = partnerService.getExportDataForSbomInfo(partner);
}
userInfo.setUserId(creator);
downloadFileName += FileUtil.makeValidFileName(strPrjName, "_").replaceAll(" ", "").replaceAll("--", "-");
List<String> packageInfoidentifierList = new ArrayList<>();
//Document Info
{
Row row = sheetDoc.getRow(1);
int cellIdx = 0;
// Spreadsheet Version
cellIdx ++;
// SPDX Version
cellIdx ++;
// Data License
cellIdx ++;
// SPDX Identifier
cellIdx++;
// License List Version
cellIdx ++;
// Document Name
Cell cellDocumentName = getCell(row, cellIdx); cellIdx++;
cellDocumentName.setCellValue(strPrjName);
// Document Namespace
Cell cellDocumentNamespace = getCell(row, cellIdx); cellIdx++;
String spdxidentifier = "SPDXRef-" + strPrjName.replaceAll(" ", "") + "-" + createdTime;
String domain = CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org/");
if (!domain.endsWith("/")) {
domain += "/";
}
cellDocumentNamespace.setCellValue(domain + spdxidentifier);
// Document Contents
cellIdx++;
//External Document References
cellIdx ++;
// Document Comment
cellIdx ++;
// Creator
Cell cellCreator = getCell(row, cellIdx); cellIdx++;
String strCreator = "Person: ";
userInfo = userService.getUser(userInfo);
strCreator += creator + " (" + userInfo.getEmail() + ")";
cellCreator.setCellValue(strCreator);
// Created
Cell cellCreated = getCell(row, cellIdx); cellIdx++;
cellCreated.setCellValue(createdDateTime);
// Creator Comment
}
// Package Info
{
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
List<OssComponents> sourceList = (List<OssComponents>) packageInfo.get("disclosureObligationList");
boolean hideOssVersionFlag = CoConstDef.FLAG_YES.equals(ossNotice.getHideOssVersionYn());
if (sourceList != null && !sourceList.isEmpty()) {
noticeList.addAll(sourceList);
}
if (packageInfo.containsKey("notObligationList")) {
List<OssComponents> notObligationList = (List<OssComponents>) packageInfo.get("notObligationList");
if (notObligationList != null && !notObligationList.isEmpty()) {
noticeList.addAll(notObligationList);
}
}
noticeList = verificationService.setMergeGridData(noticeList); // merge Data
int rowIdx = 1;
for (OssComponents bean : noticeList) {
Row row = sheetPackage.getRow(rowIdx);
if (row == null) {
row = sheetPackage.createRow(rowIdx);
}
String attributionText = "";
int cellIdx = 0;
// Package Name
Cell cellPackageName = getCell(row, cellIdx); cellIdx++;
cellPackageName.setCellValue(bean.getOssName());
// SPDX Identifier
Cell cellSPDXIdentifier = getCell(row, cellIdx); cellIdx++;
String ossName = bean.getOssName().replace("'", "\'");
String relationshipsKey = (ossName + "(" + avoidNull(bean.getOssVersion()) + ")").toUpperCase();
String spdxRefId = "";
if (ossName.equals("-") || (bean.getOssId() == null || bean.getOssId().isEmpty())) {
spdxRefId = "SPDXRef-File-";
} else {
spdxRefId = "SPDXRef-Package-";
}
spdxRefId += bean.getComponentId();
cellSPDXIdentifier.setCellValue(spdxRefId);
packageInfoidentifierList.add(spdxRefId);
relationshipsMap.put(relationshipsKey, spdxRefId);
// Package Version
Cell cellPackageVersion = getCell(row, cellIdx); cellIdx++;
cellPackageVersion.setCellValue(hideOssVersionFlag ? "" : avoidNull(bean.getOssVersion()));
// Package FileName
cellIdx++;
// Package Supplier
Cell packageSupplier = getCell(row, cellIdx); cellIdx++;
packageSupplier.setCellValue("Person: \"\"");
// Package Originator
Cell packageOriginator = getCell(row, cellIdx); cellIdx++;
packageOriginator.setCellValue("Organization: \"\"");
// Home Page
Cell cellHomePage = getCell(row, cellIdx); cellIdx++;
cellHomePage.setCellValue(avoidNull(bean.getHomepage()));
// Package Download Location
Cell cellPackageDownloadLocation = getCell(row, cellIdx); cellIdx++;
String downloadLocation = bean.getDownloadLocation();
if (isEmpty(downloadLocation)) {
downloadLocation = "NONE";
}
// Invalid download location is output as NONE
if (SpdxVerificationHelper.verifyDownloadLocation(downloadLocation) != null) {
downloadLocation = "NONE";
}
cellPackageDownloadLocation.setCellValue(downloadLocation);
// Package Checksum
cellIdx++;
// Package Verification Code
cellIdx++;
// Verification Code Excluded Files
cellIdx++;
// Source Info
cellIdx++;
// License Declared
Cell cellLicenseDeclared = getCell(row, cellIdx); cellIdx++;
OssMaster _ossBean = null;
if (ossName.equals("-")) {
String licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
cellLicenseDeclared.setCellValue(CommonFunction.removeSpecialCharacters(licenseStr, true).replaceAll("\\(", "-").replaceAll("\\)", ""));
attributionText = bean.getAttribution();
} else {
_ossBean = CoCodeManager.OSS_INFO_UPPER.get( (ossName + "_" + avoidNull(bean.getOssVersion())).toUpperCase());
if (_ossBean != null) {
String licenseStr = CommonFunction.makeLicenseExpression(_ossBean.getOssLicenses(), false, true);
licenseStr = CommonFunction.removeSpecialCharacters(licenseStr, false).replaceAll("\\(", "-").replaceAll("\\)", "");
if (_ossBean.getOssLicenses().size() > 1) {
licenseStr = "(" + licenseStr + ")";
}
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = avoidNull(_ossBean.getAttribution()); // oss attribution
} else {
boolean multiFlag = false;
String licenseStr = "";
if (bean.getLicenseName().contains(",")) {
multiFlag = true;
for (String license : bean.getLicenseName().split(",")) {
if (!isEmpty(license)) {
licenseStr += " AND ";
}
String licenseName = "";
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(license).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(license).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
licenseName = liMaster.getShortIdentifier();
} else {
licenseName = "LicenseRef-" + license;
}
} else {
licenseName = "LicenseRef-" + license;
}
if (licenseName.startsWith("LicenseRef-")) {
licenseName = CommonFunction.removeSpecialCharacters(licenseName, true).replaceAll("\\(", "-").replaceAll("\\)", "");
}
licenseStr += licenseName;
}
} else {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(bean.getLicenseName()).toUpperCase())) {
licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
} else {
licenseStr = "LicenseRef-" + CommonFunction.removeSpecialCharacters(bean.getLicenseName(), true).replaceAll("\\(", "-").replaceAll("\\)", "");
}
}
if (multiFlag) licenseStr = "(" + licenseStr + ")";
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = bean.getAttribution();
}
}
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
String licenseName = "";
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
licenseName = liMaster.getShortIdentifier();
} else {
licenseName = "LicenseRef-" + liBean.getLicenseName();
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution()); // license attribution
} else {
licenseName = "LicenseRef-" + liBean.getLicenseName();
}
if (licenseName.startsWith("LicenseRef-")) {
licenseName = CommonFunction.removeSpecialCharacters(licenseName, true).replaceAll("\\(", "-").replaceAll("\\)", "");
}
srtLicenseName += licenseName;
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(srtLicenseName);
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
if (ossName.equals("-")) {
licenseInfoFromFiles.setCellValue(CommonFunction.licenseStrToSPDXLicenseFormat(CommonFunction.removeSpecialCharacters(bean.getLicenseName(), true).replaceAll("\\(", "-").replaceAll("\\)", "")));
} else if (_ossBean != null) {
String licenseInfo = CommonFunction.makeLicenseFromFiles(_ossBean, true);
licenseInfoFromFiles.setCellValue(licenseInfo);
} else {
licenseInfoFromFiles.setCellValue(""); // OSS Info가 없으므로 빈값이 들어감.
}
// License Comments
cellIdx++;
// Package Copyright Text
Cell cellPackageCopyrightText = getCell(row, cellIdx); cellIdx++;
String copyrightText = StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762);
if (copyrightText.isEmpty() || copyrightText.equals("-")) {
copyrightText = "NOASSERTION";
}
cellPackageCopyrightText.setCellValue(copyrightText);
// Summary
cellIdx++;
// Description
cellIdx++;
// Attribution Text
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(hideOssVersionFlag ? bean.getOssAttribution().replaceAll("<br>", "\n") : attributionText);
// Files Analyzed
Cell filesAnalyzed = getCell(row, cellIdx); cellIdx++;
filesAnalyzed.setCellValue("false");
// User Defined Columns...
rowIdx++;
}
}
// Extracted License Info
{
// BOM에 사용된 OSS Info중 License identifier가 설정되어 있지 않은 license 정보만 출력한다.
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
Map<String, LicenseMaster> nonIdetifierNoticeList = new HashMap<>();
for (OssComponents ocBean : noticeList) {
String ossName = ocBean.getOssName().replace("'", "\'");
List<String> licenseList = new ArrayList<>();
if (ossName.equals("-")) {
licenseList = Arrays.asList(ocBean.getLicenseName());
} else {
OssMaster _ossBean = CoCodeManager.OSS_INFO_UPPER.get((ossName + "_" + avoidNull(ocBean.getOssVersion())).toUpperCase());
licenseList = Arrays.asList(CommonFunction.makeLicenseFromFiles(_ossBean, false).split(","));
}
for (String licenseNm : licenseList) {
LicenseMaster lmBean = CoCodeManager.LICENSE_INFO.get(licenseNm);
if (lmBean != null && isEmpty(lmBean.getShortIdentifier()) && !nonIdetifierNoticeList.containsKey(lmBean.getLicenseId())) {
nonIdetifierNoticeList.put(lmBean.getLicenseId(), lmBean);
}
}
}
int rowIdx = 1;
for (LicenseMaster bean : nonIdetifierNoticeList.values()) {
int cellIdx = 0;
Row row = sheetLicense.getRow(rowIdx);
if (row == null) {
row = sheetLicense.createRow(rowIdx);
}
String _licenseName = bean.getLicenseNameTemp().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-");
// Identifier
Cell cellIdentifier = getCell(row, cellIdx); cellIdx++;
cellIdentifier.setCellValue("LicenseRef-" + _licenseName);
// Extracted Text
Cell cellExtractedText = getCell(row, cellIdx); cellIdx++;
cellExtractedText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getLicenseText()), 0, 32762) );
// License Name
Cell cellLicenseName = getCell(row, cellIdx); cellIdx++;
cellLicenseName.setCellValue(bean.getLicenseNameTemp());
// Cross Reference URLs
Cell cellCrossReferenceURLs = getCell(row, cellIdx); cellIdx++;
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
cellCrossReferenceURLs.setCellValue(avoidNull(CommonFunction.makeLicenseInternalUrl(bean, distributionFlag)));
// Comment
rowIdx ++;
}
}
// Per File Info sheet
{
// oss name이 "-" 인 case 만
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("addOssComponentList");
List<OssComponents> nonIdetifierNoticeList = new ArrayList<>();
for (OssComponents bean : noticeList) {
// set false because "Per file info sheet" is not currently output
if ("-".equals(bean.getOssName()) && false) {
nonIdetifierNoticeList.add(bean);
}
}
int rowIdx = 1;
for (OssComponents bean : nonIdetifierNoticeList) {
int cellIdx = 0;
String attributionText = "";
Row row = sheetPerFile.getRow(rowIdx);
if (row == null) {
row = sheetPerFile.createRow(rowIdx);
}
// File Name
Cell fileName = getCell(row, cellIdx); cellIdx++;
fileName.setCellValue(avoidNull(bean.getFilePath(), "./"));
// SPDX Identifier
Cell sPDXIdentifier = getCell(row, cellIdx); cellIdx++;
sPDXIdentifier.setCellValue("SPDXRef-File-" + bean.getComponentId());
// Package Identifier
cellIdx++;
// File Type(s)
Cell fileType = getCell(row, cellIdx); cellIdx++;
fileType.setCellValue("SOURCE");
// File Checksum(s)
cellIdx++;
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
liBean.setLicenseName(liMaster.getShortIdentifier());
} else {
liBean.setLicenseName("LicenseRef-" + liBean.getLicenseName());
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution());
}
liBean.setLicenseName(liBean.getLicenseName().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-"));
srtLicenseName += liBean.getLicenseName();
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(srtLicenseName);
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
licenseInfoFromFiles.setCellValue(srtLicenseName); // License Concluded 란과 동일한 값으로 표시
// License Comments
cellIdx++;
// File Copyright Text
Cell fileCopyrightText = getCell(row, cellIdx); cellIdx++;
fileCopyrightText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762) );
// Notice Text
cellIdx++;
// Artifact of Project
cellIdx++;
// Artifact of Homepage
cellIdx++;
// Artifact of URL
cellIdx++;
// Contributors
cellIdx++;
// File Comment
cellIdx++;
// File Dependencies
cellIdx++;
// Attrinbution Info
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(attributionText);
// User Defined Columns...
cellIdx++;
rowIdx ++;
}
}
// sheetRelationships
{
int rowIdx = 1;
for (String _identifierB : packageInfoidentifierList) {
int cellIdx = 0;
Row row = sheetRelationships.getRow(rowIdx);
if (row == null) {
row = sheetRelationships.createRow(rowIdx);
}
// SPDX Identifier A
Cell spdxIdentifierA = getCell(row, cellIdx); cellIdx++;
spdxIdentifierA.setCellValue("SPDXRef-DOCUMENT");
// Relationship
Cell relationship = getCell(row, cellIdx); cellIdx++;
relationship.setCellValue("DESCRIBES");
// SPDX Identifier B
Cell spdxIdentifierB = getCell(row, cellIdx); cellIdx++;
spdxIdentifierB.setCellValue(_identifierB);
rowIdx++;
}
for (OssComponents oss : dependenciesDataList) {
String key = (oss.getOssName() + "(" + oss.getOssVersion() + ")").toUpperCase();
if (relationshipsMap.containsKey(key)) {
String spdxElementId = (String) relationshipsMap.get(key);
String[] dependencies = oss.getDependencies().split(",");
for (String dependency : dependencies) {
String relatedSpdxElementKey = dependency.toUpperCase();
if (relationshipsMap.containsKey(relatedSpdxElementKey)) {
String relatedSpdxElement = (String) relationshipsMap.get(relatedSpdxElementKey);
int cellIdx = 0;
Row row = sheetRelationships.getRow(rowIdx);
if (row == null) {
row = sheetRelationships.createRow(rowIdx);
}
// SPDX Identifier A
Cell spdxIdentifierA = getCell(row, cellIdx); cellIdx++;
spdxIdentifierA.setCellValue(spdxElementId);
// Relationship
Cell relationship = getCell(row, cellIdx); cellIdx++;
relationship.setCellValue("DEPENDS_ON");
// SPDX Identifier B
Cell spdxIdentifierB = getCell(row, cellIdx); cellIdx++;
spdxIdentifierB.setCellValue(relatedSpdxElement);
rowIdx++;
}
}
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName, "xls");
}
@SuppressWarnings("unchecked")
private static String getSelfCheckSPDX_SpreadSheetExcelPost(String dataStr) throws IOException {
Workbook wb = null;
Sheet sheetDoc = null; // Document info
Sheet sheetPackage = null; // Package Info
Sheet sheetLicense = null; // Extracted License Info
Sheet sheetPerFile = null; // Per File Info
Sheet sheetRelationships = null; // Relationships
FileInputStream inFile=null;
// download file name
String downloadFileName = "SPDXRdf-"; // Default
Type ossNoticeType = new TypeToken<OssNotice>(){}.getType();
OssNotice ossNotice = (OssNotice) fromJson(dataStr, ossNoticeType);
ossNotice.setFileType("text");
String prjId = ossNotice.getPrjId();
try {
inFile= new FileInputStream(new File(downloadpath+"/SPDXRdf_2.2.2.xls"));
wb = WorkbookFactory.create(inFile);
sheetDoc = wb.getSheetAt(0);
sheetPackage = wb.getSheetAt(1);
sheetLicense = wb.getSheetAt(3);
sheetPerFile = wb.getSheetAt(4);
sheetRelationships = wb.getSheetAt(5);
String createdTime = CommonFunction.getCurrentDateTime("yyyyMMddhhmm");
String createdTimeFull = CommonFunction.getCurrentDateTime("yyyy-MM-dd hh:mm:ss");
Date createdDateTime = DateUtil.getCurrentDate();
Project projectInfo = new Project();
projectInfo.setPrjId(prjId);
projectInfo = selfCheckService.getProjectDetail(projectInfo);
T2Users userInfo = new T2Users();
userInfo.setUserId(projectInfo.getCreator());
Map<String, Object> packageInfo = selfCheckService.getExportDataForSBOMInfo(ossNotice);
String strPrjName = projectInfo.getPrjName();
if (!isEmpty(projectInfo.getPrjVersion())) {
strPrjName += "-" + projectInfo.getPrjVersion();
}
downloadFileName += FileUtil.makeValidFileName(strPrjName, "_").replaceAll(" ", "").replaceAll("--", "-");
List<String> packageInfoidentifierList = new ArrayList<>();
//Document Info
{
Row row = sheetDoc.getRow(1);
int cellIdx = 0;
// Spreadsheet Version
cellIdx ++;
// SPDX Version
cellIdx ++;
// Data License
cellIdx ++;
// SPDX Identifier
cellIdx++;
// License List Version
cellIdx ++;
// Document Name
Cell cellDocumentName = getCell(row, cellIdx); cellIdx++;
cellDocumentName.setCellValue(strPrjName);
// Document Namespace
Cell cellDocumentNamespace = getCell(row, cellIdx); cellIdx++;
String spdxidentifier = "SPDXRef-" + strPrjName.replaceAll(" ", "") + "-" + createdTime;
String domain = CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org/");
if (!domain.endsWith("/")) {
domain += "/";
}
cellDocumentNamespace.setCellValue(domain + spdxidentifier);
// Document Contents
cellIdx++;
//External Document References
cellIdx ++;
// Document Comment
cellIdx ++;
// Creator
Cell cellCreator = getCell(row, cellIdx); cellIdx++;
String strCreator = "Person: ";
userInfo = userService.getUser(userInfo);
strCreator += projectInfo.getCreator() + " (" + userInfo.getEmail() + ")";
cellCreator.setCellValue(strCreator);
// Created
Cell cellCreated = getCell(row, cellIdx); cellIdx++;
cellCreated.setCellValue(createdDateTime);
// Creator Comment
}
// Package Info
{
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
List<OssComponents> sourceList = (List<OssComponents>) packageInfo.get("disclosureObligationList");
boolean hideOssVersionFlag = CoConstDef.FLAG_YES.equals(ossNotice.getHideOssVersionYn());
// permissive oss와 copyleft oss를 병합
if (sourceList != null && !sourceList.isEmpty()) {
noticeList.addAll(sourceList);
}
if (packageInfo.containsKey("notObligationList")) {
List<OssComponents> notObligationList = (List<OssComponents>) packageInfo.get("notObligationList");
if (notObligationList != null && !notObligationList.isEmpty()) {
noticeList.addAll(notObligationList);
}
}
noticeList = selfCheckService.setMergeGridData(noticeList); // merge Data
int rowIdx = 1;
for (OssComponents bean : noticeList) {
Row row = sheetPackage.getRow(rowIdx);
if (row == null) {
row = sheetPackage.createRow(rowIdx);
}
String attributionText = "";
int cellIdx = 0;
// Package Name
Cell cellPackageName = getCell(row, cellIdx); cellIdx++;
cellPackageName.setCellValue(bean.getOssName());
// SPDX Identifier
Cell cellSPDXIdentifier = getCell(row, cellIdx); cellIdx++;
String ossName = bean.getOssName().replace("'", "\'"); // ossName에 '가 들어갈 경우 정상적으로 oss Info를 찾지 못하는 증상이 발생하여 현재 값으로 치환.
if (!isEmpty(bean.getOssId())) {
cellSPDXIdentifier.setCellValue("SPDXRef-Package-" + bean.getOssId());
packageInfoidentifierList.add("SPDXRef-Package-" + bean.getOssId());
} else {
// ossName.equals("-") or unconfirmed OSS Name || OSS Version
cellSPDXIdentifier.setCellValue("SPDXRef-File-" + bean.getComponentId());
packageInfoidentifierList.add("SPDXRef-File-" + bean.getComponentId());
}
// Package Version
Cell cellPackageVersion = getCell(row, cellIdx); cellIdx++;
cellPackageVersion.setCellValue(hideOssVersionFlag ? "" : avoidNull(bean.getOssVersion()));
// Package FileName
cellIdx++;
// Package Supplier
Cell packageSupplier = getCell(row, cellIdx); cellIdx++;
packageSupplier.setCellValue("Person: \"\"");
// Package Originator
Cell packageOriginator = getCell(row, cellIdx); cellIdx++;
packageOriginator.setCellValue("Organization: \"\"");
// Home Page
Cell cellHomePage = getCell(row, cellIdx); cellIdx++;
cellHomePage.setCellValue(avoidNull(bean.getHomepage()));
// Package Download Location
Cell cellPackageDownloadLocation = getCell(row, cellIdx); cellIdx++;
String downloadLocation = bean.getDownloadLocation();
if (downloadLocation.isEmpty()) {
downloadLocation = "NONE";
}
// Invalid download location is output as NONE
if (SpdxVerificationHelper.verifyDownloadLocation(downloadLocation) != null) {
downloadLocation = "NONE";
}
cellPackageDownloadLocation.setCellValue(downloadLocation);
// Package Checksum
cellIdx++;
// Package Verification Code
cellIdx++;
// Verification Code Excluded Files
cellIdx++;
// Source Info
cellIdx++;
// License Declared
Cell cellLicenseDeclared = getCell(row, cellIdx); cellIdx++;
OssMaster _ossBean = null;
if (ossName.equals("-")) {
String licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = bean.getAttribution();
} else {
_ossBean = CoCodeManager.OSS_INFO_UPPER.get( (ossName + "_" + avoidNull(bean.getOssVersion())).toUpperCase());
if (_ossBean != null) {
String licenseStr = CommonFunction.makeLicenseExpression(_ossBean.getOssLicenses(), false, true);
if (_ossBean.getOssLicenses().size() > 1) {
licenseStr = "(" + licenseStr + ")";
}
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = avoidNull(_ossBean.getAttribution()); // oss attribution
} else {
String licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
cellLicenseDeclared.setCellValue(licenseStr);
attributionText = bean.getAttribution();
}
}
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
liBean.setLicenseName(liMaster.getShortIdentifier());
} else {
liBean.setLicenseName("LicenseRef-" + liBean.getLicenseName());
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution()); // license attribution
}
liBean.setLicenseName(liBean.getLicenseName().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-"));
srtLicenseName += liBean.getLicenseName();
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(srtLicenseName);
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
if (ossName.equals("-")) {
licenseInfoFromFiles.setCellValue(CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName()));
} else if (_ossBean != null) {
licenseInfoFromFiles.setCellValue(CommonFunction.makeLicenseFromFiles(_ossBean, true)); // Declared & Detected License Info (중복제거)
} else {
licenseInfoFromFiles.setCellValue(""); // OSS Info가 없으므로 빈값이 들어감.
}
// License Comments
cellIdx++;
// Package Copyright Text
Cell cellPackageCopyrightText = getCell(row, cellIdx); cellIdx++;
String copyrightText = StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762);
if (copyrightText.isEmpty() || copyrightText.equals("-")) {
copyrightText = "NOASSERTION";
}
cellPackageCopyrightText.setCellValue(copyrightText);
// Summary
cellIdx++;
// Description
cellIdx++;
// Attribution Text
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(hideOssVersionFlag ? bean.getOssAttribution().replaceAll("<br>", "\n") : attributionText);
// Files Analyzed
Cell filesAnalyzed = getCell(row, cellIdx); cellIdx++;
filesAnalyzed.setCellValue("false");
// User Defined Columns...
rowIdx++;
}
}
// Extracted License Info
{
// BOM에 사용된 OSS Info중 License identifier가 설정되어 있지 않은 license 정보만 출력한다.
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
Map<String, LicenseMaster> nonIdetifierNoticeList = new HashMap<>();
for (OssComponents ocBean : noticeList) {
String ossName = ocBean.getOssName().replace("'", "\'");
List<String> licenseList = new ArrayList<>();
if (ossName.equals("-")) {
licenseList = Arrays.asList(ocBean.getLicenseName());
} else {
OssMaster _ossBean = CoCodeManager.OSS_INFO_UPPER.get((ossName + "_" + avoidNull(ocBean.getOssVersion())).toUpperCase());
if (_ossBean != null) {
licenseList = Arrays.asList(CommonFunction.makeLicenseFromFiles(_ossBean, false).split(","));
}
}
for (String licenseNm : licenseList) {
LicenseMaster lmBean = CoCodeManager.LICENSE_INFO.get(licenseNm);
if (lmBean != null && isEmpty(lmBean.getShortIdentifier()) && !nonIdetifierNoticeList.containsKey(lmBean.getLicenseId())) {
nonIdetifierNoticeList.put(lmBean.getLicenseId(), lmBean);
}
}
}
int rowIdx = 1;
for (LicenseMaster bean : nonIdetifierNoticeList.values()) {
int cellIdx = 0;
Row row = sheetLicense.getRow(rowIdx);
if (row == null) {
row = sheetLicense.createRow(rowIdx);
}
String _licenseName = bean.getLicenseNameTemp().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-");
// Identifier
Cell cellIdentifier = getCell(row, cellIdx); cellIdx++;
cellIdentifier.setCellValue("LicenseRef-" + _licenseName);
// Extracted Text
Cell cellExtractedText = getCell(row, cellIdx); cellIdx++;
cellExtractedText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getLicenseText()), 0, 32762) );
// License Name
Cell cellLicenseName = getCell(row, cellIdx); cellIdx++;
cellLicenseName.setCellValue(bean.getLicenseNameTemp());
// Cross Reference URLs
Cell cellCrossReferenceURLs = getCell(row, cellIdx); cellIdx++;
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
cellCrossReferenceURLs.setCellValue(avoidNull(CommonFunction.makeLicenseInternalUrl(bean, distributionFlag)));
// Comment
rowIdx ++;
}
}
// Per File Info sheet
{
// oss name이 "-" 인 case 만
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("addOssComponentList");
List<OssComponents> nonIdetifierNoticeList = new ArrayList<>();
for (OssComponents bean : noticeList) {
// set false because "Per file info sheet" is not currently output
if ("-".equals(bean.getOssName()) && false) {
nonIdetifierNoticeList.add(bean);
}
}
int rowIdx = 1;
for (OssComponents bean : nonIdetifierNoticeList) {
int cellIdx = 0;
String attributionText = "";
Row row = sheetPerFile.getRow(rowIdx);
if (row == null) {
row = sheetPerFile.createRow(rowIdx);
}
// File Name
Cell fileName = getCell(row, cellIdx); cellIdx++;
fileName.setCellValue(avoidNull(bean.getFilePath(), "./"));
// SPDX Identifier
Cell sPDXIdentifier = getCell(row, cellIdx); cellIdx++;
sPDXIdentifier.setCellValue("SPDXRef-File-" + bean.getComponentId());
// Package Identifier
cellIdx++;
// File Type(s)
Cell fileType = getCell(row, cellIdx); cellIdx++;
fileType.setCellValue("SOURCE");
// File Checksum(s)
cellIdx++;
// License Concluded
Cell cellLicenseConcluded = getCell(row, cellIdx); cellIdx++;
String srtLicenseName = "";
for (OssComponentsLicense liBean : bean.getOssComponentsLicense()) {
if (!isEmpty(srtLicenseName)) {
srtLicenseName += " AND ";
}
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(liBean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(liBean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
liBean.setLicenseName(liMaster.getShortIdentifier());
} else {
liBean.setLicenseName("LicenseRef-" + liBean.getLicenseName());
}
if (!isEmpty(attributionText)) {
attributionText += "\n";
}
attributionText += avoidNull(liMaster.getAttribution());
}
liBean.setLicenseName(liBean.getLicenseName().replaceAll("\\(", "-").replaceAll("\\)", "").replaceAll(" ", "-").replaceAll("--", "-"));
srtLicenseName += liBean.getLicenseName();
}
if (!bean.getOssComponentsLicense().isEmpty() && bean.getOssComponentsLicense().size() > 1) {
srtLicenseName = "(" + srtLicenseName + ")";
}
cellLicenseConcluded.setCellValue(srtLicenseName);
// License Info From Files
Cell licenseInfoFromFiles = getCell(row, cellIdx); cellIdx++;
licenseInfoFromFiles.setCellValue(srtLicenseName); // License Concluded 란과 동일한 값으로 표시
// License Comments
cellIdx++;
// File Copyright Text
Cell fileCopyrightText = getCell(row, cellIdx); cellIdx++;
fileCopyrightText.setCellValue(StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762) );
// Notice Text
cellIdx++;
// Artifact of Project
cellIdx++;
// Artifact of Homepage
cellIdx++;
// Artifact of URL
cellIdx++;
// Contributors
cellIdx++;
// File Comment
cellIdx++;
// File Dependencies
cellIdx++;
// Attrinbution Info
Cell attributionInfo = getCell(row, cellIdx); cellIdx++;
attributionInfo.setCellValue(attributionText);
// User Defined Columns...
cellIdx++;
rowIdx ++;
}
}
// sheetRelationships
{
int rowIdx = 1;
for (String _identifierB : packageInfoidentifierList) {
int cellIdx = 0;
Row row = sheetRelationships.getRow(rowIdx);
if (row == null) {
row = sheetRelationships.createRow(rowIdx);
}
// SPDX Identifier A
Cell spdxIdentifierA = getCell(row, cellIdx); cellIdx++;
spdxIdentifierA.setCellValue("SPDXRef-DOCUMENT");
// Relationship
Cell relationship = getCell(row, cellIdx); cellIdx++;
relationship.setCellValue("DESCRIBES");
// SPDX Identifier B
Cell spdxIdentifierB = getCell(row, cellIdx); cellIdx++;
spdxIdentifierB.setCellValue(_identifierB);
rowIdx++;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName, "xls");
}
private static Cell getCell(Row row, int cellIdx) {
Cell cell = row.getCell(cellIdx);
if (cell == null) {
cell = row.createCell(cellIdx);
}
return cell;
}
/**
* 3rd party export<br>
* 기존 업로드한 check list data 파일을 재사용한다.
* @param prjId
* @return
* @throws InvalidFormatException
* @throws IOException
*/
private static String getPartnerChecklistReportExcelPost(String prjId) throws InvalidFormatException, IOException {
FileInputStream inFile=null;
Workbook wb = null;
// download file name
String downloadFileName = "fosslight-report"; // Default
try {
//cover
PartnerMaster projectInfo = new PartnerMaster();
projectInfo.setPartnerId(prjId);
projectInfo = partnerService.getPartnerMasterOne(projectInfo);
ProjectIdentification ossListParam = new ProjectIdentification();
ossListParam.setReferenceId(prjId);
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_PARTNER);
Map<String, Object> resultMap = projectService.getIdentificationGridList(ossListParam);
inFile= new FileInputStream(new File(downloadpath+"/OssCheckList.xlsx"));
wb = WorkbookFactory.create(inFile);
int sheetIdx = wb.getSheetIndex("Open Source Software List");
Sheet sheet1 = wb.getSheetAt(sheetIdx); // OSS List sheet
//fosslight_report_[date]_3rd-[ID].xlsx
downloadFileName += "_" + CommonFunction.getCurrentDateTime() + "_3rd-" + StringUtil.deleteWhitespaceWithSpecialChar(prjId);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_PARTNER, sheet1, resultMap, null, false);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName);
}
public static String getExcelDownloadIdOss(String type, OssMaster oss, String filepath) throws Exception {
downloadpath = filepath;
String downloadId = null;
if (isMaximumRowCheck(ossMapper.selectOssMasterTotalCount(oss))){
oss.setStartIndex(0);
oss.setPageListSize(MAX_RECORD_CNT);
oss.setSearchFlag(CoConstDef.FLAG_NO); // 화면 검색일 경우 "Y" export시 "N"
Map<String,Object> ossMap = ossService.getOssMasterList(oss);
downloadId = getOssExcel((List<OssMaster>) ossMap.get("rows"));
}
return downloadId;
}
private static String makeVerificationExcel (List<ProjectIdentification> verificationList) throws Exception {
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile = null;
try {
inFile= new FileInputStream(new File(downloadpath+"/VerificationList.xlsx"));
wb = WorkbookFactory.create(inFile);
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "DisclosureOSSList");
// 화면상에 편집가능한 path 정보를 제외하고는 componentid로 DB정보를 참조한다.
OssComponents param = new OssComponents();
for (ProjectIdentification bean : verificationList) {
param.addOssComponentsIdList(bean.getComponentId());
}
Map<String, OssComponents> dbDataMap = new HashMap<>();
List<OssComponents> list = projectService.selectOssComponentsListByComponentIds(param);
if (list != null) {
for (OssComponents bean : list) {
dbDataMap.put(bean.getComponentId(), bean);
}
}
List<String[]> rows = new ArrayList<>();
for (ProjectIdentification bean : verificationList) {
OssComponents dbBean = null;
if (dbDataMap.containsKey(bean.getComponentId())) {
dbBean = dbDataMap.get(bean.getComponentId());
}
String[] rowParam = {
bean.getComponentId()
, bean.getReferenceDiv()
, dbBean != null ? dbBean.getOssName() : bean.getOssName()
, dbBean != null ? dbBean.getOssVersion() : bean.getOssVersion()
, dbBean != null ? dbBean.getDownloadLocation() : bean.getDownloadLocation()
, dbBean != null ? dbBean.getHomepage() : bean.getHomepage()
, bean.getLicenseName()
, bean.getFilePath()
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
return makeExcelFileId(wb,"PackagingOSSList");
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {
}
}
}
}
private static String getSelfCheckListExcelPost(String search, String type) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/selfCheckList.xlsx"));
try {wb = new XSSFWorkbook(inFile);} catch (IOException e) {log.error(e.getMessage());}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "selfCheckList");
Type collectionType2 = new TypeToken<Project>(){}.getType();
Project project = (Project) fromJson(search, collectionType2);
List<Project> selfCheckList = selfCheckMapper.getSelfCheckList(project);
List<String[]> rows = new ArrayList<>();
for (int i = 0; i < selfCheckList.size(); i++){
Project param = selfCheckList.get(i);
String[] rowParam = {
param.getPrjId()
, param.getPrjName()
, param.getPrjVersion()
// , CoConstDef.COMMON_SELECTED_ETC.equals(avoidNull(param.getOsType(), CoConstDef.COMMON_SELECTED_ETC)) ? param.getOsTypeEtc() : CoCodeManager.getCodeString(CoConstDef.CD_OS_TYPE, param.getOsType())
// , param.getDistributionType()
, param.getCvssScore()
, (isEmpty(param.getBomCnt()) ? "0" : param.getBomCnt()) + "(" + (isEmpty(param.getDiscloseCnt()) ? "0" : param.getDiscloseCnt()) + ")"
// , param.getDivision()
, param.getCreator()
, CommonFunction.formatDate(param.getCreatedDate())
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
}
return makeExcelFileId(wb,"selfCheckList");
}
private static String getSelftReportExcelPost (String prjId) throws IOException, InvalidFormatException {
Workbook wb = null;
FileInputStream inFile=null;
// download file name
String downloadFileName = "fosslight_report"; // Default
try {
inFile= new FileInputStream(new File(downloadpath+"/SelfCheck-Report.xlsx"));
wb = WorkbookFactory.create(inFile);
//cover
Project projectInfo = new Project();
{
projectInfo.setPrjId(prjId);
projectInfo = selfCheckService.getProjectDetail(projectInfo);
}
//fosslight_report_[date]_self-[ID].xlsx
downloadFileName += "_" + CommonFunction.getCurrentDateTime() + "_self-" + StringUtil.deleteWhitespaceWithSpecialChar(prjId);
ProjectIdentification ossListParam = new ProjectIdentification();
ossListParam.setReferenceId(prjId);
ossListParam.setReferenceDiv(CoConstDef.CD_DTL_SELF_COMPONENT_ID);
ossListParam.setMerge(CoConstDef.FLAG_NO);
// self check는 기본적으로 Identification SRC와 동일하게 동작
// self check의 경우만 추가 처리가 필요한 경우는 isSelfCheck flag로 판단한다.
Map<String, Object> selfCheckGridInfo = selfCheckService.getIdentificationGridList(ossListParam);
reportIdentificationSheet(CoConstDef.CD_DTL_COMPONENT_ID_SRC, wb.getSheetAt(0), selfCheckGridInfo, projectInfo, true);
// Vuln 출력
// selfCheckService.getIdentificationGridList 에서 OSS_Master를 기준으로
try {
Sheet vulnSheet = wb.getSheetAt(1);
if (vulnSheet == null) {
vulnSheet = wb.createSheet("Vulnerability");
}
List<Vulnerability> vulnList = selfCheckService.getAllVulnListWithProject(projectInfo.getPrjId());
List<String[]> vulnRows = new ArrayList<>();
if (vulnList != null && !vulnList.isEmpty()) {
String _host = CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org");
for (Vulnerability vulnBean : vulnList) {
List<String> params = new ArrayList<>();
String url = _host+"/vulnerability/vulnpopup?ossName=";
// PRODUCT
if (!isEmpty(vulnBean.getOssName())) {
// nick name에 의해 조회된 경우
params.add(vulnBean.getOssName());
params.add(avoidNull(vulnBean.getProduct()));
} else {
params.add(avoidNull(vulnBean.getProduct()));
params.add("-");
}
url += vulnBean.getProduct(); // OSS PRODUCT으로 검색
// VERSION
params.add(avoidNull(vulnBean.getVersion()));
params.add(avoidNull(vulnBean.getCvssScore()));
// vulnpopup url
if (!isEmpty(vulnBean.getVersion()) && !"-".equals(vulnBean.getVersion())) {
url += "&ossVersion=" + vulnBean.getVersion(); // + "&vulnType=v"; 사용하지 않는 parameter
}
params.add(url);
vulnRows.add(params.toArray(new String[params.size()]));
}
}
if (vulnRows != null && !vulnRows.isEmpty()) {
makeSheet(vulnSheet, vulnRows, 2, true);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e) {}
}
}
return makeExcelFileId(wb,downloadFileName);
}
/* 2018-07-26 choye 추가 */
private static String getVulnerabilityExcel(List<Vulnerability> vulnerabilityList) throws Exception{
Workbook wb = null;
Sheet sheet = null;
String fileName = "VulnerabilityList";
try (
FileInputStream inFile= new FileInputStream(new File(downloadpath+"/VulnerabilityReport.xlsx"));
) {
try {wb = new XSSFWorkbook(inFile);} catch (IOException e) {log.error(e.getMessage());}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "vulnerabilityList");
List<String[]> rows = new ArrayList<>();
Set<String> ossName = new HashSet<>();
for (Vulnerability param : vulnerabilityList){
String[] rowParam = {
param.getProduct()
, param.getVersion()
, param.getCveId()
, param.getCvssScore()
, convertPipeToLineSeparator(param.getVulnSummary())
, param.getPublDate()
, param.getModiDate()
, param.getVendor()
};
ossName.add(param.getProduct());
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows);
if (ossName.size() == 1) {
fileName += "_" + ossName.toString().substring(1,ossName.toString().length()-1);
}
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
}
return makeExcelFileId(wb, fileName);
}
private static boolean isMaximumRowCheck(int totalRow){
final String RowCnt = CoCodeManager.getCodeExpString(CoConstDef.CD_EXCEL_DOWNLOAD, CoConstDef.CD_MAX_ROW_COUNT);
if (totalRow > Integer.parseInt(RowCnt)){
return false;
}
return true;
}
@SuppressWarnings({ "unchecked", "serial" })
public static String getChartExcel(List<Statistics> chartParams, String filePath) throws Exception {
Map<String, Object> chartDataMap = new HashMap<String, Object>();
Statistics result = new Statistics();
Statistics result2 = new Statistics();
Statistics ChartData = chartParams.get(0);
ChartData.setIsRawData(CoConstDef.FLAG_NO);
boolean projectUseFlag = CommonFunction.propertyFlagCheck("menu.project.use.flag", CoConstDef.FLAG_YES);
boolean partnerUseFlag = CommonFunction.propertyFlagCheck("menu.partner.use.flag", CoConstDef.FLAG_YES);
if (projectUseFlag) {
ChartData.setCategoryType("STT");
result = (Statistics) statisticsService.getDivisionalProjectChartData(ChartData).get("chartData");
ChartData.setCategoryType("REV");
result2 = (Statistics) statisticsService.getDivisionalProjectChartData(ChartData).get("chartData");
result.getDataArray().addAll(result2.getDataArray());
result.getTitleArray().addAll(result2.getTitleArray());
ChartData.setCategoryType("DST");
result2 = (Statistics) statisticsService.getDivisionalProjectChartData(ChartData).get("chartData");
result.getDataArray().addAll(result2.getDataArray());
result.getTitleArray().addAll(result2.getTitleArray());
chartDataMap.put("divisionalProjectChart", result);
}
ChartData.setChartType("OSS");
ChartData.setCategoryType("REV");
chartDataMap.put("mostUsedOssChart", (List<Statistics>) statisticsService.getMostUsedChartData(ChartData).get("chartData"));
ChartData.setChartType("LICENSE");
ChartData.setCategoryType("REV");
chartDataMap.put("mostUsedLicenseChart", (List<Statistics>) statisticsService.getMostUsedChartData(ChartData).get("chartData"));
chartDataMap.put("updatedOssChart", (Statistics) statisticsService.getUpdatedOssChartData(ChartData).get("chartData"));
chartDataMap.put("updatedLicenseChart", (Statistics) statisticsService.getUpdatedLicenseChartData(ChartData).get("chartData"));
if (partnerUseFlag) {
ChartData.setCategoryType("3rdSTT");
result = (Statistics) statisticsService.getTrdPartyRelatedChartData(ChartData).get("chartData");
ChartData.setCategoryType("REV");
result2 = (Statistics) statisticsService.getTrdPartyRelatedChartData(ChartData).get("chartData");
result.getDataArray().addAll(result2.getDataArray());
result.getTitleArray().addAll(result2.getTitleArray());
chartDataMap.put("trdPartyRelatedChart", result);
}
ChartData.setIsRawData(CoConstDef.FLAG_YES);
chartDataMap.put("userRelatedChart", (List<Statistics>) statisticsService.getUserRelatedChartData(ChartData).get("chartData"));
return getChartDataExcelId(chartDataMap, filePath);
}
/**
*
* @param partner
* @return
* @throws Exception
* @용도 3rd 엑셀 파일 ID
*/
@SuppressWarnings("unchecked")
private static String getChartDataExcelId(Map<String, Object> chartDataMap, String filepath) throws Exception{
downloadpath = filepath;
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/chartDataList.xlsx"));
wb = new XSSFWorkbook(inFile);
String[] sheetIdxList = new String[] {"divisionalProjectChart", "mostUsedOssChart", "mostUsedLicenseChart", "updatedOssChart", "updatedLicenseChart", "trdPartyRelatedChart", "userRelatedChart"};
if (chartDataMap != null && !chartDataMap.isEmpty()) {
for (String key : chartDataMap.keySet()) {
String chartName = key;
int idx = 1;
sheet = wb.getSheetAt((int) Arrays.asList(sheetIdxList).indexOf(chartName));
List<String[]> rows = new ArrayList<>();
List<String> params = new ArrayList<>();
switch(chartName) {
case "divisionalProjectChart":
case "updatedOssChart":
case "updatedLicenseChart":
case "trdPartyRelatedChart":
Statistics chartData = (Statistics) chartDataMap.get(chartName);
List<String> divisionList = new ArrayList<String>();
if (!chartName.startsWith("updated")) {
divisionList = CoCodeManager.getCodeNames(CommonFunction.getCoConstDefVal("CD_USER_DIVISION"));
}
/* Title */
params = new ArrayList<>();
params.add("NO"); // seq
params.add(!chartName.startsWith("updated") ? "Division" : "Date"); // divisionNm
for (String title : chartData.getTitleArray()) {
params.add(title); // category
}
rows.add(params.toArray(new String[params.size()]));
/* Data */
for (int seq = 0, length = chartData.getDataArray().get(0).size() ; seq < length ; seq++) {
params = new ArrayList<>();
params.add(Integer.toString(idx)); // seq
if (!chartName.startsWith("updated")) {
params.add(divisionList.get(seq)); // category
}else {
params.add(chartData.getCategoryList().get(seq)); // category
}
for (List<Integer> arr : chartData.getDataArray()) {
params.add(Integer.toString(arr.get(seq))); // category Cnt
}
idx++;
rows.add(params.toArray(new String[params.size()]));
}
break;
case "mostUsedOssChart":
case "mostUsedLicenseChart":
params = new ArrayList<>();
params.add("NO"); // seq
params.add("mostUsedOssChart".equals(chartName) ? "OSS Name" : "License Name"); // OSS Name
params.add("Cnt"); // OSS Cnt
rows.add(params.toArray(new String[params.size()]));
for (Statistics stat : (List<Statistics>) chartDataMap.get(chartName)) {
params = new ArrayList<>();
params.add(Integer.toString(idx)); // seq
params.add(stat.getColumnName()); // OSS Name || License Name
params.add(Integer.toString(stat.getColumnCnt())); // OSS || License Cnt
idx++;
rows.add(params.toArray(new String[params.size()]));
}
break;
case "userRelatedChart":
params = new ArrayList<>();
params.add("NO"); // seq
params.add("Division"); // Division
params.add("Total"); // Total Cnt
params.add("Activator"); // Activator Cnt
rows.add(params.toArray(new String[params.size()]));
for (Statistics stat : (List<Statistics>) chartDataMap.get(chartName)) {
params = new ArrayList<>();
params.add(Integer.toString(idx)); // seq
params.add(stat.getDivisionNm()); // Division
params.add(Integer.toString(stat.getCategory0Cnt())); // Total Cnt
params.add(Integer.toString(stat.getCategory1Cnt())); // Activor Cnt
idx++;
rows.add(params.toArray(new String[params.size()]));
}
break;
}
//시트 만들기
makeChartSheet(sheet, rows);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeExcelFileId(wb,"chartDataList");
}
/* 2018-07-26 choye 추가 */
private static String getAnalysisListExcel(List<OssAnalysis> analysisList, String prjId) throws Exception{
Workbook wb = null;
Sheet sheet = null;
InputStream inFile=null;
try {
inFile= new FileInputStream(new File(downloadpath+"/AutoAnalysisList.xlsx"));
try {wb = new XSSFWorkbook(inFile);} catch (IOException e) {log.error(e.getMessage());}
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "Auto Analysis Input");
List<String[]> rows = new ArrayList<>();
for (OssAnalysis param : analysisList){
String[] rowParam = {
param.getGridId()
, param.getOssName()
, param.getOssVersion()
, param.getLicenseName()
, param.getDownloadLocation().replaceAll("%40", "@")
, param.getHomepage().replaceAll("%40", "@")
};
rows.add(rowParam);
}
//시트 만들기
makeSheet2(sheet, rows);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (Exception e2) {
}
}
}
return makeAnalysisListExcelFileId(wb, "AutoAnalysisList", "xlsx", prjId);
}
/**
*
* @param bomCompareList
* @return
* @throws Exception
* @용도 bomcompare 엑셀
*/
@SuppressWarnings("unchecked")
private static String getBomCompareExcelId(String dataStr) throws Exception{
Workbook wb = null;
Sheet sheet = null;
FileInputStream inFile=null;
ObjectMapper objMapper = new ObjectMapper();
try {
Map<String, String> map = objMapper.readValue(dataStr, Map.class);
String beforePrjId = map.get("beforePrjId").toString();
String afterPrjId = map.get("afterPrjId").toString();
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;
beforeBom = projectController.getOssComponentDataInfo(beforeIdentification, beforeReferenceDiv);
if (beforeReferenceDiv.equals(CoConstDef.CD_DTL_COMPONENT_ID_BOM)) {
if (!beforeBom.containsKey("rows") || (List<ProjectIdentification>) beforeBom.get("rows") == null) {
} else {
beforeBomList = (List<ProjectIdentification>) beforeBom.get("rows");
}
} else {
if (!beforeBom.containsKey("mainData") || (List<ProjectIdentification>) beforeBom.get("mainData") == null) {
} else {
beforeBomList = projectService.setMergeGridDataByAndroid((List<ProjectIdentification>) beforeBom.get("mainData"));
}
}
afterBom = projectController.getOssComponentDataInfo(AfterIdentification, afterReferenceDiv);
if (afterReferenceDiv.equals(CoConstDef.CD_DTL_COMPONENT_ID_BOM)) {
if (!afterBom.containsKey("rows") || (List<ProjectIdentification>) afterBom.get("rows") == null) {
} else {
afterBomList = (List<ProjectIdentification>) afterBom.get("rows");
}
} else {
if (!afterBom.containsKey("mainData") || (List<ProjectIdentification>) afterBom.get("mainData") == null) {
} else {
afterBomList = projectService.setMergeGridDataByAndroid((List<ProjectIdentification>) afterBom.get("mainData"));
}
}
if (beforeBomList == null || afterBomList == null) {// before, after값 중 하나라도 null이 있으면 비교 불가함.
throw new Exception();
}
List<Map<String, String>> bomCompareListExcel = prjService.getBomCompare(beforeBomList, afterBomList, "excel");
try {
inFile= new FileInputStream(new File(downloadpath + "/BOM_Compare.xlsx"));
wb = new XSSFWorkbook(inFile);
sheet = wb.getSheetAt(0);
wb.setSheetName(0, "BOM_Compare_"+beforePrjId+"_"+afterPrjId);
List<String[]> rows = new ArrayList<String[]>();
for (int i = 0; i < bomCompareListExcel.size(); i++){
String[] rowParam = {
bomCompareListExcel.get(i).get("status"),
bomCompareListExcel.get(i).get("beforeossname"),
bomCompareListExcel.get(i).get("beforelicense"),
bomCompareListExcel.get(i).get("afterossname"),
bomCompareListExcel.get(i).get("afterlicense")
};
rows.add(rowParam);
}
//시트 만들기
makeSheet(sheet, rows, 1);
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
if (inFile != null) {
try {inFile.close();}
catch (Exception e2) {}
}
}
return makeBomCompareExcelFileId(beforePrjId, afterPrjId, wb, "BOM_Compare", "xlsx");
} catch (IOException e){
log.error(e.getMessage());
}
return null;
}
private static String makeBomCompareExcelFileId(String beforePrjId, String afterPrjId, Workbook wb, String target, String exp) throws IOException {
String fileName = CommonFunction.replaceSlashToUnderline(target) + "_" + beforePrjId + "_" + afterPrjId + "_" + CommonFunction.getCurrentDateTime();
String logiFileName = fileName + "." + exp;
String excelFilePath = writepath + "/download/";
FileOutputStream outFile = null;
try {
if (!Files.exists(Paths.get(excelFilePath))) {
Files.createDirectories(Paths.get(excelFilePath));
}
outFile = new FileOutputStream(excelFilePath + logiFileName);
wb.write(outFile);
// db 등록
return fileService.registFileDownload(excelFilePath, fileName + "."+exp, logiFileName);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (outFile != null) {
try {
outFile.close();
} catch (Exception e2) {}
}
}
return null;
}
private static String getCycloneDXFileId(String type, String dataStr, boolean verifyFlag) {
// download file name
String downloadFileName = "CycloneDX-"; // Default
String prjId = dataStr;
boolean thirdPartyCheckFlag = false;
if (prjId.startsWith("3rd_")) {
thirdPartyCheckFlag = true;
String[] prjIdSplit = dataStr.split("_");
prjId = prjIdSplit[1];
}
OssNotice ossNotice = new OssNotice();
ossNotice.setPrjId(prjId);
ossNotice.setFileType("text");
List<OssComponents> dependenciesDataList = null;
Map<String, Object> packageInfo = null;
String strPrjName = "";
String creator = "";
Date timeStamp = null;
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
if (!thirdPartyCheckFlag) {
Project projectInfo = new Project();
projectInfo.setPrjId(prjId);
projectInfo = projectService.getProjectDetail(projectInfo);
String createDate = projectInfo.getCreatedDate();
timeStamp = sdformat.parse(createDate.replace(" ", "T") + ".000");
creator = projectInfo.getCreator();
strPrjName = projectInfo.getPrjName();
if (!isEmpty(projectInfo.getPrjVersion())) {
strPrjName += "-" + projectInfo.getPrjVersion();
}
downloadFileName += FileUtil.makeValidFileName(strPrjName, "_").replaceAll(" ", "").replaceAll("--", "-");
if (verifyFlag) {
packageInfo = verificationService.getNoticeHtmlInfo(ossNotice);
} else {
packageInfo = projectService.getExportDataForSBOMInfo(ossNotice);
}
projectInfo.setReferenceDiv(CoConstDef.CD_DTL_COMPONENT_ID_DEP);
dependenciesDataList = projectService.getDependenciesDataList(projectInfo);
} else {
PartnerMaster partner = new PartnerMaster();
partner.setPartnerId(prjId);
partner = partnerService.getPartnerMasterOne(partner);
timeStamp = sdformat.parse(partner.getCreatedDate());
creator = partner.getCreator();
strPrjName = partner.getPartnerName();
packageInfo = partnerService.getExportDataForSbomInfo(partner);
}
} catch (Exception e) {
log.error(e.getMessage());
}
Bom bom = generatorCycloneDXBOM(packageInfo, dependenciesDataList, timeStamp, creator, verifyFlag);
UUID randomUUID = UUID.randomUUID();
String fileName = CommonFunction.replaceSlashToUnderline(downloadFileName);
String logiFileName = fileName + "_" + randomUUID;
String ext = type.toUpperCase().endsWith("JSON") ? ".json" : ".xml";
logiFileName += ext;
String excelFilePath = writepath+"/download/";
String fileId = "";
FileWriter fw = null;
try {
fw = new FileWriter(excelFilePath + "/" + logiFileName, true);
if (type.toUpperCase().endsWith("JSON")) {
fw.write(BomGeneratorFactory.createJson(CycloneDxSchema.Version.VERSION_14, bom).toJsonString());
} else {
fw.write(BomGeneratorFactory.createXml(CycloneDxSchema.Version.VERSION_14, bom).toXmlString());
}
fileId = fileService.registFileDownload(excelFilePath, fileName + ext, logiFileName);
} catch (IOException | GeneratorException e) {
log.error(e.getMessage(), e);
} finally {
if (fw != null) {
try {
fw.close();
} catch (Exception e2) {}
}
}
return fileId;
}
@SuppressWarnings("unchecked")
private static Bom generatorCycloneDXBOM(Map<String, Object> packageInfo, List<OssComponents> dependenciesDataList, Date timeStamp, String creator, boolean verifyFlag) {
Bom bom = new Bom();
List<OssComponents> noticeList = (List<OssComponents>) packageInfo.get("noticeObligationList");
List<OssComponents> sourceList = (List<OssComponents>) packageInfo.get("disclosureObligationList");
if (sourceList != null && !sourceList.isEmpty()) {
noticeList.addAll(sourceList);
}
if (!verifyFlag && packageInfo.containsKey("notObligationList")) {
List<OssComponents> notObligationList = (List<OssComponents>) packageInfo.get("notObligationList");
if (notObligationList != null && !notObligationList.isEmpty()) {
noticeList.addAll(notObligationList);
}
}
noticeList = verificationService.setMergeGridData(noticeList); // merge Data
Map<String, Object> relationshipsMap = new HashMap<>();
Metadata meta = new Metadata();
meta.setTimestamp(timeStamp);
List<Tool> tools = new ArrayList<>();
Tool tool = new Tool();
tool.setVendor("LG Electronics");
tool.setName("FOSSLIhgt Hub");
tool.setVersion(CommonFunction.getProperty("project.version"));
tools.add(tool);
meta.setTools(tools);
List<OrganizationalContact> authors = new ArrayList<>();
OrganizationalContact organizationalContract = new OrganizationalContact();
organizationalContract.setName(creator);
authors.add(organizationalContract);
meta.setAuthors(authors);
OrganizationalEntity organizationalEntity = new OrganizationalEntity();
organizationalEntity.setName("LG Electronics");
organizationalEntity.setUrls(Arrays.asList(new String[] {"https://opensource.lge.com"}));
meta.setSupplier(organizationalEntity);
bom.setMetadata(meta);
List<Component> componentList = new ArrayList<>();
List<org.cyclonedx.model.vulnerability.Vulnerability> vulnerablityList = new ArrayList<>();
List<String> checkCveIdList = new ArrayList<>();
List<Dependency> dependencyList = new ArrayList<>();
boolean distributionFlag = CommonFunction.propertyFlagCheck("distribution.use.flag", CoConstDef.FLAG_YES);
for (OssComponents bean : noticeList) {
String ossName = bean.getOssName();
String ossVersion = bean.getOssVersion();
Component component = new Component();
ExternalReference external = new ExternalReference();
List<ExternalReference> externalList = new ArrayList<>();
String relationshipsKey = (ossName + "(" + avoidNull(bean.getOssVersion()) + ")").toUpperCase();
String bomRef = bean.getComponentId();
relationshipsMap.put(relationshipsKey, bomRef);
component.setType(org.cyclonedx.model.Component.Type.LIBRARY);
component.setBomRef(bomRef);
component.setName(ossName);
component.setVersion(bean.getOssVersion());
LicenseChoice licenseChoice = new LicenseChoice();
List<License> licenseList = new ArrayList<>();
OssMaster _ossBean = null;
if (ossName.equals("-")) {
String licenseStr = CommonFunction.licenseStrToSPDXLicenseFormat(bean.getLicenseName());
licenseStr = CommonFunction.removeSpecialCharacters(licenseStr, true).replaceAll("\\(", "-").replaceAll("\\)", "");
if (licenseStr.contains(",")) {
for (String license : licenseStr.split(",")) {
License li = new License();
li.setName(license.trim());
licenseList.add(li);
}
} else {
License li = new License();
li.setName(licenseStr.trim());
licenseList.add(li);
}
} else {
_ossBean = CoCodeManager.OSS_INFO_UPPER.get( (ossName + "_" + avoidNull(bean.getOssVersion())).toUpperCase());
if (_ossBean != null) {
for (OssLicense ossLicense : _ossBean.getOssLicenses()) {
License li = new License();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(ossLicense.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(ossLicense.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
li.setId(liMaster.getShortIdentifier());
} else {
li.setName(liMaster.getLicenseName());
String internalUrl = CommonFunction.makeLicenseInternalUrl(liMaster, distributionFlag);
if (!isEmpty(internalUrl)) li.setUrl(internalUrl);
}
} else {
li.setName(ossLicense.getLicenseName());
}
licenseList.add(li);
}
} else {
if (bean.getLicenseName().contains(",")) {
for (String license : bean.getLicenseName().split(",")) {
License li = new License();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(license).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(license).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
li.setId(liMaster.getShortIdentifier());
} else {
li.setName(liMaster.getLicenseName());
String internalUrl = CommonFunction.makeLicenseInternalUrl(liMaster, distributionFlag);
if (!isEmpty(internalUrl)) li.setUrl(internalUrl);
}
} else {
li.setName(license.trim());
}
licenseList.add(li);
}
} else {
License li = new License();
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(avoidNull(bean.getLicenseName()).toUpperCase())) {
LicenseMaster liMaster = CoCodeManager.LICENSE_INFO_UPPER.get(avoidNull(bean.getLicenseName()).toUpperCase());
if (!isEmpty(liMaster.getShortIdentifier())) {
li.setId(liMaster.getShortIdentifier());
} else {
li.setName(liMaster.getLicenseName());
String internalUrl = CommonFunction.makeLicenseInternalUrl(liMaster, distributionFlag);
if (!isEmpty(internalUrl)) li.setUrl(internalUrl);
}
} else {
li.setName(CommonFunction.removeSpecialCharacters(bean.getLicenseName(), true).replaceAll("\\(", "-").replaceAll("\\)", ""));
}
licenseList.add(li);
}
}
}
licenseChoice.setLicenses(licenseList);
component.setLicenseChoice(licenseChoice);
String copyrightText = StringUtil.substring(CommonFunction.brReplaceToLine(bean.getCopyrightText()), 0, 32762);
if (!copyrightText.isEmpty() && !copyrightText.equals("-")) {
component.setCopyright(copyrightText);
}
// download location
String downloadLocation = bean.getDownloadLocation();
external.setType(org.cyclonedx.model.ExternalReference.Type.WEBSITE);
if (!isEmpty(downloadLocation)) {
external.setUrl(downloadLocation);
}
externalList.add(external);
component.setExternalReferences(externalList);
componentList.add(component);
// vulnerability
if (!isEmpty(ossName) && !ossName.equals("-")) {
OssMaster param = new OssMaster();
param.setOssName(ossName);
param.setOssVersion(isEmpty(ossVersion) ? "N/A" : ossVersion);
Map<String, Object> vulnMap = vulnerabilityService.getVulnListByOssName(param);
List<Vulnerability> vulnList = (List<Vulnerability>) vulnMap.get("rows");
if (vulnList != null && !vulnList.isEmpty()) {
for (Vulnerability vulnerability : vulnList) {
String cveId = vulnerability.getCveId();
String key = bomRef + "_" + cveId;
if (!checkCveIdList.contains(key)) {
org.cyclonedx.model.vulnerability.Vulnerability vuln = new org.cyclonedx.model.vulnerability.Vulnerability();
Source vulnSource = new Source();
vulnSource.setName("NVD"); // source set name : NVD
vulnSource.setUrl("https://nvd.nist.gov/vuln/detail/" + cveId); // source set nvd url
vuln.setBomRef(bomRef);
vuln.setId(cveId);
vuln.setSource(vulnSource);
vulnerablityList.add(vuln);
checkCveIdList.add(key);
}
}
}
}
}
List<Dependency> depList = null;
// dependency
for (OssComponents oss : dependenciesDataList) {
String key = (oss.getOssName() + "(" + oss.getOssVersion() + ")").toUpperCase();
if (relationshipsMap.containsKey(key)) {
depList = new ArrayList<>();
String componentId = (String) relationshipsMap.get(key);
String[] dependencies = oss.getDependencies().split(",");
Dependency bomRefDep = new Dependency(componentId);
for (String dependency : dependencies) {
String relatedBomRefKey = dependency.toUpperCase();
if (relationshipsMap.containsKey(relatedBomRefKey)) {
String relatedComponentId = (String) relationshipsMap.get(relatedBomRefKey);
Dependency dep = new Dependency(relatedComponentId);
bomRefDep.addDependency(dep);
}
}
depList.add(bomRefDep);
}
if (depList != null) {
dependencyList.addAll(depList);
}
}
bom.setComponents(componentList);
if (!dependencyList.isEmpty()) bom.setDependencies(dependencyList);
if (!vulnerablityList.isEmpty()) bom.setVulnerabilities(vulnerablityList);
return bom;
}
}
| 180,717 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
PdfUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/PdfUtil.java | package oss.fosslight.util;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.layout.font.FontProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.domain.*;
import oss.fosslight.domain.File;
import oss.fosslight.repository.*;
import oss.fosslight.service.ProjectService;
import oss.fosslight.service.VulnerabilityService;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import static oss.fosslight.common.CoConstDef.CD_LICENSE_RESTRICTION;
@Slf4j
public final class PdfUtil extends CoTopComponent {
private static PdfUtil instance;
private static VerificationMapper verificationMapper;
private static LicenseMapper licenseMapper;
private static OssMapper ossMapper;
private static VulnerabilityService vulnerabilityService;
private static ProjectService projectService;
private static CodeMapper codeMapper;
private static ProjectMapper projectMapper;
public static PdfUtil getInstance() {
if (instance == null) {
instance = new PdfUtil();
licenseMapper = (LicenseMapper) getWebappContext().getBean(LicenseMapper.class);
ossMapper = (OssMapper) getWebappContext().getBean(OssMapper.class);
projectService = (ProjectService) getWebappContext().getBean(ProjectService.class);
vulnerabilityService = (VulnerabilityService) getWebappContext().getBean(VulnerabilityService.class);
codeMapper = (CodeMapper) getWebappContext().getBean(CodeMapper.class);
projectMapper = (ProjectMapper) getWebappContext().getBean(ProjectMapper.class);
verificationMapper = (VerificationMapper) getWebappContext().getBean(VerificationMapper.class);
}
return instance;
}
public static ByteArrayInputStream html2pdf(String html) throws IOException {
String font = "src/main/resources/static/NanumGothicBold.ttf";
ConverterProperties properties = new ConverterProperties();
FontProvider fontProvider = new DefaultFontProvider(false,false,false);
FontProgram fontProgram = FontProgramFactory.createFont(font);
fontProvider.addFont(fontProgram);
properties.setFontProvider(fontProvider);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HtmlConverter.convertToPdf(html, outputStream, properties);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return inputStream;
}
public String getReviewReportHtml(String prjId) throws Exception
{
Map<String,Object> convertData = new HashMap<>();
List<OssMaster> ossReview = new ArrayList<>();
List<LicenseMaster> licenseReview = new ArrayList<>();
List<Vulnerability> vulnerabilityReview = new ArrayList<>();
Map<String,LicenseMaster> licenseMasterMap = new HashMap<>();
String type = CoConstDef.CD_DTL_COMPONENT_ID_BOM;
Project projectMaster = new Project();
projectMaster.setPrjId(prjId);
Project project = projectMapper.selectProjectMaster(projectMaster);
convertData.put("project", project);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
String strToday = sdf.format(c1.getTime());
convertData.put("date", strToday);
ProjectIdentification _param = new ProjectIdentification();
_param.setReferenceDiv(type);
_param.setReferenceId(prjId);
_param.setMerge(CoConstDef.FLAG_NO);
Map<String, Object> map = projectService.getIdentificationGridList(_param, true);
List<ProjectIdentification> list = (List<ProjectIdentification>) map.get("rows");
for (ProjectIdentification projectIdentification : list) {
//OssMasterReview
OssMaster ossMaster = new OssMaster();
ossMaster.setOssId(projectIdentification.getOssId());
OssMaster oss = ossMapper.selectOssOne(ossMaster);
if (!oss.getSummaryDescription().equals("")) {
ossReview.add(oss);
}
//VulnerabilityReview
projectIdentification.setOssName(oss.getOssName());
projectIdentification.setOssVersion(oss.getOssVersion());
ProjectIdentification prjOssMaster = projectMapper.getOssId(projectIdentification);
if(prjOssMaster.getCvssScore()!=null) {
BigDecimal bdScore = new BigDecimal(Float.parseFloat(prjOssMaster.getCvssScore()));
if (bdScore.compareTo(new BigDecimal("8.0")) >= 0) {
Vulnerability vulnerability = new Vulnerability();
vulnerability.setOssName(oss.getOssName());
vulnerability.setVersion(oss.getOssVersion());
vulnerability.setCvssScore(prjOssMaster.getCvssScore());
vulnerability.setVulnerabilityLink(CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org") + "/vulnerability/vulnpopup?ossName=" + oss.getOssName() + "&ossVersion=" + oss.getOssVersion());
vulnerabilityReview.add(vulnerability);
}
}
//LisenseReview
LicenseMaster licenseMaster = new LicenseMaster();
licenseMaster.setLicenseId(projectIdentification.getLicenseId());
LicenseMaster license = licenseMapper.selectLicenseOne(licenseMaster);
if (!isEmpty(license.getRestriction())) {
String[] arrRestrictions = license.getRestriction().split(",");
String str = "";
for (int i = 0; i < arrRestrictions.length - 2; i++) {
str += codeMapper.getCodeDtlNm(CD_LICENSE_RESTRICTION, arrRestrictions[i]) + ", ";
}
if (arrRestrictions.length > 0) {
str += codeMapper.getCodeDtlNm(CD_LICENSE_RESTRICTION, arrRestrictions[arrRestrictions.length - 1]);
}
license.setRestriction(str);
}
if (license.getRestriction() != null || license.getDescription() != null) {
licenseMasterMap.put(license.getLicenseName(), license);
}
}
for (LicenseMaster licenseMaster : licenseMasterMap.values()) {
licenseReview.add(licenseMaster);
}
convertData.put("OssReview", ossReview);
convertData.put("LicenseReview", licenseReview);
convertData.put("VulnerabilityReview", vulnerabilityReview);
String pdfContent = getVelocityTemplateContent("/template/report/reviewReport.html", convertData);
return pdfContent;
}
/**
* * Get velocity template content.
*
* @param path the path
* @param model the model
* @return the string
* */
private String getVelocityTemplateContent(String path, Map<String, Object> model) {
VelocityContext context = new VelocityContext();
Writer writer = new StringWriter();
VelocityEngine vf = new VelocityEngine();
Properties props = new Properties();
for (String key : model.keySet()) {
if (!"templateUrl".equals(key)) {
context.put(key, model.get(key));
}
}
context.put("domain", CommonFunction.emptyCheckProperty("server.domain", "http://fosslight.org"));
context.put("commonFunction", CommonFunction.class);
props.put("resource.loader", "class");
props.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
props.put("input.encoding", "UTF-8");
props.put("output.encoding", "UTF-8");
vf.init(props);
try {
Template template = vf.getTemplate(path); // file name
template.merge(context, writer);
return writer.toString();
} catch (Exception e) {
log.error("Exception occured while processing velocity template:" + e.getMessage());
}
return "";
}
public Map<String,Object> getPdfFilePath(String prjId) throws Exception{
Map<String,Object> fileInfo = new HashMap<>();
String fileName = "";
String filePath = CommonFunction.emptyCheckProperty("reviewReport.path", "/reviewReport");
Project project = new Project();
project.setPrjId(prjId);
project = projectMapper.selectProjectMaster(project);
oss.fosslight.domain.File pdfFile = null;
if(!isEmpty(project.getZipFileId())) {
pdfFile = verificationMapper.selectVerificationFile(project.getZipFileId());
fileName = pdfFile.getOrigNm();
filePath += java.io.File.separator + fileName;
} else {
pdfFile = verificationMapper.selectVerificationFile(project.getReviewReportFileId());
fileName = pdfFile.getOrigNm();
filePath += java.io.File.separator + prjId + java.io.File.separator + fileName;
}
// Check File Exist
java.io.File file = new java.io.File(filePath);
if(!file.exists()){
throw new Exception("Don't Exist PDF");
}
fileInfo.put("fileName",fileName);
fileInfo.put("filePath",filePath);
return fileInfo;
}
}
| 9,818 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
CryptUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/CryptUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* 암복호화 유틸 클래스
*/
public class CryptUtil {
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
/**
* AES 256 으로 암호화
*
* @param message
* @param key
*
* @return
*
* @throws java.io.UnsupportedEncodingException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeySpecException
*/
public static String encryptAES256(String message, String key) throws Exception {
if (message == null || message.trim().length() == 0) {
return message;
}
byte[] textBytes = message.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeBase64String(cipher.doFinal(textBytes));
}
/**
* AES 256 으로 복호화
*
* @param encMessage
* @param key
*
* @return
*
* @throws java.io.UnsupportedEncodingException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static String decryptAES256(String encMessage, String key) throws Exception {
if (encMessage == null || encMessage.trim().length() == 0) {
return encMessage;
}
byte[] textBytes = Base64.decodeBase64(encMessage);
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
}
}
| 2,834 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
DateUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/DateUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DurationFieldType;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.context.i18n.LocaleContextHolder;
import oss.fosslight.common.CoConstDef;
/**
* DESC : Joda Time 을 사용하여 날짜, 시간 및 요일 계산, 유효성 체크와 포맷 변경 등의 기능을 제공한다.<br><br>
*
* Apache LICENSE-2.0의 Anyframe Utils(Version 1.0.1)을 기반으로 작성된 클래스임을 명시한다.
*
*/
public final class DateUtil {
private DateUtil() { }
public static final int HOURS_24 = 24;
public static final int MINUTES_60 = 60;
public static final int SECONDS_60 = 60;
public static final int MILLI_SECONDS_1000 = 1000;
/** Date pattern */
public static final String DATE_PATTERN_DASH = "yyyy-MM-dd";
/** Time pattern */
public static final String TIME_PATTERN = "HH:mm";
/** Date Time pattern */
public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/** Date HMS pattern */
public static final String DATE_HMS_PATTERN = "yyyyMMddHHmmss";
public static final String DATE_HMS_PATTERN2 = "yyyyMMddHHmm";
/** Time stamp pattern */
public static final String TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
/** year pattern (yyyy)*/
public static final String YEAR_PATTERN = "yyyy";
/** month pattern (MM) */
public static final String MONTH_PATTERN = "MM";
/** day pattern (dd) */
public static final String DAY_PATTERN = "dd";
/** date pattern (yyyyMMdd) */
public static final String DATE_PATTERN = "yyyyMMdd";
/** date pattern (yyyy년 M월 d일) */
public static final String DATE_DISP_SIMPLE_PATTERN = "yyyy년 M월 d일";
public static final String DATE_DISP_SIMPLE_PATTERN_TIME = "yyyy년 M월 d일 HH시mm분";
public static final String DATE_DISP_PATTERN = "yyyy년 M월 d일 (E)";
/** hour, minute, second pattern (HHmmss) */
public static final String TIME_HMS_PATTERN = "HHmmss";
/** hour, minute, second pattern (HH:mm:ss) */
public static final String TIME_HMS_PATTERN_COLONE = "HH:mm:ss";
/**
* 현재 날짜, 시간을 조회하여 문자열 형태로 반환한다.<br>
*
* @return (yyyy-MM-dd HH:mm:ss) 포맷으로 구성된 현재 날짜와 시간
*/
public static String getCurrentDateTime() {
return getCurrentDateTime(DATE_TIME_PATTERN);
}
/**
* 현재 날짜, 시간을 조회을 조회하고, pattern 형태의 포맷으로 문자열을 반환한다.<br><br>
*
* DateUtils.getCurrentDateTime("yyyy년 MM월 dd일 hh시 mm분 ss초") = "2012년 04월 12일 20시 41분 50초"<br>
* DateUtils.getCurrentDateTime("yyyy-MM-dd hh-mm-ss") = "2012-04-12 20:41:50"
*
* @param pattern 날짜 및 시간에 대한 포맷
* @return patter 포맷 형태로 구성된 현재 날짜와 시간
*/
public static String getCurrentDateTime(String pattern) {
DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return fmt.print(dt);
}
/**
* 현재 년월을 조회하여 "yyyy-MM" 포맷의 문자열을 반환한다.
*
* @return (yyyy-MM) 포맷으로 구성된 현재 년월
*/
public static String getThisMonth() {
return getCurrentDateTime("yyyy-MM");
}
/**
* 현재 년월을 조회하고, pattern 형태의 포맷으로 문자열을 반환한다.
*
* @param pattern 날짜 및 시간에 대한 포맷
* @return patter 포맷 형태로 구성된 현재 년월
*/
public static String getThisMonth(String pattern) {
return getCurrentDateTime(pattern);
}
/**
* 현재 년을 조회하여 "yyyy" 포맷의 문자열을 반환한다.
*
* @return (yyyy-MM) 포맷으로 구성된 현재 년도
*/
public static String getThisYear() {
return getCurrentDateTime("yyyy");
}
/**
* 입력받은 일자의 요일을 반환한다.<br><br>
*
* DateUtils.getDayOfWeek("2010-11-26") = "금"
*
* @param str (yyyy-MM-dd) 포맷의 문자열
* @return 입력받은 일자에 해당하는 요일
*/
public static String getDayOfWeek(String str) {
return getDayOfWeek(str, true, LocaleContextHolder.getLocale());
}
public static String getDayOfWeek(String str, Boolean abbreviation, Locale locale) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(str);
DateTime.Property dayOfWeek = dt.dayOfWeek();
return abbreviation ? dayOfWeek.getAsShortText(locale) : dayOfWeek.getAsText(locale);
}
public static int getDays(Calendar cal1, Calendar cal2) {
long min = getMinutes(cal1, cal2);
return (int) (min / (HOURS_24 * MINUTES_60));
}
public static int getDays(String startDate, String endDate) {
return getDays(startDate, endDate, DATE_PATTERN_DASH);
}
public static int getDays(String startDate, String endDate, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
DateTime startDateTime = fmt.parseDateTime(startDate);
DateTime endDateTime = fmt.parseDateTime(endDate);
long startMillis = startDateTime.getMillis();
long endMillis = endDateTime.getMillis();
int result = (int) (startMillis / (60 * 60 * 1000 * 24));
int result1 = (int) (endMillis / (60 * 60 * 1000 * 24));
return result1 - result;
}
public static boolean equals(Date date1, String date2) {
return equals(date1, date2, DATE_PATTERN_DASH);
}
public static boolean equals(Date date1, String date2, String date2pattern) {
Date date = convertStringToDate(date2, date2pattern);
return equals(date1, date);
}
public static boolean equals(Date date1, Date date2) {
if (date1.getTime() == date2.getTime()) {
return true;
}
return false;
}
public static boolean greaterThan(Date date1, String date2) {
return greaterThan(date1, date2, DATE_PATTERN_DASH);
}
public static boolean greaterThan(Date date1, String date2, String date2pattern) {
Date date = convertStringToDate(date2, date2pattern);
return greaterThan(date1, date);
}
public static boolean greaterThan(Date date1, Date date2) {
if (date1.getTime() > date2.getTime()) {
return true;
}
return false;
}
public static boolean greaterThan(Timestamp timestamp1, String timestamp2) {
return greaterThan(timestamp1, timestamp2, TIMESTAMP_PATTERN);
}
public static boolean greaterThan(Timestamp timestamp1, String timestamp2, String timestamp2pattern) {
Timestamp date = convertStringToTimestamp(timestamp2, timestamp2pattern);
return greaterThan(timestamp1, date);
}
public static boolean greaterThan(Timestamp timestamp1, Timestamp timestamp2) {
if (timestamp1.getTime() > timestamp2.getTime()) {
return true;
}
return false;
}
public static String addDays(String date, int days) {
if (days == 0) {
return date;
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(date);
DateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), days);
return fmt.print(subtracted);
}
public static String addDaysYYYYMMDD(String date, int days) {
if (days == 0) {
return date;
}
date = date.replaceAll("[^\\d]*", "");
if (date.length() > 8) {
date = date.substring(0, 8);
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN);
DateTime dt = fmt.parseDateTime(date);
DateTime subtracted = dt.withFieldAdded(DurationFieldType.days(), days);
return fmt.print(subtracted);
}
public static String addMonths(String date, int months) {
if (months == 0) {
return date;
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(date);
DateTime subtracted = dt.withFieldAdded(DurationFieldType.months(), months);
return fmt.print(subtracted);
}
public static String addYears(String date, int years) {
if (years == 0) {
return date;
}
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(date);
DateTime subtracted = dt.withFieldAdded(DurationFieldType.years(), years);
return fmt.print(subtracted);
}
public static String addYearMonthDay(String date, int years, int months, int days) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(date);
if (years != 0) {
dt = dt.withFieldAdded(DurationFieldType.years(), years);
}
if (months != 0) {
dt = dt.withFieldAdded(DurationFieldType.months(), months);
}
if (days != 0) {
dt = dt.withFieldAdded(DurationFieldType.days(), days);
}
return fmt.print(dt);
}
public static String getFirstDateOfMonth(String date) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(date);
DateTime dtRet = new DateTime(dt.getYear(), dt.getMonthOfYear(), 1, 0, 0, 0, 0);
return fmt.print(dtRet);
}
public static String getLastDateOfMonth(String date) {
String firstDateOfMonth = getFirstDateOfMonth(date);
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(firstDateOfMonth);
dt = dt.plusMonths(1).minusDays(1);
return fmt.print(dt);
}
public static String getFirstDateOfPrevMonth(String date) {
String firstDateOfMonth = getFirstDateOfMonth(date);
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(firstDateOfMonth);
dt = dt.minusMonths(1);
return fmt.print(dt);
}
public static String getLastDateOfPrevMonth(String date) {
String firstDateOfMonth = getFirstDateOfMonth(date);
DateTimeFormatter fmt = DateTimeFormat.forPattern(DATE_PATTERN_DASH);
DateTime dt = fmt.parseDateTime(firstDateOfMonth);
dt = dt.minusDays(1);
return fmt.print(dt);
}
public static boolean isDate(String date) {
return isDate(date, DATE_PATTERN_DASH);
}
public static boolean isDate(String date, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
DateTime dt = new DateTime();
try {
dt = fmt.parseDateTime(date);
} catch (Exception e) {
return false;
}
if (!fmt.print(dt).equals(date)) {
return false;
}
return true;
}
/**
* 입력된 시간이 유효한 시간인지를 체크한다.<br><br>
*
* DateUtils.isTime("11:56") = true<br>
* DateUtils.isTime("31:56") = false
*
* @param time (HH:mm) 포맷형태의 시간
* @return 유효한 시간이면 true를 그렇지않으면 false를 반환
*/
public static boolean isTime(String time) {
return isTime(time, TIME_PATTERN);
}
/**
* 입력된 시간이 유효한 시간인지를 체크한다.
*
* @param time 입력시간
* @param pattern 포맷형태
* @return 유효한 시간이면 true를 그렇지 않으면 false를 반환
*/
public static boolean isTime(String time, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
DateTime dt = new DateTime();
try {
dt = fmt.parseDateTime(time);
} catch (Exception e) {
return false;
}
if (!fmt.print(dt).equals(time)) {
return false;
}
return true;
}
/**
* 문자열을 java.util.Date 타입으로 변경한다.<br><br>
*
* DateUtils.convertStringToDate("2010-12-14")
*
* @param str (yyyy-MM-dd) 포맷의 Date형으로 변환할 문자열
* @return (yyyy-MM-dd) 포맷의 Date형
*/
public static Date convertStringToDate(String str) {
return convertStringToDate(str, DATE_PATTERN_DASH);
}
/**
* 문자열을 java.util.Date 타입으로 변경한다.<br><br>
*
* DateUtils.convertStringToDate("2010-12-14 16:26:33", "yyyy-MM-dd HH:mm:ss")
*
* @param str pattern 포맷의 Date형으로 변환할 문자열
* @param pattern 변경할 포맷
* @return pattern 포맷의 Date형
*/
public static Date convertStringToDate(String str, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return fmt.parseDateTime(str).toDate();
}
/**
* java.util.Date 타입을 문자열로 변경한다.<br><br>
*
* DateUtils.convertDateToString(new Date(1292311593557l)) = "2010-12-14"
*
* @param date Date형의 입력된 날짜
* @return (yyyy-MM-dd) 포맷의 문자열
*/
public static String convertDateToString(Date date) {
return convertDateToString(date, DATE_PATTERN_DASH);
}
/**
* java.util.Date 타입을 패턴에 맞는 문자열로 변경한다.<br><br>
*
* DateUtils.convertDateToString(new Date(1292311593557l, "yyyy/MM/dd") = "2010/12/14"
*
* @param date Date형의 입력된 날짜
* @param pattern 날짜 패턴
* @return pattern 포맷의 문자열
*/
public static String convertDateToString(Date date, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return fmt.print(date.getTime());
}
/**
* 문자열을 java.sql.Date 타입으로 변환한다.<br><br>
*
* DateUtils.convertStringToSQLDate("2010-12-14")
*
* @param str (yyyy-MM-dd) 포맷의 Sql Date형으로 변환할 문자열
* @return (yyyy-MM-dd) 포맷의 Sql Date형
*/
public static java.sql.Date convertStringToSQLDate(String str) {
return convertStringToSQLDate(str, DATE_PATTERN_DASH);
}
/**
* 문자열을 java.sql.Date 타입으로 변환한다.<br><br>
*
* DateUtils.convertStringToSQLDate("2010/12/14", "yyyy/MM/dd")
*
* @param str pattern 포맷의 Sql Date형으로 변환할 문자열
* @param pattern 날짜 패턴
* @return pattern 포맷의 Sql Date형
*/
public static java.sql.Date convertStringToSQLDate(String str, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return new java.sql.Date(fmt.parseDateTime(str).getMillis());
}
/**
* 문자열을 java.sql.Timestamp 타입으로 변환한다.<br><br>
*
* DateUtils.convertStringToTimestamp("2010-12-14")
*
* @param str (yyyy-MM-dd) 포맷의 Timestamp형으로 변환할 문자열
* @return (yyyy-MM-dd) 포맷의 Timestamp형
*/
public static Timestamp convertStringToTimestamp(String str) {
return convertStringToTimestamp(str, DATE_PATTERN_DASH);
}
public static Timestamp convertStringToTimestamp(String str, String pattern) {
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
return new Timestamp(fmt.parseDateTime(str).getMillis());
}
/**
* java.sql.Timestamp 타입의 일자를 문자열로 변환한다.<br><br>
*
* DateUtils.convertTimestampToString(new Timestamp(1292311593000l))<br>
* DateUtils.convertTimestampToString(new Timestamp(new Date().getTime()))
*
* @param date (yyyy-MM-dd) 포맷의 문자열로 변환할 timestamp
* @return (yyyy-MM-dd) 포맷의 문자열
*/
public static String convertTimestampToString(Timestamp date) {
return convertTimestampToString(date, DATE_PATTERN_DASH);
}
/**
* java.sql.Timestamp 타입의 일자를 패턴에 맞는 문자열로 변환한다.<br><br>
*
* DateUtils.convertTimestampToString(new Timestamp(1292311593000l), "yyyy/MM/dd hh:mm") = "2010/12/14 16:26"
*
* @param date pattern 포맷의 문자열로 변환할 timestamp
* @param pattern 날짜 패턴
* @return pattern 포맷의 문자열
*/
public static String convertTimestampToString(Timestamp date, String pattern) {
if (date == null) {
return "";
}
return convertDateToString(date, pattern);
}
/**
* 문자열을 java.util.Calendar 타입으로 변환한다.<br><br>
*
* DateUtils.convertStringToCalender("20101214123412")
*
* @param str Calendar형으로 변환할 (yyyyMMddHHmmss) 포맷의 문자열
* @return Calendar
*/
public static Calendar convertStringToCalender(String str) {
if ((str == null) || (str.length() < 14)) {
return null;
}
String year = str.substring(0, 4);
String month = str.substring(4, 6);
String day = str.substring(6, 8);
String hour = str.substring(8, 10);
String minute = str.substring(10, 12);
String second = str.substring(12, 14);
return (new GregorianCalendar(StringUtil.string2integer(year), StringUtil.string2integer(month) - 1, StringUtil
.string2integer(day), StringUtil.string2integer(hour), StringUtil.string2integer(minute), StringUtil
.string2integer(second)));
}
/**
* java.util.Calendar타입의 일자를 문자열로 변환한다.<br><br>
*
* DateUtils.convertCalendarToString(new GregorianCalendar(2010, 11, 14, 12, 34, 12)) = "20101214123412000"
*
* @param calendar 문자열로 변환할 calendar
* @return (yyyyMMddHHmmss) 포맷 형태의 문자열
*/
public static String convertCalendarToString(Calendar calendar) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
return dateFormat.format(calendar.getTime()) + "000";
}
public static String convertStringToString(String str, String basePattern, String wantedPattern) {
DateTimeFormatter basefmt = DateTimeFormat.forPattern(basePattern);
DateTimeFormatter wantedfmt = DateTimeFormat.forPattern(wantedPattern);
DateTime dt = basefmt.parseDateTime(str);
return wantedfmt.print(dt);
}
/**
* 입력된 두 일자 사이의 분을 계산하여 반환한다.<br><br>
*
* DateUtils.getMinutes(new GregorianCalendar(2010, 11, 14, 12, 34, 12), new GregorianCalendar(2010, 11, 14, 13, 32, 12)) = 58
*
* @param cal1 입력된 calendar1
* @param cal2 입력된 calendar2
* @return 입력된 두 일자 사이의 분
*/
public static int getMinutes(Calendar cal1, Calendar cal2) {
long utc1 = cal1.getTimeInMillis();
long utc2 = cal2.getTimeInMillis();
long result = (utc2 - utc1) / (SECONDS_60 * MILLI_SECONDS_1000);
return (int) result;
}
/**
* 입력된 두 일자 사이의 분을 계산하여 반환한다.<br><br>
*
* DateUtils.getMinutes("20121212012321","20121212014321") = 20
*
* @param date1 (yyyyMMddHHmmss) 포맷의 문자열
* @param date2 (yyyyMMddHHmmss) 포맷의 문자열
* @return 입력된 두 일자 사이의 분
*/
public static int getMinutes(String date1, String date2) {
Calendar cal1 = convertStringToCalender(date1);
Calendar cal2 = convertStringToCalender(date2);
if (cal1 == null || cal2 == null) {
return -1;
}
return getMinutes(cal1, cal2);
}
/**
* 어제 일자를 반환한다.
*
* @return (yyyy-MM-dd) 포맷의 어제 일자
*/
public static String getYesterday() {
return getYesterday(DATE_PATTERN_DASH);
}
/**
* 어제 일자를 반환한다.
*
* @param pattern 날짜 포맷
* @return pattern 포맷의 어제 일자
*/
public static String getYesterday(String pattern) {
Calendar cal = getCalendar();
cal.add(Calendar.DATE, -1);
Date date = cal.getTime();
return convertDateToString(date, pattern);
}
/**
* 한국 시간대에 맞는java.util.Calendar 타입의 일자를 반환한다.
*
* @return Calendar 타입
*/
public static Calendar getCalendar() {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"), Locale.KOREA);
calendar.setTime(new Date());
return calendar;
}
/**
* 두 일자 사이의 일자 목록을 반환한다.<br><br>
*
* DateUtils.getDates("2010-12-17", "2010-12-20") = 2010-12-17, 2010-12-18, 2010-12-19, 2010-12-20
*
* @param startDay (yyyy-MM-dd) 포맷의 시작일
* @param endDay (yyyy-MM-dd) 포맷의 종료일
* @return 시작일과 종료일 사이의 일자 목록(String 배열)
*/
public static String[] getDates(String startDay, String endDay) {
return getDates(startDay, endDay, DATE_PATTERN_DASH);
}
/**
* 두 일자 사이의 일자 목록을 반환한다.<br><br>
*
* DateUtils.getDates("2010/12/17", "2010/12/20", "yyyy/MM/dd") = 2010/12/17, 2010/12/18, 2010/12/19, 2010/12/20
*
* @param startDay 시작일
* @param endDay 종료일
* @param pattern 일자 포맷
* @return pattern 포맷 형식의 시작일과 종요일 사이의 일자 목록(String 배열)
*/
public static String[] getDates(String startDay, String endDay, String pattern) {
List<String> result = new ArrayList<String>();
result.add(startDay);
Calendar cal = getCalendar();
cal.setTime(convertStringToDate(startDay, pattern));
String nextDay = convertDateToString(cal.getTime(), pattern);
while (!nextDay.equals(endDay)) {
cal.add(Calendar.DATE, 1);
nextDay = convertDateToString(cal.getTime(), pattern);
result.add(nextDay);
}
return result.toArray(new String[0]);
}
/**
* 현재 일자를 yyyy-MM-dd 패턴의 문자열로 반환한다.<br><br>
*
* DateUtils.getCurrentDateAsString = 2009-04-28
*
* @return (yyyy-MM-dd) 포맷 형태의 현재 일자
*/
public static String getCurrentDateAsString() {
return getCurrentDateAsString(DATE_PATTERN_DASH);
}
/**
* 현재 일자를 지정된 패턴의 문자열로 반환한다.<br><br>
*
* DateUtils.getCurrentDateAsString("yyyyMMdd") = 20090428
*
* @param pattern 일자의 포맷 형태
* @return patter 포맷 형태의 현재 일자
*/
public static String getCurrentDateAsString(String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(new Date());
}
/**
* 현재 일자를 java.sql.Date 타입으로 반환한다.
*
* @return java.sql.Date 타입의 현재 일자
*/
public static java.sql.Date getCurrentDate() {
return new java.sql.Date((new java.util.Date()).getTime());
}
/**
* 현재 시각에 대한 Time 객체를 반환한다.
*
* @return java.sql.Time 타입의 현재 시각
*/
public static Time getCurrentTime() {
return new Time(new Date().getTime());
}
/**
* 현재 시각에 대한 Time 문자열을 반환한다.
*
* @return (HH:mm:ss) 포맷의 현재 시각
*/
public static String getCurrentTimeAsString() {
return new Time(new Date().getTime()).toString();
}
/**
* 현재 시각에 대한 Timestamp 객체를 반환한다.
*
* @return java.sql.Timestamp 타입의 현재 시각
*/
public static Timestamp getCurrentTimestamp() {
Timestamp timestamp = new Timestamp(new Date().getTime());
return timestamp;
}
/**
* 현재 시각에 대한 Timestamp 문자열을 구한다.
*
* @return (yyyy-MM-dd HH:mm:ss.SSS) 포맷의 현재 시각
*/
public static String getCurrentTimestampAsString() {
return getCurrentTimestamp().toString();
}
/**
* 입력된 일자를 기준으로 해당년도가 윤년인지 여부를 반환한다.
*
* @param inputDate (yyyy-MM-dd) 형식의 일자
* @return 윤년이면 true를 그렇지 않으면 false를 반환
*/
public static boolean isLeapYear(String inputDate) {
return isLeapYear(Integer.parseInt(inputDate.substring(0, 4)));
}
/**
* 정수형태로 입력된 년도를 기준으로 해당년도가 윤년인지 여부를 반환한다.
*
* @param year 년도
* @return year이 윤년이면 true를 그렇지 않으면 false를 반환
*/
public static boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? true : false;
}
/**
* yyyy-mm-dd hh:mm:ss.SSS or yyyy-mm-dd 로 받은 타입을 yyyy년 yy월 mm일 타입으로 변환한다.
*
* @param date
* @return
*/
public static String dateTypeConvert(String date){
if (!date.isEmpty()){
date = date.substring(0, 10);
String[] temp = date.split("-");
date = date.format("%s년 %s월 %s일", temp[0], temp[1], temp[2]);
}
return date;
}
/**
* 파라미터의 해당하는 년월의 전달을 구한다.
* @param yearMonth yyyyMM
* @param minVal
* @return
*/
public static String getBeforeYearMonthByYM(String yearMonth, int minVal){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Calendar cal = Calendar.getInstance();
int year = Integer.parseInt(yearMonth.substring(0,4));
int month = Integer.parseInt(yearMonth.substring(4,6));
cal.set(year, month-minVal, 0);
String beforeYear = dateFormat.format(cal.getTime()).substring(0,4);
String beforeMonth = dateFormat.format(cal.getTime()).substring(4,6);
String retStr = beforeYear + beforeMonth;
return retStr;
}
/**
* 해당년월의 마지막 날짜를 구한다.
* @param yearMonth yyyyMM
* @return
*/
public static String getLastDayOfMonth(String yearMonth){
String year = yearMonth.substring(0,4);
String month = yearMonth.substring(4,6);
int _year = Integer.parseInt(year);
int _month = Integer.parseInt(month);
Calendar calendar = Calendar.getInstance();
calendar.set(_year, (_month-1), 1); //월은 0부터 시작
String lastDay = String.valueOf(calendar.getActualMaximum(Calendar.DATE));
return lastDay;
}
/**
* 문자열로 입력된 날짜의 포맷을 입력받은 포맷 문자열로 변경한다
* yyyyMMdd -> 사용자 지정 포멧
* @param date
* @param convDateFormat
* @return
*/
public static String dateFormatConvert(String date, String orgDateFormat, String convDateFormat) {
try{
if (StringUtil.isEmpty(date)) {
return date;
}
SimpleDateFormat sdfOrg = new SimpleDateFormat(orgDateFormat);
SimpleDateFormat sdfConv = new SimpleDateFormat(convDateFormat);
Date orgDate = sdfOrg.parse(date);
return sdfConv.format(orgDate);
} catch (Exception e) {
return date;
}
}
/**
* Date 표시 형식 변환
* yyyyMMdd -> 사용자 지정 포멧
* @param date
* @param convDateFormat
* @return
*/
public static String dateFormatConvert(String date, String convDateFormat) {
return dateFormatConvert(date, DATE_PATTERN, convDateFormat);
}
/**
* Date 표시 형식 변환
* yyyyMMdd -> yyyy년 M월 d일
* @param date
* @param convDateFormat
* @return
*/
public static String dateFormatConvert(String date) {
return dateFormatConvert(date, DATE_PATTERN, DATE_DISP_SIMPLE_PATTERN);
}
public static boolean isNewestPeriod(String date, int period){
return isNewestPeriod(DateUtil.convertStringToSQLDate(date), period);
}
public static boolean isNewestPeriod(String date, String format, int period){
return isNewestPeriod(DateUtil.convertStringToSQLDate(date, format), period);
}
public static boolean isNewestPeriod(Date date, int period){
// 현재 날짜
String toDay = DateUtil.getCurrentDateAsString();
int dCount = DateUtil.getDays(DateUtil.convertDateToString(date, CoConstDef.DISP_FORMAT_DATE_YYYYMMDD), toDay);
return dCount >= 0 && dCount <= period-1;
}
public static boolean isLastPeriod(String date, int period){
return isLastPeriod(DateUtil.convertStringToSQLDate(date), period);
}
public static boolean isLastPeriod(String date, String format, int period){
return isLastPeriod(DateUtil.convertStringToSQLDate(date, format), period);
}
public static boolean isLastPeriod(Date date, int period){
// 현재 날짜
String toDay = DateUtil.getCurrentDateAsString();
int dCount = DateUtil.getDays(toDay, DateUtil.convertDateToString(date, CoConstDef.DISP_FORMAT_DATE_YYYYMMDD));
return dCount >= 0 && dCount <= period-1;
}
public static int getPeriodStatus(String date1, String date2){
return getPeriodStatus(convertStringToSQLDate(date1), convertStringToSQLDate(date2));
}
public static int getPeriodStatus(String date1, String date2, String format){
return getPeriodStatus(convertStringToSQLDate(date1, format), convertStringToSQLDate(date2, format));
}
public static int getPeriodStatus(Date date1, Date date2){
int ret = 0; // 진행중
// 현재 날짜
Date toDay = convertStringToSQLDate(getCurrentDateAsString());
if (!((toDay.compareTo(date1) >= 0) && (toDay.compareTo(date2) <= 0))){
ret = (toDay.compareTo(date1) < 0) ? -1 : 1;
}
return ret;
}
public static int getDiffMonth(String date1, String date2) {
Date fromDate = convertStringToSQLDate(date1, DATE_PATTERN);
Date toDate = convertStringToSQLDate(date2, DATE_PATTERN);
int m1 = fromDate.getYear() * 12 + fromDate.getMonth();
int m2 = toDate.getYear() * 12 + toDate.getMonth();
return m2 - m1 + 1;
}
}
| 30,301 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
StringUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/StringUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.CharUtils;
import org.springframework.web.util.HtmlUtils;
/**
* DESC : 문자열 관련 검색, 변환, 치환, 유효성 체크 등의 기능을 제공한다.<br><br>
*
* Apache LICENSE-2.0의 Anyframe Utils(Version 1.0.1)을 기반으로 작성된 클래스임을 명시한다.<br>
* 또한, Spring의 StringUtils, commons-lang의 StringUtils의 래퍼 기능을 제공한다.
*
*/
public final class StringUtil {
private StringUtil() {}
public static final String DEFAULT_EMPTY_STRING = "";
/** UTF-8용 1바이트 캐릭터 셋 */
private static final int ONE_BYTE = 0x00007F;
/** UTF-8용 2바이트 캐릭터 셋 */
private static final int TWO_BYTE = 0x0007FF;
/** UTF-8용 3바이트 캐릭터 셋 */
private static final int THREE_BYTE = 0x00FFFF;
/**
* The empty String <code>""</code>.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/** 코드를 받아 문자열로 변환에 사용 INT*/
private static final int HEX_TO_STRING_INT = 16;
/**
* 문자열을 "…"가 포함된 지정한 사이즈로 문자열을 축소한다 최대크기는 4보다 커야한다.<br />
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str 문자열
* @param maxWidth 최대크기
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String abbreviate(String str, int maxWidth) {
return org.apache.commons.lang.StringUtils.abbreviate(str, maxWidth);
}
/**
* 문자열을 "…"가 포함된 지정한 사이즈로 문자열을 앞/뒤로 축소한다.<br />
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str 문자열
* @param offset left edge of source String
* @param maxWidth 최대크기
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String abbreviate(String str, int offset, int maxWidth) {
return org.apache.commons.lang.StringUtils.abbreviate(str, offset, maxWidth);
}
/**
* 문자열중 첫번째 문자를 대문자로 만든다.<br />
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String capitalize(String str) {
return org.apache.commons.lang.StringUtils.capitalize(str);
}
/**
* 문자열의 길이가 변환길이가 되도록 문자열 좌우에 공백문자를 우측부터 하나씩 추가한다.<br />
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str 문자열
* @param size 변환길이
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String center(String str, int size) {
return org.apache.commons.lang.StringUtils.center(str, size);
}
/**
* 문자열의 길이가 변환길이가 되도록 문자열 좌우에 삽입문자를 하나씩 우측부터 추가한다.<br />
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab"
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str 문자열
* @param size 변환길이
* @param padChar 삽입문자
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String center(String str, int size, char padChar) {
return org.apache.commons.lang.StringUtils.center(str, size, padChar);
}
/**
* 문자열의 길이가 변환길이가 되도록 문자열 좌우에 삽입문자열을 하나씩 우측부터 추가한다.<br />
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab"
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str 문자열
* @param size 변환길이
* @param padStr 삽입문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String center(String str, int size, String padStr) {
return org.apache.commons.lang.StringUtils.center(str, size, padStr);
}
/**
* 문자열 맨 끝에있는 "<code>\n</code>",<br />
* "<code>\r</code>", or "<code>\r\n</code>"을 제거한다.<br />
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String chomp(String str) {
return org.apache.commons.lang.StringUtils.chomp(str);
}
/**
* 문자열 맨 끝에 구분자가 있으면 이를 제거한다.<br />
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str 문자열
* @param separator 구분자
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String chomp(String str, String separator) {
return org.apache.commons.lang.StringUtils.chomp(str, separator);
}
/**
* 문자열 맨 끝에있는 문자 하나를 제거한다.<br />
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String chop(String str) {
return org.apache.commons.lang.StringUtils.chop(str);
}
/**
* 두단어를 사전 편찬 순서대로 비교한다.<br><br>
*
* StringUtils.compareTo("Anyframe Java Test", "Anyframe Java Test") = 0
*
* @param sourceStr 단어1
* @param anotherStr 단어2
* @return 두 단어가 같을 경우 0
* 단어1이 단어2보다 작을 경우 0 미만
* 단어1이 단어2보다 클 경우 0 초과
* @see String#compareTo(String)
*/
public static int compareTo(String sourceStr, String anotherStr) {
if (sourceStr == null || anotherStr == null) {
return -1;
}
return sourceStr.compareTo(anotherStr);
}
/**
* 두단어를 대소 문자 무시하고 사전 편찬 순서대로 비교한다.<br><br>
*
* StringUtils.compareToIgnoreCase("anyframe java test", "Anyframe Java Test") = 0
*
* @param sourceStr 단어1
* @param anotherStr 단어2
* @return 두 단어가 같을 경우 0
* 단어1이 단어2보다 작을 경우 0 미만
* 단어1이 단어2보다 클 경우 0 초과
* @see String#compareToIgnoreCase(String)
*/
public static int compareToIgnoreCase(String sourceStr, String anotherStr) {
if (sourceStr == null || anotherStr == null) {
return -1;
}
return sourceStr.compareToIgnoreCase(anotherStr);
}
/**
* 문자열 내에서 검색문자가 포함하고 있는지 확인한다.<br />
*
* <code>null</code> 또는 공백일경우 <code>false</code>를 반환한다.<br />
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param str 문자열
* @param searchChar 검색문자
* @return 검색문자가 포함되어있는 경우 true ,
* 포함되어있지 않거나 입력 문자열이 <code>null</code>인경우 false
*/
public static boolean contains(String str, char searchChar) {
return org.apache.commons.lang.StringUtils.contains(str, searchChar);
}
/**
* 문자열 내에서 검색문자열이 포함하고 있는지 확인한다.<br />
*
* <code>null</code>일경우 <code>false</code>를 반환한다.<br />
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @return 검색문자가 포함되어있는 경우 true ,
* 포함되어있지 않거나 입력 문자열이 <code>null</code>인경우 false
*/
public static boolean contains(String str, String searchStr) {
return org.apache.commons.lang.StringUtils.contains(str, searchStr);
}
/**
* 문자열 내에서 검색문자열이 대소문자를 무시하고 포함하고 있는지 확인한다.<br />
*
* <code>null</code>일경우 <code>false</code>를 반환한다.<br />
*
* <pre>
* StringUtils.containsIgnoreCase(null, *) = false
* StringUtils.containsIgnoreCase(*, null) = false
* StringUtils.containsIgnoreCase("", "") = true
* StringUtils.containsIgnoreCase("abc", "") = true
* StringUtils.containsIgnoreCase("abc", "a") = true
* StringUtils.containsIgnoreCase("abc", "z") = false
* StringUtils.containsIgnoreCase("abc", "A") = true
* StringUtils.containsIgnoreCase("abc", "Z") = false
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @return 검색문자가 포함되어있는 경우 true ,
* 포함되어있지 않거나 입력 문자열이 <code>null</code>인경우 false
*/
public static boolean containsIgnoreCase(String str, String searchStr) {
return org.apache.commons.lang.StringUtils.containsIgnoreCase(str, searchStr);
}
/**
* 입력된 문자열이 주어진 character들을 포함하는지 체크<br><br>
*
* StringUtils.containsInvalidChars("abc/", new char[] { '*', '/' }) = true
*
* @param str 문자열
* @param invalidChars 체크할 캐릭터들
* @return 문자열에 캐릭터들이 포함되어 있을 경우 true
*/
public static boolean containsInvalidChars(String str, char[] invalidChars) {
if (str == null || invalidChars == null) {
return false;
}
int strSize = str.length();
int validSize = invalidChars.length;
for (int i = 0; i < strSize; i++) {
char ch = str.charAt(i);
for (int j = 0; j < validSize; j++) {
if (invalidChars[j] == ch) {
return true;
}
}
}
return false;
}
/**
* 입력된 문자열이 주어진 character들을 포함하는지 체크<br><br>
*
* StringUtils.containsInvalidChars("abc*abc", "*") = true
*
* @param str 문자열
* @param invalidChars 체크할 캐릭터들
* @return 문자열에 캐릭터들이 포함되어 있을 경우 true
*/
public static boolean containsInvalidChars(String str, String invalidChars) {
if (str == null || invalidChars == null) {
return true;
}
return containsInvalidChars(str, invalidChars.toCharArray());
}
/**
* 입력된 문자열에 대해서 같은 character가 동일하게 반복하는지 체크<br><br>
*
* StringUtils.containsMaxSequence("abbbbc", "4") = true
*
* @param str 문자열
* @param maxSeqNumber 같은 캐릭터가 반복되는 횟수
* @return 같은 캐릭터가 주어진 횟수만큼 반복될 경우 true
*/
public static boolean containsMaxSequence(String str, String maxSeqNumber) {
int occurence = 1;
int max = Integer.valueOf(maxSeqNumber);
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < (sz - 1); i++) {
if (str.charAt(i) == str.charAt(i + 1)) {
occurence++;
if (occurence == max) {
return true;
}
} else {
occurence = 1;
}
}
return false;
}
/**
* 입력된 underscore 형태의 문자열을 camel case 형태로 변환<br><br>
*
* StringUtils.convertToCamelCase("anyframe_java_test") = "anyframeJavaTest"
*
* @param underscore underscore 형태의 문자열
* @return camel case 형태로 변환된 문자열
*/
public static String convertToCamelCase(String underscore) {
return convertToCamelCase(underscore, "_");
}
/**
* 주어진 char의 형태에 맞게 잘라진 문자열을 camel case 형태로 변환<br><br>
*
* StringUtils.convertToCamelCase("anyframe-java-test", "-") = "anyframeJavaTest"
*
* @param targetString 대상 문자열
* @param posChar 문자열을 자를 기준 캐릭터
* @return camel case 형태로 변환된 문자열
*/
public static String convertToCamelCase(String targetString, String posChar) {
StringBuilder result = new StringBuilder();
boolean nextUpper = false;
String allLower = targetString.toLowerCase();
for (int i = 0; i < allLower.length(); i++) {
char currentChar = allLower.charAt(i);
if (currentChar == CharUtils.toChar(posChar)) {
nextUpper = true;
} else {
if (nextUpper) {
currentChar = Character.toUpperCase(currentChar);
nextUpper = false;
}
result.append(currentChar);
}
}
return result.toString();
}
/**
* camel case 형태의 문자열을 underscore 형태의 문자열로 변환<br><br>
*
* StringUtils.convertToUnderScore("anyframeJavaTest") = "anyframe_java_test"
*
* @param camelCase camel case 형태의 문자열
* @return underscore 형태로 변환된 문자열
*/
public static String convertToUnderScore(String camelCase) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < camelCase.length(); i++) {
char currentChar = camelCase.charAt(i);
// This is starting at 1 so the result does not end up with an
// underscore at the begin of the value
if (i > 0 && Character.isUpperCase(currentChar)) {
result.append('_');
}
result.append(Character.toLowerCase(currentChar));
}
return result.toString();
}
/**
* 문자열중에 검색문자열이 포함되어있는 갯수를 반환한다.<br />
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str 문자열
* @param sub 검색문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static int countMatches(String str, String sub) {
return org.apache.commons.lang.StringUtils.countMatches(str, sub);
}
/**
* 한 String 객체(sub)의 패턴이 다른 String 객체(main)안에서 몇 번 등장하는지 계산한다. - 등장 패턴의 위치는<br>
* 좌측에서부터 계산하고 겹치지 않는 형태로 계산한다. + 예를 들어, "aa"는 "aaa"에서 두 번 등장하는 것이 아니라, <br>
* 한 번 등장하는 것으로 계산한다. <br><br>
*
* StringUtils.countPattern("aaa", "aa") = 1
*
* @param str
* the String to check
* @param pattern
* the pattern to count
* @return the number of occurrences
*/
public static int countPattern(String str, String pattern) {
if (str == null || pattern == null || "".equals(pattern)) {
return 0;
}
int count = 0;
int pos = 0;
while (str.indexOf(pattern, pos) != -1) {
int index = str.indexOf(pattern, pos);
count++;
pos = index + pattern.length();
}
return count;
}
/**
* 첫번째 문자열과 두번째 문자열을 비교해서 같으면 세번째 문자열을 다르면 네번재 문자열을 반환한다.<br><br>
*
* StringUtils.decode("Java", "Test", "Good", "Bad") = "bad"
*
* @param source 첫번째 문자열
* @param target 두번째 문자열
* @param result 두 문자열이 같을 때 반환할 문자열
* @param base 두 문자열이 다를 때 반환할 문자열
* @return 두 문자열이 같으면 세번째 문자열을 다르면 네번재 문자열을 반환
*/
public static String decode(String source, String target, String result, String base) {
if (source == null && target == null) {
return result;
} else if (source == null && target != null) {
return base;
} else if (source.trim().equals(target)) {
return result;
}
return base;
}
/**
* 문자열이 <code>null</code> 또는 공백 또는 공백문자 이면 <code>defaultStr</code>을 반환하고<br />
* 아니면 <code>str</code>을 반환한다.<br />
*
* <pre>
* StringUtils.defaultIfBlank(null, "NULL") = "NULL"
* StringUtils.defaultIfBlank("", "NULL") = "NULL"
* StringUtils.defaultIfBlank(" ", "NULL") = "NULL"
* StringUtils.defaultIfBlank("bat", "NULL") = "bat"
* StringUtils.defaultIfBlank("", null) = null
* </pre>
* @param str 문자열
* @param defaultStr 초기설정문자
* @return 결과문자열
*/
public static String defaultIfBlank(String str, String defaultStr) {
return org.apache.commons.lang.StringUtils.defaultIfEmpty(str, defaultStr);
}
/**
* 문자열이 <code>null</code> 또는 공백이면 <code>defaultStr</code>을 반환하고<br />
* 아니면 <code>str</code>을 반환한다.<br />
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
*
* @param str 문자열
* @param defaultStr 초기설정문자
* @return 결과문자열
*/
public static String defaultIfEmpty(String str, String defaultStr) {
return org.apache.commons.lang.StringUtils.defaultIfEmpty(str, defaultStr);
}
/**
* 문자열이 <code>null</code>이면 공백를 반환하고 아니면 <code>str</code>을 반환한다.<br />
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 공백
*/
public static String defaultString(String str) {
return org.apache.commons.lang.StringUtils.defaultString(str);
}
/**
* 문자열이 <code>null</code>이면 <code>defaultStr</code>을 반환하고<br />
* 아니면 <code>str</code>을 반환한다.<br />
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @param str 문자열
* @param defaultStr 초기설정문자
* @return 결과문자열, 문자열이 null일경우 초기설정문자
*/
public static String defaultString(String str, String defaultStr) {
return org.apache.commons.lang.StringUtils.defaultString(str, defaultStr);
}
/**
* 한 String 객체 안에서 특정 패턴 안에 포함된 모든 character들을 제거한다.<br><br>
*
* StringUtils.deleteChars("zzAccBxx", "AB") = "zzccxx"
*
* @param str
* the source String to search
* @param chars
* the char to search for and remove
* @return the substring with the char removed if found
*/
public static String deleteChars(String str, String chars) {
if (str == null || chars == null) {
return str;
}
String value = str;
for (int i = 0; i < chars.length(); i++) {
value = removeChar(value, chars.charAt(i));
}
return value;
}
/**
* 한 String 객체 안에서 특정 패턴을 제거한다. - 등장 패턴의 위치는 좌측에서부터 계산하고<br>
* 겹치지 않는 형태로 계산한다. + 따라서, 제거된 후에도 old 패턴은 남아 있을 수 있다.<br><br>
*
* StringUtils.deletePattern("aababa", "aba")는 "aba"<br>
* StringUtils.deletePattern("zzABCcc", "ABC") => "zzcc"
*
* @param str
* the source String to search
* @param pattern
* the String to search for and remove
* @return the substring with the string removed if found
*/
public static String deletePattern(String str, String pattern) {
return replacePattern(str, pattern, "");
}
/**
* 문자열중 공백문자가 있으면 모두 제거한다.<br />
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 문자열이 null일겨우 <code>null</code>
*/
public static String deleteWhitespace(String str) {
return org.apache.commons.lang.StringUtils.deleteWhitespace(str);
}
public static String deleteWhitespaceWithSpecialChar(String str) {
if (str == null) {
return "";
}
return deleteWhitespace(str).replaceAll("[^a-zA-Z0-9]", "");
}
/**
* StringTokenizer를 이용하지 않고 처리하여, 연속된 delimiter 사이는 비어 있는 token으로 간주된다. <br>
* 주어진 String이 null일 경우, null을 return한다. <br>
* delimiter가 null일 경우, 주어진 String을 하나의 element로 가지는 String[]를 return한다.<br><br>
*
* StringUtils.delimitedStringToStringArray("aaa.bbb.ccc.ddd", "."); = test[0]="aaa", test[1]="bbb"...
*
* @param str
* the silgle String to convert
* @param delimiter
* delimiter for conversioin
* @return array of String values
*/
public static String[] delimitedStringToStringArray(String str, String delimiter) {
if (str == null) {
return null;
}
if (delimiter == null) {
return new String[] {str};
}
List<String> tokens = new ArrayList<String>();
int pos = 0;
while (str.indexOf(delimiter, pos) != -1) {
int index = str.indexOf(delimiter, pos);
tokens.add(str.substring(pos, index));
pos = index + delimiter.length();
}
if (pos <= str.length()) {
tokens.add(str.substring(pos));
}
return tokens.toArray(new String[tokens.size()]);
}
/**
* 두문자열를 비교하여 다른부분을 반환한다.<br />
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 문자열1
* @param str2 문자열2
* @return 결과문자열
*/
public static String difference(String str1, String str2) {
return org.apache.commons.lang.StringUtils.difference(str1, str2);
}
/**
* 문자열이 검색문자로 끝나는지 확인한다.<br />
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* </pre>
*
* @param str 문자열
* @param suffix 검색문자
* @return 문자열이 검색문자로 끝나는경우와 문자열 양쪽모두
* <code>null</code>인경우 <code>true</code>
*/
public static boolean endsWith(String str, String suffix) {
return org.apache.commons.lang.StringUtils.endsWith(str, suffix);
}
/**
* 문자열이 검색문자로 대소문자 구분없이 끝나는지 확인한다.<br />
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @param str 문자열
* @param suffix 검색문자
* @return 문자열이 검색문자로 대소문자 구분없이 끝나는경우와 문자열 양쪽모두
* <code>null</code>인경우 <code>true</code>
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
return org.apache.commons.lang.StringUtils.endsWithIgnoreCase(str, suffix);
}
/**
* 두개의 문자열이 같은지 비교한다.<br />
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @param str1 첫번째 문자열
* @param str2 두번째 문자열
* @return 두 개의 문자열을 비교하여 같으면 true, 아니면 false를 반환
*/
public static boolean equals(String str1, String str2) {
return org.apache.commons.lang.StringUtils.equals(str1, str2);
}
/**
* 두개의 문자열을 영문 대소문자를 무시하고 같은지 비교한다.<br />
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param str1 첫번째 문자열
* @param str2 두번째 문자열
* @return 두 개의 문자열을 영문 대소문자를 무시하고 비교하여 같으면 true, 아니면 false를 반환
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2);
}
/**
* 두개의 문자열이 다른지 비교한다.<br />
*
* <pre>
* StringUtils.notEquals(null, null) = false
* StringUtils.notEquals(null, "abc") = true
* StringUtils.notEquals("abc", null) = true
* StringUtils.notEquals("abc", "abc") = false
* StringUtils.notEquals("abc", "ABC") = true
* </pre>
*
* @param str1 첫번째 문자열
* @param str2 두번째 문자열
* @return 두 개의 문자열을 비교하여 다르면 true, 아니면 false를 반환
*/
public static boolean notEquals(String str1, String str2) {
return !org.apache.commons.lang.StringUtils.equals(str1, str2);
}
/**
* 두개의 문자열을 영문 대소문자를 무시하고 다른지 비교한다.<br />
*
* <pre>
* StringUtils.notEqIgnoreCase(null, null) = false
* StringUtils.notEqIgnoreCase(null, "abc") = true
* StringUtils.notEqIgnoreCase("abc", null) = true
* StringUtils.notEqIgnoreCase("abc", "abc") = false
* StringUtils.notEqIgnoreCase("abc", "ABC") = false
* </pre>
*
* @param str1 첫번째 문자열
* @param str2 두번째 문자열
* @return 두 개의 문자열을 영문 대소문자를 무시하고 비교하여 다르면 true, 아니면 false를 반환
*/
public static boolean notEqIgnoreCase(String str1, String str2) {
return !org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2);
}
/**
* 해당하는 문자열에 대해서 byte 단위에 대해서 길이 계산해서 총 길이 반환<br><br>
*
* StringUtils.getByteLength("Anyframe Java Test") = 18
*
* @param str 문자열
* @return 문자열의 byte 단위 길이
*/
public static int getByteLength(String str) {
if (str == null) {
return -1;
}
int size = 0;
for (int i = 0; i < str.length(); i++) {
size += getByteLength(str.charAt(i));
}
return size;
}
private static int getByteLength(char charat) {
int charCode = charat;
if (charCode <= ONE_BYTE) {
return 1;
} else if (charCode <= TWO_BYTE) {
return 2;
} else if (charCode <= THREE_BYTE) {
return 3;
} else {
return 4;
}
}
/**
* 배열안의 문자열를 비교하여 같은부분의 문자열을 반환한다.<br />
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs 문자배열
* @return 결과문자열
*/
public static String getCommonPrefix(String[] strs) {
return org.apache.commons.lang.StringUtils.getCommonPrefix(strs);
}
/**
* 주어진 문자열에 대해서 해당하는 문자열이 포함되어 있는 숫자 반환<br><br>
*
* StringUtils.getContainsCount("Anyframe Java Test", "a") = 3
*
* @param str 주어진 문자열
* @param sub 검색할 문자열
* @return 문자열이 포함되어 있는 숫자
*/
public static int getContainsCount(String str, String sub) {
return org.springframework.util.StringUtils.countOccurrencesOf(str, sub);
}
/**
* 대소문자 구분없이 주어진 문자열에 대해서 해당하는 문자열이 포함되어 있는 갯수를 반환<br><br>
*
* StringUtils.getContainsCountIgnoreCase("Anyframe Java Test", "test") = 1
*
* @param str 주어진 문자열
* @param sub 검색할 문자열
* @return 문자열이 포함되어 있는 갯수
* @see org.springframework.util.StringUtils#countOccurrencesOf(String,
* String)
*/
public static int getContainsCountIgnoreCase(String str, String sub) {
return org.springframework.util.StringUtils.countOccurrencesOf(str.toLowerCase(), sub.toLowerCase());
}
/**
* 입력된 문자열을 주어진 token에 대해서 분리 후 마지막 문자열 반환<br><br>
*
* StringUtils.getLastString("Anyframe_Java_Test", "_") = "Test"
*
* @param origStr 문자열
* @param strToken 분리할 token
* @return token에 대해서 분리된 마지막 문자열
*/
public static String getLastString(String origStr, String strToken) {
StringTokenizer str = new StringTokenizer(origStr, strToken);
String lastStr = "";
while (str.hasMoreTokens()) {
lastStr = str.nextToken();
}
return lastStr;
}
/**
* 문자열1을 문자열2로 변환하기위해 치환,삽입,삭제하지 않으면 않되는 최소의 문자수를 반환한다.<br />
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","") = 0
* StringUtils.getLevenshteinDistance("","a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s 문자열1
* @param t 문자열2
* @return 문자열1을 문자열2로 변환하기위해 치환,삽입,삭제하지 않으면 않되는 최소의 문자수
*/
public static int getLevenshteinDistance(String s, String t) {
return org.apache.commons.lang.StringUtils.getLevenshteinDistance(s, t);
}
/**
* 입력된 문자열을 주어진 token에 대해서 분리 후 arraylist 형태로 반환<br><br>
*
* StringUtils.getStringArray("Anyframe/Java/Test", "/")
*
* @param str 문자열
* @param strToken 분리할 token
* @return token에 대해서 분리된 arraylist
*/
public static String[] getStringArray(String str, String strToken) {
if (str.indexOf(strToken) != -1) {
StringTokenizer st = new StringTokenizer(str, strToken);
String[] stringArray = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
stringArray[i] = st.nextToken();
}
return stringArray;
}
return new String[] {str};
}
/**
* 입력된 문자열을 ,(콤마)에 대해서 분리 후 List<String>으로 반환<br><br>
*
* @param lst 문자열
* @return ,(콤마)로 분리된 List
*/
public static List<String> getTokens(String lst) {
return getTokens(lst, ",");
}
/**
* 입력된 문자열을 주어진 separator에 대해서 분리 후 List<String>으로 반환<br><br>
*
* StringUtils.getTokens("Anyframe/Java/Test", "/")
*
* @param lst 문자열
* @param separator 분리할 기준 문자열
* @return 기준 문자열로 분리된 List
*/
public static List<String> getTokens(String lst, String separator) {
List<String> tokens = new ArrayList<String>();
if (lst != null) {
StringTokenizer st = new StringTokenizer(lst, separator);
while (st.hasMoreTokens()) {
String en = st.nextToken().trim();
tokens.add(en);
}
}
return tokens;
}
/**
* 코드를 받아 문자열로 변환한다(유니코드)
*
* @param str
* the String to convert
* @return UniCode String
*/
public static String hexToString(String str) {
String inStr = str;
char[] inChar = inStr.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < inChar.length; i += 4) {
String hex = str.substring(i, i + 4);
sb.append((char) Integer.parseInt(hex, HEX_TO_STRING_INT));
}
return sb.toString();
}
/**
* 문자열 내에서 시작인덱스로부터 첫번째 검색문자의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param str 문자열
* @param searchChar 찾을문자
* @param startPos 시작인덱스
* @return null 또는 빈 문자열은 INDEX_NOT_FOUND (-1)를 반환
*/
public static int indexOf(String str, char searchChar, int startPos) {
return org.apache.commons.lang.StringUtils.indexOf(str, searchChar, startPos);
}
public static int indexOf(String str, String searchChar) {
return org.apache.commons.lang.StringUtils.indexOf(str, searchChar);
}
/**
* 문자열 내에서 시작인덱스로부터 첫번째 검색문자열의 인덱스를 반환한다.<br />
*
* Null 문자열은-1을 반환<br />
* 부정적인 시작 위치는 0으로 처리<br />
* 빈 검색 문자열 항상 일치<br />
* 시작 위치가 문자열 길이 보다 큰 일치<br />
* 빈 검색 문자열<br />
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @param startPos 시작인덱스
* @return 검색 문자열의 첫 번째 인덱스 없는 경우-1 일치 하거나 null 문자열 입력
*/
public static int indexOf(String str, String searchStr, int startPos) {
return org.apache.commons.lang.StringUtils.indexOf(str, searchStr, startPos);
}
/**
* 문자열 내에서 검색문자배열중 포함하고 있는지 검색후<br />
* 검색된 첫번째 인덱스를 반환한다.<br />
*
* 문자열이 <code>null</code> 일경우 <code>-1</code>을 반환.<br />
* 검색배열이 <code>null</code> 또는 공백배열일경우 <code>-1</code>을 반환.<br />
* 배열내 검색문자열이 공백일경우 <code>0</code>을 반환. <br />
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str 문자열
* @param searchStrs 검색문자열
* @return 검색된 첫번째인덱스, 검색되지않은 경우 -1반환.
*/
public static int indexOfAny(String str, String[] searchStrs) {
return org.apache.commons.lang.StringUtils.indexOfAny(str, searchStrs);
}
/**
* 두문자열를 비교하여 다른부분의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param str1 문자열1
* @param str2 문자열2
* @return 결과문자열, 비교하여 같으면 -1
*/
public static int indexOfDifference(String str1, String str2) {
return org.apache.commons.lang.StringUtils.indexOfDifference(str1, str2);
}
/**
* 배열안의 문자열를 비교하여 다른부분의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param strs 문자배열
* @return 결과문자열, 비교하여 같으면 -1
* @since 2.4
*/
public static int indexOfDifference(String[] strs) {
return org.apache.commons.lang.StringUtils.indexOfDifference(strs);
}
/**
* 대소문자를 구분없이 기준 문자열에서 찾고자 하는 문자열이 포함되어 있는 경우 그 첫번째 문자열의 인덱스를 반환한다.<br><br>
*
* StringUtils.indexOfIgnoreCase("Anyframe Java Test", "java") = 9
*
* @param str 기준 문자열
* @param search 검색할 문자열
* @return 첫번째 문자열의 인덱스
* @see String#indexOf(String)
*/
public static int indexOfIgnoreCase(String str, String search) {
if (str == null || search == null) {
return -1;
}
return str.toLowerCase().indexOf(search.toLowerCase());
}
/**
* 입력된 문자열이 유니코드 문자로만 구성되었는지 체크<br><br>
*
* StringUtils.isAlpha("abcfds") = true
*
* @param str 문자열
* @return 문자열이 유니코드 문자로만 구성되어있을 경우 true
*/
public static boolean isAlpha(String str) {
if (str == null) {
return false;
}
int sz = str.length();
if (sz == 0) {
return false;
}
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 문자열이 모두 문자 또는 숫자인지 확인한다.<br />
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = true
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param str 문자열
* @return 문자 또는 숫자 또는 문자열이 null이 아닐경우 <code>true</code>
*/
public static boolean isAlphanumeric(String str) {
return org.apache.commons.lang.StringUtils.isAlphanumeric(str);
}
/**
* 문자열이 모두 문자 또는 숫자 이거나 <br />
* 공백문자인지 확인한다.<br />
*
* <pre>
* StringUtils.isAlphanumericSpace(null) = false
* StringUtils.isAlphanumericSpace("") = true
* StringUtils.isAlphanumericSpace(" ") = true
* StringUtils.isAlphanumericSpace("abc") = true
* StringUtils.isAlphanumericSpace("ab c") = true
* StringUtils.isAlphanumericSpace("ab2c") = true
* StringUtils.isAlphanumericSpace("ab-c") = false
* </pre>
*
* @param str 문자열
* @return 문자열의 문자가 문자 또는 숫자이거나 공백문자 또는 문자열이 null이 아닐경우 <code>true</code>
*/
public static boolean isAlphanumericSpace(String str) {
return org.apache.commons.lang.StringUtils.isAlphanumericSpace(str);
}
/**
* 문자열이 모두 문자 이거나 공백문자인것을 확인한다.<br />
*
* <code>null</code> will return <code>false</code>
* An empty String (length()=0) will return <code>true</code>.<br />
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param str 문자열
* @return 문자열의 문자가 모두 문자이거나 공백문자 또는 문자열이 null이 아닐경우 <code>true</code>
*/
public static boolean isAlphaSpace(String str) {
return org.apache.commons.lang.StringUtils.isAlphaSpace(str);
}
/**
* printable한 문자열인가를 확인한다.<br />
* 반환치가 「return ch >= 32 && ch < 127」경우 또는 공백문자는 true<br />
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param str 문자열
* @return 문자열의 모든 문자가 printable한 문자일경우 <code>true</code>
*/
public static boolean isAsciiPrintable(String str) {
return org.apache.commons.lang.StringUtils.isAsciiPrintable(str);
}
/**
* 문자열이 빈 공백 또는 NULL인지 확인한다.<br />
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str 문자열
* @return null 일경우 true
* 공백문자 일경우 true
* 이외의 경우 false
*/
public static boolean isBlank(String str) {
return org.apache.commons.lang.StringUtils.isBlank(str);
}
//중복되거나 불필요한 메소드 여기까지...확인. ->
/**
* 주어진 String이 '숫자'로만 구성되어 있는지를 판별한다.<br>
* 숫자인지의 판별은 Java의 기본 판별 기준을 준수한다.<br>
* 주어진 String이 null일 경우, false를 return한다.<br><br>
*
* StringUtils.isDigit("1234") = true<br>
* StringUtils.isDigit("1234A") = false
*
* @param str
* the String to check, may be null
* @return true if String contains only digits, false if not or null string
* input
*/
public static boolean isDigit(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isDigit(chars[i])) {
return false;
}
}
return true;
}
/**
* 주어진 문자열이 null 또는 공백일 경우 참 반환<br><br>
*
* StringUtils.isEmpty("") = true
*
* @param str 문자열
* @return null 또는 공백일 경우 true
*/
public static boolean isEmpty(String[] strArray) {
return (strArray == null || strArray.length == 0);
}
/**
* 주어진 문자열이 null 또는 공백일 경우 참 반환<br><br>
*
* StringUtils.isEmpty("") = true
*
* @param str 문자열
* @return null 또는 공백일 경우 true
*/
public static boolean isEmpty(String str) {
return (str == null || str.length() == 0);
}
// Mid
//-----------------------------------------------------------------------
/**
* trim한 문자열이 null 또는 공백일 경우 참 반환<br><br>
*
* StringUtils.isEmptyTrimmed(" ") = true
*
* @param str 문자열
* @return trim한 문자열이 null 또는 공백일 경우 true
*/
public static boolean isEmptyTrimmed(String str) {
return (str == null || str.trim().length() == 0);
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String이 특정한 포맷으로 구성되었는지를 검사한다.
*
* @param str
* the String to check, may be null
* @param pattern
* the pattern to check, may be null
* @return true if String contains the given pattern, false if not or null
* string input
*/
public static boolean isFormattedString(String str, String pattern) {
if (str == null || pattern == null) {
return false;
} else {
return str.matches(pattern);
}
}
/**
* 주어진 character가 한글인지의 여부를 판별한다.<br><br>
*
* StringUtils.isHangul('가') = true<br>
* StringUtils.isHangul('T') = false
*
* @param str
* the String to check, may be null
* @return true if the String contains only Korean Language, false if not
*/
public static boolean isHangul(char str) {
String unicodeBlock = Character.UnicodeBlock.of(str).toString();
return unicodeBlock.equals("HANGUL_JAMO")
|| unicodeBlock.equals("HANGUL_SYLLABLES")
|| unicodeBlock.equals("HANGUL_COMPATIBILITY_JAMO");
}
/**
* 주어진 String에 대해서, 한글로만 되어 있는지 혹은 한글이 포함되어 있는지를 판별한다.<br>
* full을 true로 설정할 경우, 한글로만 되어 있는지를 판별한다.<br>
* '한글로만 되어 있는지'는 영어나 기타 언어가 아님을 의미하는 것이 아니고,<br>
* 숫자나 기타 기호 문자 등도 없음을 의미한다.<br>
* full을 false로 설정할 경우, 한글이 하나라도 포함되어 있는지를 판별한다.<br><br>
*
* StringUtils.isHangul("가나다", true) = true<br>
* StringUtils.isHangul("가나다abc", true) = false<br>
* StringUtils.isHangul("가abc", false) = true<br>
* StringUtils.isHangul("abcd", false) = false
*
* @param str
* the String to check, may be null
* @param checkForAll
* flag for check only Korean characters(true) or any Korean
* characters(false)
* @return true if the String contains only Korean Language(when checkForAll
* is true) or any Korean characters(when checkForAll is false),
* false if not
*/
public static boolean isHangul(String str, boolean checkForAll) {
char[] chars = str.toCharArray();
if (!checkForAll) {
for (int i = 0; i < chars.length; i++) {
if (isHangul(chars[i])) {
return true;
}
}
return false;
} else {
for (int i = 0; i < chars.length; i++) {
if (!isHangul(chars[i])) {
return false;
}
}
return true;
}
}
/**
* 주어진 String이 '문자'로만 구성되어 있는지를 판별한다.<br>
* 문자인지의 판별은 Java의 기본 판별 기준을 준수한다.<br>
* 주어진 String이 null일 경우, false를 return한다.<br><br>
*
* StringUtils.isLetter("test") = true<br>
* StringUtils.isLetter("test가나")= true<br>
* StringUtils.isLetter("test#$%") = false<br>
* StringUtils.isLetter("test123") = false
*
* @param str
* the String to check, may be null
* @return true if String contains only letters, false if not or null string
* input
*/
public static boolean isLetter(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isLetter(chars[i])) {
return false;
}
}
return true;
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String이 '문자'나 '숫자'로만 구성되어 있는지를 판별한다.<br>
* 문자나 숫자인지의 판별은 Java의 기본 판별 기준을 준수한다.<br>
* 주어진 String이 null일 경우, false를 return한다.<br><br>
*
* StringUtils.isLetterOrDigit("12가나") = true<br>
* StringUtils.isLetterOrDigit("12가나@#%") = false
*
* @param str
* the String to check, may be null
* @return true if String contains only letters or digits, false if not or
* null string input
*/
public static boolean isLetterOrDigit(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (!Character.isLetterOrDigit(chars[i])) {
return false;
}
}
return true;
}
/**
* 문자열이 빈 공백 또는 NULL이 아닌지 확인한다.<br />
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param str 문자열
* @return null이 아닐경우 true
* 공백문자가 아닐경우 true
* 이외의 경우 false
*/
public static boolean isNotBlank(String str) {
return org.apache.commons.lang.StringUtils.isNotBlank(str);
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 문자열이 null 또는 공백이 아닐 경우 참 반환<br><br>
*
* StringUtils.isNotEmpty("abc") = true
*
* @param str 문자열
* @return null 또는 공백이 아닐 경우 true
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* 입력인자로 전달된 문자열이 숫자가 아닌 문자가 포함되어있는지 여부를 리턴한다.<br><br>
*
* StringUtils.isNotNumeric("12345") = false<br>
* StringUtils.isNumeric("12345ABC") = true
*
* @param str
* the String to check, may be null
* @return true if String contains any letters, false if not or null string
* input
*/
public static boolean isNotNumeric(String str) {
if (str == null) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(str.charAt(i))) {
return true;
}
}
return false;
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열이 모두 숫자인가를 확인한다.<br />
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = true
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* </pre>
*
* @param str 문자열
* @return 문자열의 모든 문자가 숫자 또는 문자열이 null이 아닐경우<code>true</code>
*/
public static boolean isNumeric(String str) {
return org.apache.commons.lang.StringUtils.isNumeric(str);
}
/**
* 문자열이 숫자 또는 공백문자인가를 확인한다.<br />
*
* <pre>
* StringUtils.isNumericSpace(null) = false
* StringUtils.isNumericSpace("") = true
* StringUtils.isNumericSpace(" ") = true
* StringUtils.isNumericSpace("123") = true
* StringUtils.isNumericSpace("12 3") = true
* StringUtils.isNumericSpace("ab2c") = false
* StringUtils.isNumericSpace("12-3") = false
* StringUtils.isNumericSpace("12.3") = false
* </pre>
*
* @param str 문자열
* @return 문자열이 숫자 또는 공백문자 이거나 문자열이 null이 아닐경우<code>true</code>
*/
public static boolean isNumericSpace(String str) {
return org.apache.commons.lang.StringUtils.isNumericSpace(str);
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String이 Space만을 가지고 있는지를 검사한다.<br>
* Space의 판별 기준은, String.trim()에서 제거되는 대상을 기준으로 한다.<br>
* 주어진 String이 null이면, false를 return한다.<br><br>
*
* StringUtils.isSpaceOnly(" ") = true<br>
* StringUtils.isSpaceOnly("") = true<br>
* StringUtils.isSpaceOnly("test") = false
*
* @param str
* the String to check, may be null
* @return true if String contains only whitespace, false if not or null
* string input
*/
public static boolean isSpaceOnly(String str) {
if (str == null) {
return false;
} else {
return str.trim().length() <= 0;
}
}
/**
* 문자열이 공백 또는 공백문자인가를 확인한다.<br />
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param str 문자열
* @return 문자열이 공백 또는 공백문자 이거나 문자열이 null이 아닐경우<code>true</code>
*/
public static boolean isWhitespace(String str) {
return org.apache.commons.lang.StringUtils.isWhitespace(str);
}
// Mid
//-----------------------------------------------------------------------
/**
* collection에서 문자열을 읽어와 구분자로 연결시킨다.<br />
*
* @param collection Collection
* @param separator 구분자
* @return 결과문자열, collection가 null일경우 <code>null</code>
*/
@SuppressWarnings("rawtypes")
public static String join(Collection collection, char separator) {
return org.apache.commons.lang.StringUtils.join(collection, separator);
}
// Mid
//-----------------------------------------------------------------------
/**
* collection에서 문자열을 읽어와 구분자로 연결시킨다.<br />
*
* @param collection Collection
* @param separator 구분자
* @return 결과문자열, collection가 null일경우 <code>null</code>
*/
@SuppressWarnings("rawtypes")
public static String join(Collection collection, String separator) {
return org.apache.commons.lang.StringUtils.join(collection, separator);
}
/**
* iterator에서 문자열을 읽어와 구분자로 연결시킨다.<br />
*
* @param iterator Iterator
* @param separator 구분자
* @return 결과문자열, iterator가 null일경우 <code>null</code>
*/
@SuppressWarnings("rawtypes")
public static String join(Iterator iterator, char separator) {
return org.apache.commons.lang.StringUtils.join(iterator, separator);
}
// Mid
//-----------------------------------------------------------------------
/**
* iterator에서 문자열을 읽어와 구분자로 연결시킨다.<br />
*
* @param iterator Iterator
* @param separator 구분자
* @return 결과문자열, iterator가 null일경우 <code>null</code>
*/
@SuppressWarnings("rawtypes")
public static String join(Iterator iterator, String separator) {
return org.apache.commons.lang.StringUtils.join(iterator, separator);
}
/**
* 배열에서 문자열을 읽어와 모두 연결시킨다.<br />
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param array 배열
* @return 결과문자열, 배열이 null일경우 <code>null</code>
*/
public static String join(Object[] array) {
return org.apache.commons.lang.StringUtils.join(array);
}
/**
* 배열에서 문자열을 읽어와 모두 연결시킨다.<br />
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array 배열
* @param separator 구분자
* @return 결과문자열, 배열이 null일경우 <code>null</code>
*/
public static String join(Object[] array, char separator) {
return org.apache.commons.lang.StringUtils.join(array, separator);
}
/**
* 배열에서 문자열을 읽어와 배열의 시작인덱스부터 끝인덱스전까지 <br />
* 구분자를 사이에두고 연결시킨다.<br />
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array 배열
* @param separator 구분자
* @param startIndex 시작인덱스
* @param endIndex 끝인덱스
* @return 결과문자열, 배열이 null일경우 <code>null</code>
*/
public static String join(Object[] array, char separator, int startIndex, int endIndex) {
return org.apache.commons.lang.StringUtils.join(array, separator, startIndex, endIndex);
}
/**
* 배열에서 문자열을 읽어와 모두 구분자를 사이에두고 연결시킨다.<br />
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array 배열
* @param separator 구분자
* @return 결과문자열, 배열이 null일경우 <code>null</code>
*/
public static String join(Object[] array, String separator) {
return org.apache.commons.lang.StringUtils.join(array, separator);
}
/**
* 배열에서 문자열을 읽어와 배열의 시작인덱스부터 끝인덱스전까지 <br />
* 구분자를 사이에두고 연결시킨다.<br />
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array 배열
* @param separator 구분자
* @param startIndex 시작인덱스
* @param endIndex 끝인덱스
* @return 결과문자열, 배열이 null일경우 <code>null</code>
*/
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
return org.apache.commons.lang.StringUtils.join(array, separator, startIndex, endIndex);
}
/**
* 문자열 내에서 마지막 검색문자의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str 문자열
* @param searchChar 검색문자
* @return 검색 문자 마지막 인덱스 없는 경우-1 일치 또는 null 문자열 입력
*/
public static int lastIndexOf(String str, char searchChar) {
return org.apache.commons.lang.StringUtils.lastIndexOf(str, searchChar);
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열 내에서 시작인덱스로부터 마지막 검색문자의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param str 문자열
* @param searchChar 검색문자
* @param startPos 시작인덱스
* @return 검색 문자 마지막 인덱스 없는 경우-1 일치 또는 null 문자열 입력
*/
public static int lastIndexOf(String str, char searchChar, int startPos) {
return org.apache.commons.lang.StringUtils.lastIndexOf(str, searchChar, startPos);
}
/**
* 문자열 내에서 마지막 검색문자열의 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 5
* StringUtils.lastIndexOf("aabaabaa", "ab") = 4
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @return 검색 문자열의 마지막 인덱스 없는 경우-1 일치 또는 null 문자열 입력
*/
public static int lastIndexOf(String str, String searchStr) {
return org.apache.commons.lang.StringUtils.lastIndexOf(str, searchStr);
}
/**
* 문자열 내에서 시작인덱스로부터 앞으로 검색문자열인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @param startPos 시작인덱스
* @return 검색 문자열의 마지막 인덱스 없는 경우-1 일치 또는 null 문자열 입력
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
return org.apache.commons.lang.StringUtils.lastIndexOf(str, searchStr, startPos);
}
/**
* 문자열 내에서 검색문자배열중 포함하고 있는지 검색후<br />
* 최후에 검색된 인덱스를 반환한다.<br />
*
* 문자열이 <code>null</code> 일경우 <code>-1</code>을 반환.<br />
* 검색배열이 <code>null</code> 또는 공백배열일경우 <code>-1</code>을 반환.<br />
* 배열내 검색문자열이 <code>null</code> 또는 공백일경우 <code>-1</code>을 반환. <br />
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str 문자열
* @param searchStrs 검색문자열
* @return 검색된 최후의 인덱스, 검색되지않은 경우 -1반환.
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
return org.apache.commons.lang.StringUtils.lastIndexOfAny(str, searchStrs);
}
/**
* 주어진 String 객체에 대해서 주어진 길이만큼 왼쪽 부분을 떼어 반환한다.<br>
* 주어진 길이보다 주어진 String의 길이가 작을 경우에는 주어진 String을 그대로 반환한다.<br>
* "..."을 붙이지 않는 점을 제외하고는 splitHead()와 동일하다.<br><br>
*
* StringUtils.left("1234567", 3) = "123"
*
* @param str
* the String to get the leftmost characters from, may be null
* @param len
* the length of the required String
* @return the leftmost characters, null if null String input
*/
public static String left(String str, int len) {
if (str == null) {
return null;
} else if (len <= 0 || str.length() <= len) {
return str;
} else {
return str.substring(0, len);
}
}
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 왼쪽부터 공백으로 채워넣는다.<br><br>
*
* StringUtils.leftPad("Anyframe", 12) = " Anyframe"
*
* @param str 문자열
* @param size 공백이 채워진 문자열의 전체 길이
* @return 부족한 길이만큼 왼쪽부터 공백이 채워진 문자열
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 왼쪽부터 지정된 character로 채워넣는다.<br><br>
*
* StringUtils.leftPad("Anyframe", 12, 'a') = "aaaaAnyframe"
*
* @param str 문자열
* @param size 캐릭터가 채워진 문자열의 전체 길이
* @param padChar 채워넣을 캐릭터
* @return 부족한 길이만큼 왼쪽부터 캐릭터가 채워진 문자열
*/
public static String leftPad(String str, int size, char padChar) {
return padChar(str, size, padChar, true);
}
// Mid
//-----------------------------------------------------------------------
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 왼쪽부터 지정된 문자열로 채워넣는다.<br><br>
*
* StringUtils.leftPad("Anyframe", 12, "Java") = "JavaAnyframe"
*
* @param str 문자열
* @param size 문자열이 채워진 문자열의 전체 길이
* @param padStr 채워넣을 문자열
* @return 부족한 길이만큼 왼쪽부터 문자열이 채워진 문자열
*/
public static String leftPad(String str, int size, String padStr) {
return padString(str, size, padStr, true);
}
/**
* 문자열의 왼쪽의 공백 문자열 제거<br><br>
*
* StringUtils.leftTrim(" Anyframe Java Test") = "Anyframe Java Test"
*
* @param str 문자열
* @return 왼쪽 공백을 제거한 문자열
* @see org.springframework.util.StringUtils#trimLeadingWhitespace(String)
*/
public static String leftTrim(String str) {
return org.springframework.util.StringUtils.trimLeadingWhitespace(str);
}
/**
* 문자열을 소문자로 변환한다.<br />
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String lowerCase(String str) {
return org.apache.commons.lang.StringUtils.lowerCase(str);
}
/**
* 문자열의 pos 인덱스부터 len 길이만큼의 문자열을 구한다.<br />
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str 문자열
* @param pos 시작인덱스
* @param len 길이 the length of the required String
* @return 결과 문자열, 문자열이 null의 경우 <code>null</code>
*/
public static String mid(String str, int pos, int len) {
return org.apache.commons.lang.StringUtils.mid(str, pos, len);
}
/**
* CRLF(newLine)가 포함된 문자열을 입력인자로 받아 CRLF(개행문자)를 SPACE로 변환하여 리턴한다.<br><br>
*
* StringUtils.newLineToSpace("\r\ntest") = " test"
*
* @param str
* the String to convert
* @return the converted string
*/
public static String newLineToSpace(String str) {
String output;
output = str.replace("\r\n", " ");
return output;
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String 객체를 검사하여 null일 경우 "" 을 반환하고, 아니면 원본을 반환한다.<br><br>
*
* StringUtils.nullToEmpty("test") = "test"<br>
* StringUtils.nullToEmpty(null) = ""
*
* @param str
* the String to check
* @return empty string if the given String is null, given string if not
*/
public static String nullToEmpty(String str) {
if (str == null || str.length() <= 0) {
return DEFAULT_EMPTY_STRING;
} else {
return str;
}
}
/**
* 주어진 Object가 null이 아닐 경우 그 Object를 반환하고, null일 경우 default Object를 반환한다.<br><br>
*
* StringUtils.nvl(null, "NULL TEST") = "NULL TEST"<br>
* StringUtils.nvl("test", "NULL TEST") = "test"
*
* @param inputObject
* the Object to check
* @param defaultObject
* the default Object
* @return Returns the default Object if the given Object is null, returns
* the given Object if not
*/
public static Object nvl(Object inputObject, Object defaultObject) {
return inputObject != null ? inputObject : defaultObject;
}
/**
* 주어진 String이 null이 아닐 경우 그 String을 반환하고, null일 경우 default String을 반환한다.<br><br>
*
* StringUtils.nvl(null, "NULL TEST") = "NULL TEST"<br>
* StringUtils.nvl("test", "NULL TEST")) = "test"
*
* @param inputString
* the String to check
* @param defaultString
* the default String
* @return Returns the default String if the given String is null, returns
* the given String if not
*/
public static String nvl(String inputString, String defaultString) {
return (String) nvl((Object) inputString, (Object) defaultString);
}
public static String nvl(Object inputObject, String defaultString) {
return (String) nvl((Object) inputObject, (Object) defaultString);
}
public static String nvl(Object inputObject) {
return (String) nvl((Object) inputObject, (Object) "");
}
/**
* 문자열 내에서 검색문자열의 n번째 해당하는 인덱스를 반환한다.<br />
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* @param str 문자열
* @param searchStr 검색문자열
* @param ordinal n번째
* @return 검색 문자열의 n 번째 인덱스-1 (INDEX_NOT_FOUND) 없으면 일치 또는 null 문자열 입력
*/
public static int ordinalIndexOf(String str, String searchStr, int ordinal) {
return org.apache.commons.lang.StringUtils.ordinalIndexOf(str, searchStr, ordinal);
}
/**
* 문자열의 시작점부터 종료점까지 변환문자로 변환한다.<br />
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str 문자열
* @param overlay 변환문자
* @param start 시작점
* @param end 종료점
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String overlay(String str, String overlay, int start, int end) {
return org.apache.commons.lang.StringUtils.overlay(str, overlay, start, end);
}
private static String padChar(String str, int size, char padChar, boolean isLeft) {
if (str == null) {
return null;
}
int originalStrLength = str.length();
if (size < originalStrLength) {
return str;
}
int difference = size - originalStrLength;
StringBuilder strBuf = new StringBuilder();
if (!isLeft) {
strBuf.append(str);
}
for (int i = 0; i < difference; i++) {
strBuf.append(padChar);
}
if (isLeft) {
strBuf.append(str);
}
return strBuf.toString();
}
// Mid
//-----------------------------------------------------------------------
/**
* 특정한 문자(char)와 일정한 길이 값을 입력으로 받아 해당 크기만큼 문자가 반복되는 문자열을 생성한다.<br>
* 주어진 길이 값이 0이면 ""을 주어진 길이 값이 0보다 작으면 null을 리턴한다.<br>
* length는 String.getBytes().length 기준이 아닌 String.length() 기준임을 유의한다.<br><br>
*
* StringUtils.padding(5, 'e') = "eeeee"
*
* @param size
* the length to pad to
* @param padChar
* the character to pad with
* @return padded String
*/
public static String padding(int size, char padChar) {
if (size < 0) {
return null;
}
StringBuffer buffer = new StringBuffer(size);
for (int i = 0; i < size; i++) {
buffer.insert(i, padChar);
}
return buffer.toString();
}
// Mid
//-----------------------------------------------------------------------
private static String padString(String str, int size, String padStr, boolean isLeft) {
if (str == null) {
return null;
}
int originalStrLength = str.length();
if (size < originalStrLength) {
return str;
}
int difference = size - originalStrLength;
String tempPad = "";
if (difference > 0) {
if (padStr == null || "".equals(padStr)) {
padStr = " ";
}
do {
for (int j = 0; j < padStr.length(); j++) {
tempPad += padStr.charAt(j);
if (str.length() + tempPad.length() >= size) {
break;
}
}
} while (difference > tempPad.length());
if (isLeft) {
str = tempPad + str;
} else {
str = str + tempPad;
}
}
return str;
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열 내에서 삭제문자가 포함되어있는 부분을 삭제후 반환한다.<br />
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str 문자열
* @param remove 삭제문자
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String remove(String str, char remove) {
return org.apache.commons.lang.StringUtils.remove(str, remove);
}
/**
* 문자열 내에서 삭제문자열이 포함되어있는 부분을 삭제후 반환한다.<br />
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str 문자열
* @param remove 삭제문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String remove(String str, String remove) {
return org.apache.commons.lang.StringUtils.remove(str, remove);
}
/**
* 입력된 문자열에 대해서 제거할 문자열을 모두 제거<br><br>
*
* StringUtils.removeAll("Anyframe Java Test", "Java") = "Anyfrme Test"
*
* @param str 문자열
* @param charsToDelete 제거할 문자열
* @return 문자열을 제거한 문자열
* @see org.springframework.util.StringUtils#deleteAny(String, String)
*/
public static String removeAll(String str, String charsToDelete) {
return org.springframework.util.StringUtils.deleteAny(str,
charsToDelete);
}
/**
* 한 String 객체 안에서 주어진 문자(char)를 제거한다.<br><br>
*
* StringUtils.removeChar("ABBBBBC", 'B') = "AC"
*
* @param str
* the source String to search
* @param remove
* the char to search for and remove
* @return the substring with the char removed if found
*/
public static String removeChar(String str, char remove) {
return replacePattern(str, String.valueOf(remove), "");
}
// Mid
//-----------------------------------------------------------------------
/**
* 한 String 객체 안에서 특정 문자들을 제거한다.<br>
* 제거할 대상 문자는 다음과 같다. {'/', '-', ':', ',', '.', '%' }<br><br>
*
* StringUtils.removeCharAll("test/-") = "test"
*
* @param str
* the source String to search
* @return the substring with specified chars removed if found
*/
public static String removeCharAll(String str) {
char[] targetCharacters = {'/', '-', ':', ',', '.', '%'};
return removeCharAll(str, targetCharacters);
}
/**
* 한 String 객체 안에서 주어진 문자들을 제거한다.<br><br>
*
* StringUtils.removeCharAll("AbbzzB", new char[]{'b','z'}) = "AB"
*
* @param str
* the source String to search
* @param remove
* chars to search for (case insensitive) and remove
* @return the substring with given chars removed if found
*/
public static String removeCharAll(String str, char[] remove) {
String value = str;
for (int i = 0; i < remove.length; i++) {
value = removeChar(value, remove[i]);
}
return value;
}
/**
* 문자열의 뒤에서부터 삭제문자열과 같은 부분을 삭제후 나머지를 반환한다.<br />
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str 문자열
* @param remove 삭제문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String removeEnd(String str, String remove) {
return org.apache.commons.lang.StringUtils.removeEnd(str, remove);
}
/**
* 문자열의 뒤에서부터 삭제문자열과 영문대소문자 구분없이 같은 부분을 삭제후 나머지를 반환한다.<br />
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str 문자열
* @param remove 삭제문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String removeEndIgnoreCase(String str, String remove) {
return org.apache.commons.lang.StringUtils.removeEndIgnoreCase(str, remove);
}
/**
* unescaped된 문자열에 대해 HTML tag 형태로 바꿔준다.<br><br>
*
* StringUtils.removeEscapeChar("<html>Anyframe Java Test<html>") = "<html>Anyframe Java Test<html>"
*
* @param input unescaped된 문자열
* @return HTML tag 형태로 바뀐 문자열
* @see HtmlUtils#htmlUnescape(String)
*/
public static String removeEscapeChar(String input) {
return HtmlUtils.htmlUnescape(input);
}
/**
* 문자열에서 삭제문자열을 삭제한나머지 문자열을 반환한다.<br />
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str 문자열
* @param remove 삭제문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String removeStart(String str, String remove) {
return org.apache.commons.lang.StringUtils.removeStart(str, remove);
}
/**
* 문자열의 시작부터 삭제문자열과 영문대소문자 구분없이 같은 부분을 삭제후 나머지를 반환한다.<br />
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str 문자열
* @param remove 삭제문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String removeStartIgnoreCase(String str, String remove) {
return org.apache.commons.lang.StringUtils.removeStartIgnoreCase(str, remove);
}
/**
* 문자열의 모든 공백 문자열 제거<br><br>
*
* StringUtils.removeWhitespace("Anyframe Java Test") = "AnyframeJavaTest"
*
* @param str 문자열
* @return 공백을 제거한 문자열
* @see org.springframework.util.StringUtils#trimAllWhitespace(String)
*/
public static String removeWhitespace(String str) {
return org.springframework.util.StringUtils.trimAllWhitespace(str);
}
/**
* 문자열을 반복횟수만큼 반복하여 반환한다.<br />
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str 문자열
* @param repeat 반복횟수
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String repeat(String str, int repeat) {
return org.apache.commons.lang.StringUtils.repeat(str, repeat);
}
/**
* 입력된 문자열에 대해서 해당하는 character를 찾아 주어진 문자열로 변경<br><br>
*
* StringUtils.replace("Anyframe/Common", "/", "|") = "Anyframe|Common"
*
* @param str 문자열
* @param replacedStr 검색할 문자열
* @param replaceStr 변경할 문자열
* @return 검색된 문자열을 변경한 문자열
*/
public static String replace(String str, String replacedStr, String replaceStr) {
String newStr = "";
if (str.indexOf(replacedStr) != -1) {
String s1 = str.substring(0, str.indexOf(replacedStr));
String s2 = str.substring(str.indexOf(replacedStr) + replacedStr.length());
newStr = s1 + replaceStr + s2;
} else {
return str;
}
return newStr;
}
/**
* 문자열 내에서 검색문자열을 검색후 치환최대치 만큼 치환문자열로 치환하여 반환한다.<br />
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text 문자열
* @param searchString 검색문자열
* @param replacement 치환문자열
* @param max 치환최대치
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replace(String text, String searchString, String replacement, int max) {
return org.apache.commons.lang.StringUtils.replace(text, searchString, replacement, max);
}
/**
* 입력된 문자열이 주어진 문자열과 일치하는 모든 문자열을 바꿔야할 문자열로 변경<br><br>
*
* StringUtils.replaceAll("Anyframe Java Test Anyframe Java Test", "Anyframe", "Enterprise") = "Enterprise Java Test Enterprise Java Test"
*
* @param source 문자열
* @param regex 검색할 문자열
* @param replacement 변경할 문자열
* @return 검색된 모든 문자열을 변경한 문자열
* @see String#replaceAll(String, String)
*/
public static String replaceAll(String source, String regex, String replacement) {
if (source == null) {
return null;
}
return source.replaceAll(regex, replacement);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* 문자열에서 검색문자를 치환문자로 모두 변환한다.<br />
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str 문자열
* @param searchChar 검색문자
* @param replaceChar 치환문자
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replaceChars(String str, char searchChar, char replaceChar) {
return org.apache.commons.lang.StringUtils.replaceChars(str, searchChar, replaceChar);
}
/**
* 문자열에서 검색문자열를 치환문자열로 모두 변환한다.<br />
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str 문자열
* @param searchChars 검색문자열
* @param replaceChars 치환문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
return org.apache.commons.lang.StringUtils.replaceChars(str, searchChars, replaceChars);
}
/**
* 문자열을 검색리스트 및 치환리스트의 각각 같은 인덱스의 문자열로 치환하여 반환한다.<br />
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text 문자열
* @param searchList 검색리스트
* @param replacementList 치환리스트
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replaceEach(String text, String[] searchList, String[] replacementList) {
return org.apache.commons.lang.StringUtils.replaceEach(text, searchList, replacementList);
}
/**
* 문자열을 검색리스트 및 치환리스트의 각각 같은 인덱스의 문자열로 치환하는 작업을<br />
* 검색리스트의 길이만큼 반복하여 반환한다.<br />
*
* <pre>
* StringUtils.replaceEachRepeatedly(null, *, *) = null
* StringUtils.replaceEachRepeatedly("", *, *) = ""
* StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalArgumentException
* </pre>
*
* @param text 문자열
* @param searchList 검색리스트
* @param replacementList 치환리스트
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) {
return org.apache.commons.lang.StringUtils.replaceEachRepeatedly(text, searchList, replacementList);
}
/**
* 입력된 문자열이 주어진 문자열과 일치하는 첫번째 문자열을 바꿔야할 문자열로 변경<br><br>
*
* StringUtils.replaceFirst("Anyframe Java Test Anyframe Java Test", "Anyframe", "Enterprise") = "Enterprise Java Test Anyframe Java Test"
*
* @param source 문자열
* @param regex 검색할 문자열
* @param replacement 변경할 문자열
* @return 검색된 문자열 중 첫번째 문자열을 변경한 문자열
* @see String#replaceFirst(String, String)
*/
public static String replaceFirst(String source, String regex, String replacement) {
if (source == null) {
return null;
}
return source.replaceFirst(regex, replacement);
}
// Mid
//-----------------------------------------------------------------------
/**
* HTML tag가 들어있는 문자열에 대해 unescape해준다.<br><br>
*
* StringUtils.replaceHtmlEscape("<html>Anyframe Java Test<html>") = "<html>Anyframe Java Test<html>"
*
* @param input HTML tag가 들어있는 문자열
* @return HTML tag를 unescape한 문자열
* @see HtmlUtils#htmlEscape(String)
*/
public static String replaceHtmlEscape(String input) {
return HtmlUtils.htmlEscape(input);
}
/**
* 입력된 문자열이 주어진 문자열과 일치하는 마지막 문자열을 바꿔야할 문자열로 변경<br><br>
*
* StringUtils.replaceLast("Anyframe Java Test Anyframe Java Test", "Anyframe", "Enterprise") = "Anyframe Java Test Enterprise Java Test"
*
* @param source 문자열
* @param regex 검색할 문자열
* @param replacement 변경할 문자열
* @return 검색된 문자열 중 마지막 문자열을 변경한 문자열
*/
public static String replaceLast(String source, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
if (!matcher.find()) {
return source;
}
int lastMatchStart = 0;
do {
lastMatchStart = matcher.start();
} while (matcher.find());
matcher.find(lastMatchStart);
StringBuffer sb = new StringBuffer(source.length());
matcher.appendReplacement(sb, replacement);
matcher.appendTail(sb);
return sb.toString();
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열 내에서 검색문자열을 검색후 치환문자열로 치환하여 반환한다.<br />
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @param text 문자열
* @param searchString 검색문자열
* @param replacement 치환문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String replaceOnce(String text, String searchString, String replacement) {
return org.apache.commons.lang.StringUtils.replaceOnce(text, searchString, replacement);
}
/**
* 한 String 객체 안에서 특정 패턴(old)을 다른 패턴(new)으로 변환한다.<br>
* 등장 패턴의 위치는 좌측에서부터 계산하고 겹치지 않는 형태로 계산한다.<br>
* 따라서, 변환된 후에도 old 패턴은 남아 있을 수 있다.<br><br>
*
* StringUtils.replacePattern("abaa", "aba", "bab") = "baba"
*
* @param text
* text to search and replace in, may be null
* @param searchString
* the String to search for, may be null
* @param replacement
* the String to replace it with, may be null
* @return the text with any replacements processed, null if null String
* input
*/
public static String replacePattern(String text, String searchString, String replacement) {
if (text == null) {
return null;
}
if (searchString == null || replacement == null) {
return text;
}
StringBuffer sbuf = new StringBuffer();
int pos = 0;
int index = text.indexOf(searchString);
int patLen = searchString.length();
for (; index >= 0; index = text.indexOf(searchString, pos)) {
sbuf.append(text.substring(pos, index));
sbuf.append(replacement);
pos = index + patLen;
}
sbuf.append(text.substring(pos));
return sbuf.toString();
}
// Mid
//-----------------------------------------------------------------------
/**
* 입력된 문자열의 순서를 반대로 바꿈<br><br>
*
* StringUtils.reverse("Anyframe Java Test") = "tseT avaJ emarfynA"
*
* @param str 문자열
* @return 순서가 반대로 바뀐 문자열
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* 구분자를 구분으로 문자열을 나눈 후 나눠진 단어들을 역순으로 바꾼다.<br />
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str 문자열
* @param separatorChar 구분자
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String reverseDelimited(String str, char separatorChar) {
return org.apache.commons.lang.StringUtils.reverseDelimited(str, separatorChar);
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String 객체에 대해서 주어진 길이만큼 오른쪽 부분을 떼어 반환한다.<br>
* 주어진 길이보다 주어진 String의 길이가 작을 경우에는 주어진 String을 그대로 반환한다.<br>
* "..."을 붙이지 않는 점을 제외하고는 splitTail()와 동일하다.<br><br>
*
* StringUtils.right("1234567", 3) = "567"
*
* @param str
* the String to get the rightmost characters from, may be null
* @param len
* the length of the required String
* @return the rightmost characters, null if null String input
*/
public static String right(String str, int len) {
if (str == null) {
return null;
} else if (len <= 0 || str.length() <= len) {
return str;
} else {
return str.substring(str.length() - len);
}
}
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 오른쪽부터 공백으로 채워넣는다.<br><br>
*
* StringUtils.rightPad("Anyframe", 12) = "Anyframe "
*
* @param str 문자열
* @param size 공백이 채워진 문자열의 전체 길이
* @return 부족한 길이만큼 오른쪽부터 공백이 채워진 문자열
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 오른쪽부터 지정된 문자로 채워넣는다.<br><br>
*
* StringUtils.rightPad("Anyframe", 12, 'a') = "Anyframeaaaa"
*
* @param str 문자열
* @param size 캐릭터가 채워진 문자열의 전체 길이
* @param padChar 채워넣을 캐릭터
* @return 부족한 길이만큼 오른쪽부터 캐릭터가 채워진 문자열
*/
public static String rightPad(String str, int size, char padChar) {
return padChar(str, size, padChar, false);
}
/**
* 해당하는 문자열에 대해서 입력된 길이만큼 부족한 길이를 오른쪽부터 지정된 문자열로 채워넣는다.<br><br>
*
* StringUtils.rightPad("Anyframe", 12, "Java") = "AnyframeJava"
*
* @param str 문자열
* @param size 문자열이 채워진 문자열의 전체 길이
* @param padStr 채워넣을 문자열
* @return 부족한 길이만큼 오른쪽부터 문자열이 채워진 문자열
*/
public static String rightPad(String str, int size, String padStr) {
return padString(str, size, padStr, false);
}
/**
* 문자열의 오른쪽의 공백 문자열 제거<br><br>
*
* StringUtils.rightTrim("Anyframe Java Test ") = "Anyframe Java Test"
*
* @param str 문자열
* @return 오른쪽 공백을 제거한 문자열
* @see org.springframework.util.StringUtils#trimTrailingWhitespace(String)
*/
public static String rightTrim(String str) {
return org.springframework.util.StringUtils.trimTrailingWhitespace(str);
}
/**
* 공백문자를 구분자로 사용하여 문자열을 분리한다.<br />
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str 문자열
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] split(String str) {
return org.apache.commons.lang.StringUtils.split(str);
}
/**
* 주어진 String에 대해서 separator(char)를 이용하여 tokenize한 후 String[]로 뽑아낸다.<br>
* 연속된 separator 사이는 token이 되지 않는다.<br>
* 주어진 String이 null일 경우, null을 return한다.<br><br>
*
* StringUtils.split("aaVbbVcc", 'V') = {"aa", "bb", "cc"}
*
* @param str
* the String to parse
* @param separator
* the character used as the delimiter
* @return an array of parsed Strings
*/
public static String[] split(String str, char separator) {
StringBuffer tempStringBuffer = new StringBuffer();
tempStringBuffer.append(separator);
return tokenizeToStringArray(str, tempStringBuffer.toString(), false, false);
}
/**
* 문자열을 구분자로 사용하여 분리한다.<br />
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str 문자열
* @param separatorChars 구분자
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] split(String str, String separatorChars) {
return org.apache.commons.lang.StringUtils.split(str, separatorChars);
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열을 구분자를 사용하여 최대크기 만큼의 배열로 분리한다.<br />
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str 문자열
* @param separatorChars 구분자
* @param max 최대크기
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] split(String str, String separatorChars, int max) {
return org.apache.commons.lang.StringUtils.split(str, separatorChars, max);
}
/**
* 문자열을 <code>java.lang.Character.getType(char)</code>의 리턴타입으로 구분하여 <br />
* 배열로 분할한다.영문대소문자타입구분<br />
*
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str 문자열
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByCharacterType(String str) {
return org.apache.commons.lang.StringUtils.splitByCharacterType(str);
}
// Mid
//-----------------------------------------------------------------------
/**
* 문자열을 <code>java.lang.Character.getType(char)</code>의 리턴타입으로 구분하여 <br />
* 배열로 분할한다.영문대소문자타입구분하지않음<br />
*
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str 문자열
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByCharacterTypeCamelCase(String str) {
return org.apache.commons.lang.StringUtils.splitByCharacterTypeCamelCase(str);
}
/**
* 문자열을 구분자를 사용하여 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str 문자열
* @param separator 구분자
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByWholeSeparator(String str, String separator) {
return org.apache.commons.lang.StringUtils.splitByWholeSeparator(str, separator);
}
/**
* 문자열을 구분자를 사용하여 최대크기 만큼의 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str 문자열
* @param separator 구분자
* @param max 최대크기
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByWholeSeparator(String str, String separator, int max) {
return org.apache.commons.lang.StringUtils.splitByWholeSeparator(str, separator, max);
}
/**
* 문자열을 구분자를 사용하여 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str 문자열
* @param separator 구분자
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) {
return org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separator);
}
/**
* 문자열을 구분자를 사용하여 최대크기 만큼의 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str 문자열
* @param separator 구분자
* @param max 최대크기
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) {
return org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separator, max);
}
/**
* 해당문자열의 사이즈 만큼 앞에서부터 자른다.<br><br>
*
* StringUtils.splitHead("Anyframe Java Test", 3) = "Any"
*
* @param str 문자열
* @param size 문자열을 자를 길이
* @return 길이만큼 앞에서부터 자른 문자열
*/
public static String splitHead(String str, int size) {
if (str == null) {
return "";
}
if (str.length() > size) {
str = str.substring(0, size);
}
return str;
}
/**
* 주어진 String 객체에 대해서 주어진 길이만큼 앞부분을 떼어 반환한다.<br>
* 주어진 길이보다 주어진 String의 길이가 작을 경우에는 주어진 String을 그대로 반환한다.<br>
* 떼어낸 앞부분의 뒤에 "..."을 붙여서 반환한다.<br><br>
*
* StringUtils.splitHead("12345678", 3) = "123..."
*
* @param str
* the String to get the leftmost characters from, may be null
* @param len
* the length of the required String
* @return the leftmost characters with ellipsis, null if null String input
*/
public static String splitHeadWithEllipsis(String str, int len) {
if (str == null) {
return null;
} else if (len <= 0 || str.length() <= len) {
return str;
} else {
return str.substring(0, len) + "...";
}
}
/**
* 공백문자를 구분자로 사용하여 문자열을 분리한다.<br />
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str 문자열
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitPreserveAllTokens(String str) {
return org.apache.commons.lang.StringUtils.splitPreserveAllTokens(str);
}
/**
* 문자열을 구분자로 사용하여 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str 문자열
* @param separatorChar 구분자
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitPreserveAllTokens(String str, char separatorChar) {
return org.apache.commons.lang.StringUtils.splitPreserveAllTokens(str, separatorChar);
}
/**
* 문자열을 구분자로 사용하여 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str 문자열
* @param separatorChars 구분자
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars) {
return org.apache.commons.lang.StringUtils.splitPreserveAllTokens(str, separatorChars);
}
/**
* 문자열을 구분자를 사용하여 최대크기 만큼의 배열로 분리한다.<br />
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab cd ef", null, 0) = [ab, , , cd, ef]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str 문자열
* @param separatorChars 구분자
* @param max 최대크기
* @return 결과문자배열, 문자열이 null일경우 <code>null</code>
*/
public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
return org.apache.commons.lang.StringUtils.splitPreserveAllTokens(str, separatorChars, max);
}
/**
* 해당문자열의 사이즈 만큼 뒤에서부터 자른다.<br><br>
*
* StringUtils.splitTail("Anyframe Java Test", 3) = "est"
*
* @param str 문자열
* @param size 문자열을 자를 길이
* @return 길이만큼 뒤에서부터 자른 문자열
*/
public static String splitTail(String str, int size) {
if (str == null) {
return "";
}
if (str.length() > size) {
str = str.substring(str.length() - size);
}
return str;
}
// Mid
//-----------------------------------------------------------------------
/**
* 주어진 String 객체에 대해서 주어진 길이만큼 뒷부분을 떼어 반환한다.<br>
* 주어진 길이보다 주어진 String의 길이가 작을 경우에는 주어진 String을 그대로 반환한다.<br>
* 떼어낸 뒷부분의 앞에 "..."을 붙여서 반환한다.<br><br>
*
* StringUtils.splitTail("12345678", 3) = "...678"
*
* @param str
* the String to get the rightmost characters from, may be null
* @param len
* the length of the required String
* @return the rightmost characters with ellipsis, null if null String input
*/
public static String splitTailWithEllipsis(String str, int len) {
if (str == null) {
return null;
} else if (len <= 0 || str.length() <= len) {
return str;
} else {
return "..." + str.substring(str.length() - len);
}
}
/**
* 문자열이 검색문자로 시작되는지 확인한다.<br />
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @param str 문자열
* @param prefix 검색문자열
* @return 문자열이 검색문자로 시작되는경우와 문자열 양쪽모두 <code>null</code>인경우 <code>true</code>
*/
public static boolean startsWith(String str, String prefix) {
return org.apache.commons.lang.StringUtils.startsWith(str, prefix);
}
/**
* 문자열이 검색문자로 대소문자 구분없이 시작되는지 확인한다.<br />
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @param str 문자열
* @param prefix 검색문자
* @return 문자열이 검색문자로 대소문자 구분없이 시작되는경우와 문자열 양쪽모두
* <code>null</code>인경우 <code>true</code>
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
return org.apache.commons.lang.StringUtils.startsWithIgnoreCase(str, prefix);
}
/**
* 문자열을 숫자로 변환하여 리턴한다.<br><br>
*
* StringUtils.string2integer("14") = 14
*
* @param str
* string representation of a number
* @return integer integer type of string
*/
public static int string2integer(String str) {
int ret = Integer.parseInt(str.trim());
return ret;
}
/**
* 문자열을 BigDecimal로 변환하여 리턴한다.<br><br>
*
* StringUtils.stringToBigDecimal("14") = 14
*
* @param str
* the String value to convert
* @return the converted BigDecimal
*/
public static BigDecimal stringToBigDecimal(String str) {
if ("".equals(rightTrim(str))) {
return new BigDecimal(0);
} else {
return new BigDecimal(str);
}
}
/**
* 문자열의 내용 중 정해진 위치의 일부 문자열을 BigDecimal로 변환하여 리턴한다.<br><br>
*
* StringUtils.stringToBigDecimal("123456", 0, 2) = 12
*
* @param str 문자열
* @param pos 시작위치
* @param len 길이
* @return 변환된 BigDecimal 값
*/
public static BigDecimal stringToBigDecimal(String str, int pos, int len) {
if ("".equals(rightTrim(str))) {
return new BigDecimal(0);
} else if (str.length() < pos + len) {
return stringToBigDecimal(leftPad(str, pos + len, "0"));
} else {
return stringToBigDecimal(str.substring(pos, pos + len));
}
}
/**
* 문자열을 받아 해당하는 hex 코드로 만들어 반환한다. (유니코드)<br><br>
*
* StringUtils.stringToHex("123") = "003100320033"
*
* @param str 문자열
* @return 변환된 hex 문자열
*/
public static String stringToHex(String str) {
String inStr = str;
char[] inChar = inStr.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < inChar.length; i++) {
String hex = Integer.toHexString((int) inChar[i]);
if (hex.length() == 2) {
hex = "00" + hex;
}
sb.append(hex);
}
return sb.toString();
}
/**
* 문자열을 정수형으로 변환하여 리턴한다.<br><br>
*
* StringUtils.stringToNumn("123") = 123
*
* @param str 문자열
* @return 정수형으로 변환된 값
*/
public static int stringToNumn(String str) {
if ("".equals(rightTrim(str))) {
return 0;
} else {
return Integer.parseInt(str);
}
}
/**
* 문자열의 내용 중 정해진 위치의 일부 문자열을 정수형으로 변환하여 리턴한다.<br><br>
*
* StringUtils.stringToNumn("123456789", 5, 3) = 678
*
* @param str 문자열
* @param pos 시작위치
* @param len 길이
* @return 문자열의 일부가 정수형으로 변환된 값
*/
public static int stringToNumn(String str, int pos, int len) {
if ("".equals(rightTrim(str))) {
return 0;
} else if (str.length() < pos + len) {
return stringToNumn(leftPad(str, pos + len, "0"));
} else {
return stringToNumn(str.substring(pos, pos + len));
}
}
/**
* 문자열의 시작과 끝에서 스페이스을 제거한다.<br />
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str 문자열
* @return null 문자열 일경우 null
* "" 일경우 ""
*/
public static String strip(String str) {
return org.apache.commons.lang.StringUtils.strip(str);
}
/**
* 문자열 좌우에 stripChars에 존재하는 문자를 제거한다.<br />
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str 문자열
* @param stripChars 공백으로 취급 하는 문자열
* @return null 문자열 일경우 null
* "" 일경우 ""
*/
public static String strip(String str, String stripChars) {
return org.apache.commons.lang.StringUtils.strip(str, stripChars);
}
/**
* 배열에 있는 모든 문자열들을 앞뒤에 있는 스페이스를 제거한다.<br />
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs 문자열
* @return strip결과 문자열
*/
public static String[] stripAll(String[] strs) {
return org.apache.commons.lang.StringUtils.stripAll(strs);
}
// Mid
//-----------------------------------------------------------------------
/**
* 배열에 있는 모든 문자열을 대상으로 앞뒤에 존재하는 제거문자들을 제거한다.<br />
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs 문자열
* @param stripChars 제거문자들
* @return strip 결과 문자열
*/
public static String[] stripAll(String[] strs, String stripChars) {
return org.apache.commons.lang.StringUtils.stripAll(strs, stripChars);
}
/**
* 문자열을 뒤에서부터 제거문자들 하나식 제거한다.<br />
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str 문자열
* @param stripChars 공백으로 취급 하는 문자열
* @return null 문자열 일경우 null
* "" 일경우 ""
*/
public static String stripEnd(String str, String stripChars) {
return org.apache.commons.lang.StringUtils.stripEnd(str, stripChars);
}
/**
* 문자열을 앞에서부터 제거문자들 하나식 제거한다.<br />
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str 문자열
* @param stripChars 제거문자들
* @return null 문자열 일경우 null
* "" 일경우 ""
*/
public static String stripStart(String str, String stripChars) {
return org.apache.commons.lang.StringUtils.stripStart(str, stripChars);
}
/**
* 처리문자가 NULL일경우 공백을 반환, 아닐경우 좌우에 있는<br />
* 스페이스를 제거한다.<br />
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str 문자열
* @return null 문자열 또는 "" 일경우 ""
*/
public static String stripToEmpty(String str) {
return org.apache.commons.lang.StringUtils.stripToEmpty(str);
}
/**
* 문자열 좌우에 있는 스페이스를 제거한다.<br />
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str 문자열
* @return null 문자열 또는 "" 일경우 null
*/
public static String stripToNull(String str) {
return org.apache.commons.lang.StringUtils.stripToNull(str);
}
/**
* 문자열 내에서 문자열을 취득한다.<br />
*
* <p>
* 문자열의 마이너스도 사용가능한 <code>n</code>번째에서 부터 마지막까지의 문자열을 취득.
* </p>
*
* <p>
* 문자열이 <code>null</code>일경우 <code>null</code>을 반환.
* 문자열이 공백일경우 공백을 반환.
* </p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = "
* "
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str 문자열
* @param start 시작점
* @return 시작점으로부터의 문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substring(String str, int start) {
return org.apache.commons.lang.StringUtils.substring(str, start);
}
/**
* 문자열 내에서 문자열을 취득한다.<br />
*
* <p>
* 문자열의 마이너스도 사용가능한 <code>n</code>번째에서 부터 마지막까지의 문자열을 취득.
* </p>
*
* <p>
* 문자열이 <code>null</code>일경우 <code>null</code>을 반환.
* 문자열이 공백일경우 공백을 반환.
* </p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str 문자열
* @param start 시작점
* @param end 종료점
* @return 시작점으로부터 종료점까지의 문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substring(String str, int start, int end) {
return org.apache.commons.lang.StringUtils.substring(str, start, end);
}
/**
* 문자열의 처음 SEPARATOR부분부터 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str 문자열
* @param separator SEPARATOR
* @return 결과문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substringAfter(String str, String separator) {
return org.apache.commons.lang.StringUtils.substringAfter(str, separator);
}
/**
* 문자열의 마지막 separator부분부터 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str 문자열
* @param separator SEPARATOR
* @return 결과문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substringAfterLast(String str, String separator) {
return org.apache.commons.lang.StringUtils.substringAfterLast(str, separator);
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* 문자열의 처음 SEPARATOR부분까지 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str 문자열
* @param separator SEPARATOR
* @return 결과문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substringBefore(String str, String separator) {
return org.apache.commons.lang.StringUtils.substringBefore(str, separator);
}
/**
* 문자열의 마지막 separator부분까지 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str 문자열
* @param separator SEPARATOR
* @return 결과문자열, 문자열이 null일경우 <code>null</code>
*/
public static String substringBeforeLast(String str, String separator) {
return org.apache.commons.lang.StringUtils.substringBeforeLast(str, separator);
}
// Substring between
//-----------------------------------------------------------------------
/**
* 문자열에서 TAG사이에 있는 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str 문자열
* @param tag TAG
* @return 결과문자열, 문자열에 TAG가 존재하지않을 경우<code>null</code>
*/
public static String substringBetween(String str, String tag) {
return org.apache.commons.lang.StringUtils.substringBetween(str, tag);
}
/**
* 문자열에서 OPEN부터 CLOSE까지 사이에 있는 문자열을 구한다.<br />
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str 문자열
* @param open OPEN
* @param close CLOSE
* @return 결과문자열, 문자열에 TAG가 존재하지않을 경우<code>null</code>
*/
public static String substringBetween(String str, String open, String close) {
return org.apache.commons.lang.StringUtils.substringBetween(str, open, close);
}
/**
* 문자열로부터 OPEN과 CLOSE에 감싸진 부분문자열을 배열로 구한다.<br />
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str 문자열
* @param open OPEN
* @param close CLOSE
* @return 결과문자배열, 문자열과 OPEN 및 CLOSE중 null인 경우<code>null</code>
*/
public static String[] substringsBetween(String str, String open, String close) {
return org.apache.commons.lang.StringUtils.substringsBetween(str, open, close);
}
/**
* 대문자는 소문자로 변환하고 소문자는 대문자로 변환한다.<br />
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* @param str the String to swap case, may be null
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String swapCase(String str) {
return org.apache.commons.lang.StringUtils.swapCase(str);
}
/**
* 첫번째 문자를 대문자로 변경<br><br>
*
* StringUtils.swapFirstLetterCase("java") = "Java"
*
* @param str 문자열
* @return 첫번째 문자를 대문자로 변경한 문자열
*/
public static String swapFirstLetterCase(String str) {
StringBuilder sbuf = new StringBuilder(str);
sbuf.deleteCharAt(0);
if (Character.isLowerCase(str.substring(0, 1).toCharArray()[0])) {
sbuf.insert(0, str.substring(0, 1).toUpperCase());
} else {
sbuf.insert(0, str.substring(0, 1).toLowerCase());
}
return sbuf.toString();
}
/**
* 주어진 String에 대해서 delimiter를 이용하여 tokenize한 후 String[]로 뽑아낸다.<br>
* Java의 StringTokenizer를 이용하여 처리한다.<br>
* 옵션에 따라 공백(space)에 대한 처리(trim), 값이 ""인 token에 대한 포함 여부를 결정할 수 있다.<br>
* StringTokenizer를 이용하므로, 연속된 delimiter 사이는 token이 되지 않는다.<br>
* 주어진 String이 null일 경우 null을 return한다.<br>
* delimiter가 null일 경우 주어진 String을 하나의 element로 가지는 String[]를 return한다.<br><br>
*
* StringUtils.tokenizeToStringArray("aaa.bbb.ccc.ddd", ".", true, true) = {"aaa", "bbb", "ccc", "ddd"}
*
* @param str 문자열
* @param separator 구분자
* @param trimTokens 공백제거 여부
* @param ignoreEmptyTokens 빈 토큰 무시 여부
* @return an array of parsed Strings
*/
public static String[] tokenizeToStringArray(String str, String separator, boolean trimTokens, boolean ignoreEmptyTokens) {
if (str == null) {
return null;
}
if (separator == null) {
return new String[] {str};
}
StringTokenizer st = new StringTokenizer(str, separator);
List<String> tokens = new ArrayList<String>();
do {
if (!st.hasMoreTokens()) {
break;
}
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() != 0) {
tokens.add(token);
}
} while (true);
return tokens.toArray(new String[tokens.size()]);
}
/**
* 입력된 문자열로 부터 숫자만 추출하여 '-'가 포함된 전화번호 형태의 문자열로 포매팅하여 리턴한다.<br><br>
*
* StringUtils.toTelephoneNumberFormat("032-123-4567") = "032-123-4567"<br>
* StringUtils.toTelephoneNumberFormat("021234567") = "02-123-4567"<br>
* StringUtils.toTelephoneNumberFormat("0212345678") = "02-1234-5678"<br>
* StringUtils.toTelephoneNumberFormat("1234567") = "123-4567"
*
* @param str 문자열
* @return 전화번호 형태로 변환된 문자열
*/
public static String toTelephoneNumberFormat(String str) {
int endNumberDigit = 4;
int minNumberDigit = 7;
if (StringUtil.isEmpty(str)) {
return null;
}
String origin = str.trim();
String tempNumber;
int originLength = origin.length();
// extract numeric chars only
if (StringUtil.isNotNumeric(origin)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < originLength; i++) {
if (Character.isDigit(origin.charAt(i))) {
sb.append(origin.charAt(i));
}
}
tempNumber = sb.toString();
} else {
tempNumber = origin;
}
int numberLength = tempNumber.length();
if (numberLength < minNumberDigit) {
return tempNumber;
}
String firstNumber = "";
String secondNumber = "";
String thirdNumber = "";
if (tempNumber.charAt(0) == '0') { // local number or mobile number
if (tempNumber.charAt(1) == '2') { // Seoul
firstNumber = tempNumber.substring(0, 2);
secondNumber = tempNumber.substring(2, numberLength - endNumberDigit);
thirdNumber = tempNumber.substring(numberLength - endNumberDigit, numberLength); // split last 4 digits
} else { // local number or mobile number
firstNumber = tempNumber.substring(0, 3);
secondNumber = tempNumber.substring(3, numberLength - endNumberDigit);
thirdNumber = tempNumber.substring(numberLength - endNumberDigit, numberLength); // split last 4 digits
}
return firstNumber + "-" + secondNumber + "-" + thirdNumber;
} else { // telephone number without local number
firstNumber = tempNumber.substring(0, numberLength - endNumberDigit);
secondNumber = tempNumber.substring(numberLength - endNumberDigit, numberLength);
return firstNumber + "-" + secondNumber;
}
}
/**
* 주어진 6자리 숫자 String을 "111-111" 형태의 우편번호 포맷으로 변환한다.<br>
* 주어진 String이 6자리가 아닐 경우 ""를 return한다.<br>
* 주어진 String이 숫자만으로 구성되어 있지 않을 경우 ""을 return한다.<br><br>
*
* StringUtils.toZipCodePattern("111111") = "111-111"
*
* @param str 문자열
* @return 우편번호 형태로 변환된 문자열
*/
public static String toZipCodePattern(String str) {
if (str == null) {
return "";
}
if (str.length() != 6 || !isDigit(str)) {
return "";
} else {
StringBuffer buffer = new StringBuffer();
buffer.append(str.substring(0, 3));
buffer.append('-');
buffer.append(str.substring(3, 6));
return buffer.toString();
}
}
/**
* 문자열의 좌우에 있는 스페이스를 제거한다.<br />
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str 문자열
* @return null 문자열 일경우 null
* "" 일경우 ""
*/
public static String trim(String str) {
return org.apache.commons.lang.StringUtils.trim(str);
}
/**
* 입력된 문자열에서 주어진 문자열과 일치하는 부분을 trim한다.<br><br>
*
* StringUtils.trim("Anyframe*Java", "*") = "AnyframeJava"
*
* @param origString 문자열
* @param trimString trim할 문자열
* @return 주어진 문자열에서 trim할 문자열을 trim한 문자열
*/
public static String trim(String origString, String trimString) {
int startPosit = origString.indexOf(trimString);
if (startPosit != -1) {
int endPosit = trimString.length() + startPosit;
return origString.substring(0, startPosit) + origString.substring(endPosit);
}
return origString;
}
/**
* 처리문자가 NULL일경우 공백을 반환, 아닐경우 좌우에 있는<br />
* 스페이스를 제거한다.<br />
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str 문자열
* @return null 문자열 또는 ""일 경우 ""
*/
public static String trimToEmpty(String str) {
return org.apache.commons.lang.StringUtils.trimToEmpty(str);
}
/**
* 문자열의 좌우에 있는 스페이스를 제거한다.<br />
* 제거후 결과가 공백일경우 NULL를 반환<br />
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str 문자열
* @return null 문자열 또는 ""일 경우 null
*/
public static String trimToNull(String str) {
return org.apache.commons.lang.StringUtils.trimToNull(str);
}
/**
* 문자열의 첫문자를 소문자로 변환한다.<br />
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String uncapitalize(String str) {
return org.apache.commons.lang.StringUtils.uncapitalize(str);
}
/**
* 문자열을 대문자로 변환한다.<br />
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* @param str 문자열
* @return 결과문자열, 입력문자열이 null일경우 <code>null</code>
*/
public static String upperCase(String str) {
return org.apache.commons.lang.StringUtils.upperCase(str);
}
// 파라미터 -> Map
public static HashMap<String, Object> convertStringToQueryMap(String query) {
String[] params = query.split("&");
HashMap<String, Object> map = new HashMap<String, Object>();
for (String param : params) {
String param_array[] = param.split("=");
String name = "";
String value = "";
try{
name = param_array[0];
value = param_array[1];
map.put(name.trim(), value.trim());
} catch(Exception e){}
}
return map;
}
public static String createLicenseCode(){
String ramdom_code = getRandom("ABC123",16);
String st1=ramdom_code.substring(0,4);
String st2=ramdom_code.substring(4,8);
String st3=ramdom_code.substring(8,12);
String st4=ramdom_code.substring(12,16);
String return_code = st1+"-"+st2+"-"+st3+"-"+st4;
return return_code;
}
// 랜덤 함수 생성
public static String getRandom(String type, int loopCount) {
String dummyString="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlmnopqrstuvwxyz";
if (type != null){
if (type.equals("123")) {
dummyString = "1234567890";
} else if (type.equals("abc")) {
dummyString = "abcdefghijlmnopqrstuvwxyz";
} else if (type.equals("ABC")) {
dummyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
} else if (type.equals("ABC123") || type.equals("123ABC")) {
dummyString = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
} else if (type.equals("abc123") || type.equals("123abc")) {
dummyString = "1234567890abcdefghijklmnopqrstuvwxyz";
} else if (type.equals("aA1!")) {
dummyString = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@#$%_-";
}
}
Random random=new Random();
// char 48=0 65=A 90=Z 97=a 122=z
StringBuilder tempBuilder=new StringBuilder(100);
int randomInt;
char tempChar;
for (int loop=0; loop<loopCount; loop++) {
randomInt=random.nextInt(dummyString.length());
tempChar=dummyString.charAt(randomInt);
tempBuilder.append(tempChar);
}
return tempBuilder.toString();
}
public static String convertTimestampToDate(int timestamp) {
String dd=null;
String hh=null;
String ii=null;
String ss=null;
try {
int temp=timestamp;
dd=String.valueOf((int)Math.floor(temp/(3600*24)));
temp=temp%(3600*24);
hh=String.format("%02d", (int)Math.floor(temp/(60*60)));
temp=temp%(60*60);
ii=String.format("%02d", (int)Math.floor(temp/60));
temp=temp%60;
ss=String.format("%02d", (int)Math.floor(temp));
} catch (Exception e) {
return "-";
}
return String.format("%sd %s:%s:%s", dd,hh,ii,ss);
}
public static String createYMDDir(){
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy/MM/dd",Locale.KOREA);
Date currentTime=new Date();
String mTime=mSimpleDateFormat.format(currentTime);
return mTime;
}
public static String avoidNull(String s0, String s1) {
return StringUtil.isEmptyTrimmed(s0) ? s1 : s0;
}
public static String convert2CamelCase(String underScore) {
if (underScore.indexOf('_') < 0 && Character.isLowerCase(underScore.charAt(0))) {
return underScore;
}
StringBuilder result = new StringBuilder();
boolean nextUpper = false;
int len = underScore.length();
for (int i = 0; i < len; i++) {
char currentChar = underScore.charAt(i);
if (currentChar == '_') {
nextUpper = true;
} else {
if (nextUpper) {
result.append(Character.toUpperCase(currentChar));
nextUpper = false;
} else {
result.append(Character.toLowerCase(currentChar));
}
}
}
return result.toString();
}
}
| 160,127 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ExcelUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/ExcelUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;
import oss.fosslight.CoTopComponent;
import oss.fosslight.common.CoCodeManager;
import oss.fosslight.common.CoConstDef;
import oss.fosslight.common.ColumnMissingException;
import oss.fosslight.common.ColumnNameDuplicateException;
import oss.fosslight.common.CommonFunction;
import oss.fosslight.config.AppConstBean;
import oss.fosslight.domain.*;
import oss.fosslight.repository.CodeMapper;
import oss.fosslight.repository.ProjectMapper;
import oss.fosslight.service.FileService;
import static oss.fosslight.common.CoConstDef.*;
@PropertySources(value = {@PropertySource(value=AppConstBean.APP_CONFIG_PROPERTIES_PATH)})
@Slf4j
public class ExcelUtil extends CoTopComponent {
// Service
private static FileService fileService = (FileService) getWebappContext().getBean(FileService.class);
// Mapper
private static ProjectMapper projectMapper = (ProjectMapper) getWebappContext().getBean(ProjectMapper.class);
private static CodeMapper codeMapper = (CodeMapper) getWebappContext().getBean(CodeMapper.class);
// Sheet names that starts with specific word
public static List<String> getSheetNoStartsWith(String word, List<UploadFile> list, String excelLocalPath) throws InvalidFormatException, IOException {
List<Object> sheets = ExcelUtil.getSheetNames(list, excelLocalPath);
List<String> sheetNoList = new ArrayList<>();
for (Object sheet : sheets) {
HashMap<String, String> info = (HashMap<String, String>) sheet;
String sheetName = info.get("name");
String sheetNo = info.get("no");
if (sheetName.startsWith(word)) {
sheetNoList.add(sheetNo);
}
}
return sheetNoList;
}
public static List<Object> getSheetNames(List<UploadFile> list, String excelLocalPath) throws InvalidFormatException, FileNotFoundException, IOException {
List<Object> sheetNameList = new ArrayList<Object>();
//파일 만들기
String fileName = list.get(0).getFileName();
String[] ext = StringUtil.split(fileName, ".");
String extType = ext[ext.length-1];
String codeExt[] = StringUtil.split(codeMapper.selectExtType("12"),",");
int count = 0;
for (int i = 0; i < codeExt.length; i++){
if (codeExt[i].equalsIgnoreCase(extType)){
count++;
};
}
if (count != 1) {
sheetNameList = null;
} else {
File file = new File(excelLocalPath + "/" + fileName);
//엑셀 컬럼 읽기
Workbook wb = null;
try {
wb = WorkbookFactory.create(file);
int sheetNum = wb.getNumberOfSheets();
for (int i = 0; i < sheetNum; i++){
String no = String.valueOf(i);
String name = wb.getSheetName(i);
// Excel내 sheet이름이 "."으로 시작되는 경우 (예: .Data), 사용자가 선택하도록 보여주는 list에서 제외하여 주시기 바랍니다.
if (avoidNull(name).trim().startsWith(".")) {
continue;
}
Map<String, Object> param = new HashMap<String, Object>();
param.put("no",no);
param.put("name",name);
sheetNameList.add(param);
}
} finally {
try {
wb.close();
} catch (Exception e) {}
}
}
return sheetNameList;
}
public static List<OssComponents> getOssList(MultipartHttpServletRequest req, String excelLocalPath) {
Iterator<String> fileNames = req.getFileNames();
List<OssComponents> ossList = new ArrayList<OssComponents>();
while (fileNames.hasNext()){
//파일 만들기
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String[] fileNameArray = StringUtil.split(fileName, File.separator);
fileName = fileNameArray[fileNameArray.length-1];
File file = new File(excelLocalPath + "/" + fileName);
FileUtil.transferTo(multipart, file);
//엑셀 컬럼 읽기
HSSFWorkbook wbHSSF = null;
XSSFWorkbook wbXSSF = null;
String extType = file.getName().split("[.]")[1].trim();
int rowindex=0;
int colindex=0;
if (extType.isEmpty()) {
return null;
} else if ("xls".equals(extType) || "XLS".equals(extType)) {
try{
wbHSSF = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = wbHSSF.getSheetAt(0);
List<OssComponentsLicense> ossLicList = new ArrayList<OssComponentsLicense>();
String originalCom = "";
int totalSize = 0;
for (rowindex = 0; rowindex < sheet.getPhysicalNumberOfRows(); rowindex++) {
HSSFRow row = sheet.getRow(rowindex);
int maxcols = row.getLastCellNum();
OssComponents ossCom = new OssComponents();
OssComponentsLicense ossLicense = new OssComponentsLicense();
//다중 라이센스 여부
String emptyYN = CoConstDef.FLAG_NO;
for (colindex = 0; colindex < maxcols; colindex++) {
HSSFCell cell = row.getCell(colindex);
String value = getCellData(cell);
if (rowindex != 0){
//oss name
if (colindex == 1) {
if ("null".equals(value) || "".equals(value)){
emptyYN = CoConstDef.FLAG_YES;
}else{
ossCom.setOssName(value);
}
} else if (colindex == 2) { // oss version
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setOssVersion(value);
}
} else if (colindex == 3) { // download location
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setDownloadLocation(value);
}
} else if (colindex == 4) { // homepage
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setHomepage(value);
}
} else if (colindex == 5){ // license
if ("null".equals(value) || "".equals(value)) {
} else {
ossLicense.setLicenseName(value);
}
} else if (colindex == 6){ // license text
if ("null".equals(value) || "".equals(value)){
} else {
ossLicense.setLicenseText(value);
}
} else if (colindex == 7) { // copyright text
if ("null".equals(value) || "".equals(value)){
} else {
ossLicense.setCopyrightText(value);
}
} else if (colindex == 8) { // path or file
if ("null".equals(value) || "".equals(value)){
} else {
ossCom.setFilePath(value);
}
}
}
}
if (rowindex == 1) {
ossList.add(ossCom);
ossLicList.add(ossLicense);
originalCom = "0";
totalSize = 0;
} else if (rowindex == 0) {
} else {
if (rowindex == sheet.getPhysicalNumberOfRows()) {
if (CoConstDef.FLAG_YES.equals(emptyYN)) {
ossLicList.add(ossLicense);
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
} else {
ossList.add(ossCom);
totalSize = totalSize+1;
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
ossLicList.clear();
ossLicList.add(ossLicense);
ossList.get(totalSize).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize).getOssComponentsLicense().addAll(ossLicList);
}
} else {
if (CoConstDef.FLAG_YES.equals(emptyYN)){
ossLicList.add(ossLicense);
} else {
ossList.add(ossCom);
totalSize = totalSize+1;
if ("".equals(originalCom)){
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
} else {
ossList.get(Integer.parseInt(originalCom)).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(Integer.parseInt(originalCom)).getOssComponentsLicense().addAll(ossLicList);
originalCom = "";
}
ossLicList.clear();
ossLicList.add(ossLicense);
}
}
}
}
} catch(IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbHSSF.close();
}catch(Exception e) {}
}
} else if ("xlsx".equals(extType) || "XLSX".equals(extType)) {
try{
wbXSSF = new XSSFWorkbook(new FileInputStream(file));
XSSFSheet sheet = wbXSSF.getSheetAt(0);
List<OssComponentsLicense> ossLicList = new ArrayList<OssComponentsLicense>();
String originalCom = "";
int totalSize = 0;
for (rowindex = 0; rowindex <= sheet.getPhysicalNumberOfRows(); rowindex++){
XSSFRow row = sheet.getRow(rowindex);
int maxcols = row.getLastCellNum();
OssComponents ossCom = new OssComponents();
OssComponentsLicense ossLicense = new OssComponentsLicense();
//다중 라이센스 여부
String emptyYN = CoConstDef.FLAG_NO;
for (colindex = 0; colindex < maxcols; colindex++){
XSSFCell cell = row.getCell(colindex);
String value = getCellData(cell);
if (rowindex != 0){
if (colindex == 1){ // oss name
if ("null".equals(value) || "".equals(value)) {
emptyYN = CoConstDef.FLAG_YES;
} else {
ossCom.setOssName(value);
}
} else if (colindex == 2) { // oss version
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setOssVersion(value);
}
} else if (colindex == 3) { // download location
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setDownloadLocation(value);
}
} else if (colindex == 4) { // homepage
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setHomepage(value);
}
} else if (colindex == 5) { // license
if ("null".equals(value) || "".equals(value)) {
} else {
ossLicense.setLicenseName(value);
}
} else if (colindex == 6) { // license text
if ("null".equals(value) || "".equals(value)) {
} else {
ossLicense.setLicenseText(value);
}
} else if (colindex == 7) { // copyright text
if ("null".equals(value) || "".equals(value)) {
} else {
ossLicense.setCopyrightText(value);
}
} else if (colindex == 8) { // path or file
if ("null".equals(value) || "".equals(value)) {
} else {
ossCom.setFilePath(value);
}
}
}
}
if (rowindex == 1){
ossList.add(ossCom);
ossLicList.add(ossLicense);
originalCom = "0";
totalSize = 0;
} else if (rowindex == 0) {
} else {
if (rowindex == sheet.getPhysicalNumberOfRows()) {
if (CoConstDef.FLAG_YES.equals(emptyYN)){
ossLicList.add(ossLicense);
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
} else {
ossList.add(ossCom);
totalSize = totalSize+1;
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
ossLicList.clear();
ossLicList.add(ossLicense);
ossList.get(totalSize).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize).getOssComponentsLicense().addAll(ossLicList);
}
} else {
if (CoConstDef.FLAG_YES.equals(emptyYN)) {
ossLicList.add(ossLicense);
} else {
ossList.add(ossCom);
totalSize = totalSize+1;
if ("".equals(originalCom)) {
ossList.get(totalSize-1).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(totalSize-1).getOssComponentsLicense().addAll(ossLicList);
} else {
ossList.get(Integer.parseInt(originalCom)).setOssComponentsLicense(new ArrayList<OssComponentsLicense>());
ossList.get(Integer.parseInt(originalCom)).getOssComponentsLicense().addAll(ossLicList);
originalCom = "";
}
ossLicList.clear();
ossLicList.add(ossLicense);
}
}
}
}
} catch(IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbXSSF.close();
} catch (Exception e2) {}
}
}
}
return ossList;
}
public static String getCellData(HSSFCell cell) {
String value = "";
if (cell == null) {
value = null;
} else {
CellType cellType = cell.getCellType();
switch (cellType) {
case FORMULA:
if (CellType.NUMERIC == cell.getCachedFormulaResultType()) {
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
} else if (CellType.STRING == cell.getCachedFormulaResultType()) {
value = cell.getStringCellValue();
}
break;
case NUMERIC:
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = cell.getStringCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
default:
break;
}
}
return value;
}
public static String getCellData(XSSFCell cell) {
String value = "";
if (cell == null) {
value = null;
} else {
CellType cellType = cell.getCellType();
switch (cellType) {
case FORMULA:
if (CellType.NUMERIC == cell.getCachedFormulaResultType()) {
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
} else if (CellType.STRING == cell.getCachedFormulaResultType()) {
value = cell.getStringCellValue();
}
break;
case NUMERIC:
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = cell.getStringCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
default:
break;
}
}
return value;
}
public static boolean readReport(String readType, boolean checkId, String[] targetSheetNums, String fileSeq, List<OssComponents> list, List<String> errMsgList) {
return readReport(readType, checkId, targetSheetNums, fileSeq, list, errMsgList, false);
}
/**
*
* @param readType Report종류(3rd, SRC, BAT ...)
* @param checkId true:Report Data를 기준으로 AutoIdentification 수행여부(ossId등 미입력 상목 fill)
* @param targetSheetNums
* @param fileSeq
* @param list
* @param errMsg
* @return
*/
public static boolean readReport(String readType, boolean checkId, String[] targetSheetNums, String fileSeq,
List<OssComponents> list,List<String> errMsgList, boolean exactMatchFlag) {
T2File fileInfo = fileService.selectFileInfo(fileSeq);
if (fileInfo == null) {
log.error("파일정보를 찾을 수 없습니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("파일 정보를 찾을 수 없습니다.");
return false;
}
if (!Arrays.asList("XLS", "XLSX", "XLSM", "CSV").contains(avoidNull(fileInfo.getExt()).toUpperCase())) {
log.error("허용하지 않는 파일 입니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("허용하지 않는 파일 입니다.");
return false;
}
File file = new File(fileInfo.getLogiPath() + "/" + fileInfo.getLogiNm());
if (!file.exists() || !file.isFile()) {
log.error("파일정보를 찾을 수 없습니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("파일 정보를 찾을 수 없습니다.");
return false;
}
List<Map<String, String>> errList = new ArrayList<>(); // 전체 sheet에 대한 에러메시지 저장 리스트
// read excel file
Workbook wb = null;
try {
/*
OSS Report의 압축률이 낮아서 관련 내용 검토결과 0.9이하로 압축률이 되어 있을 경우 문제가 발생 할수 있음.
다만, 확장자를 변경시 정상동작을 하고 있어서 해당 code는 주석처리를 해둠.
//ZipSecureFile.setMinInflateRatio(-1.0d);
*/
if (fileInfo.getExt().equals("csv")) {
wb = CsvUtil.csvFileToExcelWorkbook(file, readType);
} else {
wb = WorkbookFactory.create(file);
}
// Son System의 Final List 시트가 선택되어 잇을 경우, 다른 sheet는 무시한다.
try {
Sheet sheet = wb.getSheetAt(Integer.parseInt(targetSheetNums[0]));
} catch (Exception e) {
List<String> sheetNames = new ArrayList<String>();
for (int i=0; i<wb.getNumberOfSheets(); i++) {
sheetNames.add( wb.getSheetName(i) );
}
List<String> targetSheetNumsArrayList = new ArrayList<String>();
int idx = 0;
for (String sheetName : sheetNames){
if (exactMatchFlag) {
if (sheetName.equalsIgnoreCase(readType)) {
targetSheetNumsArrayList.add(Integer.toString(idx));
}
} else {
if (sheetName.startsWith(readType)){
targetSheetNumsArrayList.add(Integer.toString(idx));
}
}
idx++;
}
if (targetSheetNumsArrayList.isEmpty()) {
targetSheetNums = new String[] {"-1"};
} else {
targetSheetNums = targetSheetNumsArrayList.toArray(new String[0]);
}
}
if (hasFileListSheet(targetSheetNums, wb)) {
// 1. final list sheet data 취득
Sheet sheet = wb.getSheet("Final List");
Map<String, String> finalListErrMsg = new HashMap<>();
finalListErrMsg = readSheet(sheet, list, true, readType, errMsgList);
if (!finalListErrMsg.isEmpty()) {
errList.add(finalListErrMsg);
}
Map<String, OssComponents> allDataMap = new HashMap<>();
// path 경로 확인
if (!list.isEmpty()) {
// 모든 시트의 정보를 읽는다.(No는 중복될 수 없다는 전제)
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
// final list는 제외
Sheet _sheet = wb.getSheetAt(i);
if ("Final List".equalsIgnoreCase(_sheet.getSheetName())) {
continue;
}
List<OssComponents> _list = new ArrayList<>();
Map<String, String> errMsg = new HashMap<>();
errMsg = readSheet(_sheet, _list, true, readType, errMsgList);
if (!errMsg.isEmpty()) {
errList.add(errMsg);
}
for (OssComponents data : _list) {
allDataMap.put(data.getReportKey(), data);
}
}
// ref col에서 참조하고 있는 File path가 다른 경우
List<OssComponents> addDiffRefList = new ArrayList<>();
for (OssComponents bean : list) {
if (bean.getFinalListRefList() != null && !bean.getFinalListRefList().isEmpty()) {
// file 단위로 입력되어 있기 때문에, ref col 이 1개 이상일 경우 path단위로 그룹핑
if (bean.getFinalListRefList().size() > 1) {
List<String> _keyList = new ArrayList<>();
for (String refKey : bean.getFinalListRefList()) {
if (allDataMap.containsKey(refKey)) {
// file 단위로 입력되어 있기 때문에, ref col 이 1개 이상일 경우 path단위로 그룹핑
// path 취득
String _path = allDataMap.get(refKey).getFilePath();
if (!_keyList.contains(_path)) {
if (!isEmpty(bean.getFilePath()) && !_keyList.contains(bean.getFilePath())) {
addDiffRefList.add(bean);
} else {
bean.setFilePath(_path);
}
_keyList.add(_path);
}
}
}
} else {
String refKey = bean.getFinalListRefList().get(0);
if (allDataMap.containsKey(refKey)) {
bean.setFilePath(allDataMap.get(refKey).getFilePath());
}
}
}
}
if (!addDiffRefList.isEmpty()) {
list.addAll(addDiffRefList);
}
}
// 2. ref sheet
} else {
for (String sheetIdx : targetSheetNums) {
if (StringUtil.isNotNumeric(sheetIdx)) {
continue;
}
// get target sheet
Sheet sheet = wb.getSheetAt(StringUtil.string2integer(sheetIdx));
Map<String, String> errMsg = new HashMap<>();
errMsg = readSheet(sheet, list, false, readType, errMsgList);
if (!errMsg.isEmpty()) {
errList.add(errMsg);
}
}
}
if (!errList.isEmpty()) { // sheet 별로 저장 된 에러 메시지를 에러 종류 별로 재 가공
String returnMsg = "";
String missHeader = "";
List<String> dupCol = new ArrayList<>();
List<String> reqCol = new ArrayList<>();
List<String> errRow = new ArrayList<>();
String emptySheet = "";
boolean newLineYn = false;
for (Map<String, String> item : errList) {
missHeader += item.containsKey("missHeader")?(isEmpty(missHeader)?"":", ").concat(item.get("missHeader")):"";
if (item.containsKey("dupCol")) {
dupCol.add(item.get("dupCol"));
}
if (item.containsKey("reqCol")) {
reqCol.add(item.get("reqCol"));
}
if (item.containsKey("errRow")) {
errRow.add(item.get("errRow"));
}
emptySheet += item.containsKey("emptySheet")?(isEmpty(emptySheet)?"":", ").concat(item.get("emptySheet")):"";
}
if (!isEmpty(missHeader)) {
returnMsg += "Can not found Header Row, Sheet Name : [".concat(missHeader).concat("]");
newLineYn = true;
}
if (!dupCol.isEmpty()) {
returnMsg += newLineYn?"<br/><br/>":"";
for (int i = 0 ; i < dupCol.size() ; i++) {
returnMsg += (i==0?"":"<br/>").concat(dupCol.get(i));
}
newLineYn = true;
}
if (!reqCol.isEmpty()) {
returnMsg += newLineYn?"<br/><br/>":"";
for (int i = 0 ; i < reqCol.size() ; i++) {
returnMsg += (i==0?"":"<br/>").concat(reqCol.get(i));
}
newLineYn = true;
}
if (!errRow.isEmpty()) {
returnMsg += newLineYn?"<br/><br/>":"";
for (int i = 0 ; i < errRow.size() ; i++) {
returnMsg += (i==0?"":"<br/>").concat(errRow.get(i));
}
newLineYn = true;
}
if (!isEmpty(emptySheet)) {
returnMsg += newLineYn?"<br/><br/>":"";
returnMsg += "There are no OSS listed. Sheet Name : [".concat(emptySheet).concat("]");
returnMsg += "<br><br>";
returnMsg += "사용한 Open Source가 없으면, OSS Name란에 하이픈(\"-\")을 기재하고, License란에서는 \"LGE Proprietary License\" (3rd Party가 자체 개발한 File일 경우, Other Proprietary License)를 선택하십시오.";
returnMsg += "<br><br>";
returnMsg += "For the files that do not use open source at all, enter \"-\" on the OSS Name field and select \"LGE Proprietary License\" on the License field (\"Other Proprietary License\" for the file obtained from the 3rd Party).";
}
throw new ColumnMissingException(returnMsg);
}
} catch (ColumnNameDuplicateException e) {
// log.error("There are duplicated header rows in the OSS Report. Please check it.<br/>" + e.getMessage());
errMsgList.add("There are duplicated header rows in the OSS Report. Please check it.<br/>" + e.getMessage());
return false;
} catch (ColumnMissingException e) {
// log.warn(e.getMessage(), e);
errMsgList.add(e.getMessage());
return false;
} catch (Exception e) {
log.error("Failed Read Excel File, file seq : " + fileSeq);
log.error(e.getMessage(), e);
errMsgList.add("report 파일에 오류가 있습니다. <br/>" + e.getMessage());
return false;
} finally {
try {
wb.close();
} catch (Exception e2) {}
}
// 사용자 입력 값을 기준으로 OSS Master 정보를 비교 ID를 설정한다.
if (checkId && list != null && !list.isEmpty()) {
// AutoIdentification 처리중 라이선스명이 사용자설정 명칭(닉네임)이 DB에 등록된 정식명칭등으로 치환되는 내용을 사용자에게 표시하기 위해
// 엑셀 파일의 원본 내용을 보관한다.
List<OssComponents> orgList = new ArrayList<>();
orgList = list;
try {
OssComponentUtil.getInstance().makeOssComponent(list, true, true);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
// TODO Auto-generated catch block
log.error(e.getMessage(), e);
errMsgList.add("오픈소슨 또는 라이선스 검출시 애러가 발생했습니다.<br/>" + e.getMessage());
return false;
}
// checkLicenseNameChanged(orgList, list, fileSeq);
}
return true;
}
public static Map<String, String> readSheet(Sheet sheet, List<OssComponents> list, boolean readNoCol,
String readType, List<String> errMsgList) {
int DefaultHeaderRowIndex = 2; // header index
int ossNameCol = -1;
int ossVersionCol = -1;
int downloadLocationCol = -1;
int homepageCol = -1;
int licenseCol = -1;
int licenseTextCol = -1;
int copyrightTextCol = -1;
int pathOrFileCol = -1;
int binaryNameCol = -1;
int excludeCol = -1;
int commentCol = -1;
// 기존 레프트 load시 제외대상 처리 여부
// "Loaded on Product" 가 X 인 row는 제외 처리
int loadOnProductCol = -1;
// final list 전용
int finalListRefCol = -1;
int noCol = -1;
// OSS Name => nickName check
int nickNameCol = -1;
// SPDX Identifier
int spdxIdentifierCol = -1;
// Pacakge Identifier
int packageIdentifierCol = -1;
// Dependencies
int dependenciesCol = -1;
Map<String, String> errMsg = new HashMap<>();
DefaultHeaderRowIndex = findHeaderRowIndex(sheet);
if (DefaultHeaderRowIndex < 0) {
if (!readNoCol) {
log.warn("Can not found Header Row, Sheet Name : " + sheet.getSheetName());
errMsg.put("missHeader", sheet.getSheetName());
}
} else {
// set column index
Row headerRow = sheet.getRow(DefaultHeaderRowIndex);
Iterator<Cell> iter = headerRow.cellIterator();
int colIdx = 0;
List<String> dupColList = new ArrayList<>();
while (iter.hasNext()) {
Cell cell = (Cell) iter.next();
String value = avoidNull(getCellData(cell)).toUpperCase().trim();
// 각 컬럼별 colindex 찾기
// 기존 report와 해더 칼럼명 호환 처리가 필요한 경우 여기에 추가
switch (value) {
case "OSS NAME":
case "OSS NAME ( OPEN SOURCE SOFTWARE NAME )":
case "OSS COMPONENT":
case "PACKAGE NAME":
if (ossNameCol > -1) {
dupColList.add(value);
}
ossNameCol = colIdx;
break;
case "OSS VERSION":
case "PACKAGE VERSION":
if (ossVersionCol > -1) {
dupColList.add(value);
}
ossVersionCol = colIdx;
break;
case "DOWNLOAD LOCATION":
case "PACKAGE DOWNLOAD LOCATION":
if (downloadLocationCol > -1) {
dupColList.add(value);
}
downloadLocationCol = colIdx;
break;
case "HOMEPAGE":
case "OSS WEBSITE":
case "HOME PAGE":
if (homepageCol > -1) {
dupColList.add(value);
}
homepageCol = colIdx;
break;
case "LICENSE":
case "LICENSE CONCLUDED":
if (licenseCol > -1) {
dupColList.add(value);
}
licenseCol = colIdx;
break;
case "LICENSE TEXT":
if (licenseTextCol > -1) {
dupColList.add(value);
}
licenseTextCol = colIdx;
break;
case "COPYRIGHT TEXT":
case "COPYRIGHT & LICENSE":
case "PACKAGE COPYRIGHT TEXT":
case "FILE COPYRIGHT TEXT":
if (copyrightTextCol > -1) {
dupColList.add(value);
}
copyrightTextCol = colIdx;
break;
case "PATH OR FILE":
case "PATH":
case "FILE OR DIRECTORY":
case "FILE PATH":
case "DIRECTORY":
case "SOURCE CODE DIRECTORY (FILE)":
case "PATH OR BINARY" :
case "BINARY NAME OR (IF DELIVERY FORM IS SOURCE CODE) SOURCE PATH":
case "FILE NAME OR PATH":
case "SOURCE NAME OR PATH":
case "MANIFEST FILE":
if (pathOrFileCol > -1) {
dupColList.add(value);
}
pathOrFileCol = colIdx;
break;
case "BINARY NAME OR SOURCE PATH":
if ("BIN".equalsIgnoreCase(readType)) {
if (binaryNameCol > -1) {
dupColList.add(value);
}
binaryNameCol = colIdx;
} else {
if (pathOrFileCol > -1) {
dupColList.add(value);
}
pathOrFileCol = colIdx;
}
break;
case "LOADED ON PRODUCT":
if (loadOnProductCol > -1) {
dupColList.add(value);
}
loadOnProductCol = colIdx;
break;
case "REF. COLUMNS":
if (finalListRefCol > -1) {
dupColList.add(value);
}
finalListRefCol = colIdx;
break;
case "NO":
case "ID":
if (noCol > -1) {
dupColList.add(value);
}
noCol = colIdx;
break;
case "BINARY FILE":
case "BINARY/LIBRARY FILE":
case "BINARY NAME":
if (binaryNameCol > -1) {
dupColList.add(value);
}
binaryNameCol = colIdx;
break;
case "EXCLUDE":
if (excludeCol > -1) {
dupColList.add(value);
}
excludeCol = colIdx;
break;
case "COMMENT":
case "LICENSE COMMENTS":
if (commentCol > -1) {
dupColList.add(value);
}
commentCol = colIdx;
break;
case "NICK NAME":
if (nickNameCol > -1) {
dupColList.add(value);
}
nickNameCol = colIdx;
break;
case "FILE NAME":
if (binaryNameCol > -1) {
dupColList.add(value);
}
binaryNameCol = colIdx;
if (pathOrFileCol > -1) {
dupColList.add(value);
}
pathOrFileCol = colIdx;
break;
case "PACKAGE IDENTIFIER":
if (packageIdentifierCol > -1) {
dupColList.add(value);
}
packageIdentifierCol = colIdx;
break;
case "SPDX IDENTIFIER":
if (spdxIdentifierCol > -1) {
dupColList.add(value);
}
spdxIdentifierCol = colIdx;
case "DEPENDENCIES":
if (dependenciesCol > -1) {
dupColList.add(value);
}
dependenciesCol = colIdx;
default:
break;
}
colIdx++;
}
// header 중복 체크
if (!dupColList.isEmpty()) {
String msg = dupColList.toString();
msg = "There are duplicated. Sheet Name : [".concat(sheet.getSheetName()).concat("], Filed Name : ").concat(msg);
errMsg.put("dupCol", msg);
}
// 필수 header 누락 시 Exception
List<String> colNames = new ArrayList<String>();
if (licenseCol < 0) {
colNames.add("LICENSE");
}
// Per file info sheet of SPDX Spreadsheet does not proceed
if (packageIdentifierCol < 0) {
if (ossNameCol < 0) {
colNames.add("OSS NAME");
}
if (ossVersionCol < 0) {
colNames.add("OSS VERSION");
}
}
if (!colNames.isEmpty()) {
String msg = colNames.toString();
msg = "No required fields were found. Sheet Name : [".concat(sheet.getSheetName()).concat("], Filed Name : ").concat(msg);
errMsg.put("reqCol", msg);
}
String lastOssName = "";
String lastOssVersion = "";
String lastFilePath = "";
String lastBinaryName = "";
String lastExcludeYn = "";
List<String> duplicateCheckList = new ArrayList<>();
List<String> errRow = new ArrayList<>();
for (int rowIdx = DefaultHeaderRowIndex+1; rowIdx < sheet.getPhysicalNumberOfRows(); rowIdx++) {
try {
// final list의 ref Data를 찾을 경우, No Cell이 없는 시트는 무시
if (readNoCol && noCol < 0) {
continue;
}
Row row = sheet.getRow(rowIdx);
if (row == null) {
continue;
}
// 신분석결과서 대응 (작성 가이드 row는 제외)
if (noCol > -1 && "-".equals(avoidNull(getCellData(row.getCell(noCol))))) {
continue;
}
OssComponents bean = new OssComponents();
// The SPDX Spradsheet reads the same row as the Package Identifier of the Per File Info sheet and the Spdx Identifier of the Package Info sheet
if (ossNameCol < 0) {
bean.setBinaryName(binaryNameCol < 0 ? "" : avoidNull(getCellData(row.getCell(binaryNameCol))).trim().replaceAll("\t", ""));
bean.setCopyrightText(copyrightTextCol < 0 ? "" : getCellData(row.getCell(copyrightTextCol)));
bean.setComments(commentCol < 0 ? getCellData(row.getCell(licenseCol)).trim() : getCellData(row.getCell(licenseCol)).trim() + ", " + getCellData(row.getCell(commentCol)).trim());
bean.setFilePath(pathOrFileCol < 0 ? "" : avoidNull(getCellData(row.getCell(pathOrFileCol))).trim().replaceAll("\t", ""));
if (bean.getCopyrightText() == ""){
bean.setCopyrightText(" ");
}
String packageIdentifier = getCellData(row.getCell(packageIdentifierCol));
boolean nullCheck = true;
for (int beanIndex = 0; beanIndex < list.size(); beanIndex++) {
OssComponents temp = list.get(beanIndex);
if (packageIdentifier.equals(temp.getSpdxIdentifier())){
nullCheck = false;
bean.setOssName(temp.getOssName());
bean.setOssVersion(temp.getOssVersion());
bean.setDownloadLocation(temp.getDownloadLocation());
bean.setHomepage(temp.getHomepage());
break;
}
}
if (nullCheck) {
bean.setOssName("");
bean.setOssVersion("");
bean.setDownloadLocation("");
bean.setHomepage("");
}
} else {
// basic info
bean.setOssName(ossNameCol < 0 ? "" : avoidNull(getCellData(row.getCell(ossNameCol))).trim().replaceAll("\t", ""));
bean.setOssVersion(ossVersionCol < 0 ? "" : avoidNull(getCellData(row.getCell(ossVersionCol))).trim().replaceAll("\t", ""));
String downloadLocation = avoidNull(getCellData(row.getCell(downloadLocationCol))).trim().replaceAll("\t", "");
if (downloadLocation.equals("NONE") || downloadLocation.equals("NOASSERTION") || downloadLocationCol < 0) {
bean.setDownloadLocation("");
} else {
bean.setDownloadLocation(downloadLocation);
}
bean.setHomepage(homepageCol < 0 ? "" : avoidNull(getCellData(row.getCell(homepageCol))).trim().replaceAll("\t", ""));
bean.setFilePath(pathOrFileCol < 0 ? "" : avoidNull(getCellData(row.getCell(pathOrFileCol))).trim().replaceAll("\t", ""));
bean.setBinaryName(binaryNameCol < 0 ? "" : avoidNull(getCellData(row.getCell(binaryNameCol))).trim().replaceAll("\t", ""));
String copyrightText = getCellData(row.getCell(copyrightTextCol));
if (copyrightText.equals("NONE") || copyrightText.equals("NOASSERTION") || copyrightTextCol < 0) {
bean.setCopyrightText("");
} else {
bean.setCopyrightText(copyrightText);
}
bean.setOssNickName(nickNameCol < 0 ? "" : getCellData(row.getCell(nickNameCol)));
bean.setSpdxIdentifier(spdxIdentifierCol < 0 ? "" : getCellData(row.getCell(spdxIdentifierCol)));
}
duplicateCheckList.add(avoidNull(bean.getOssName()) + "-" + avoidNull(bean.getOssVersion()) + "-" + avoidNull(bean.getLicenseName()));
// final list인 경우
if (finalListRefCol > 0) {
bean.setFinalListRefList(Arrays.asList(avoidNull(getCellData(row.getCell(finalListRefCol))).split(",")));
}
if (readNoCol) {
bean.setReportKey(getCellData(row.getCell(noCol)));
}
String licenseConcluded = getCellData(row.getCell(licenseCol));
if (isSPDXSpreadsheet(sheet) && (licenseConcluded.contains("AND") || licenseConcluded.contains("OR"))) {
String licenseComment = getCellData(row.getCell(commentCol));
String comment = "";
if (!licenseConcluded.isEmpty()) {
comment += licenseConcluded;
}
if (!licenseComment.isEmpty()) {
if (licenseConcluded.isEmpty()) {
comment += licenseComment;
} else {
comment += " / " + licenseComment;
}
}
bean.setComments(commentCol < 0 ? "" : comment.trim());
} else {
bean.setComments(commentCol < 0 ? "" : getCellData(row.getCell(commentCol)).trim());
}
// oss Name을 입력하지 않거나, 이전 row와 oss name, oss version이 동일한 경우, 멀티라이선스로 판단
OssComponentsLicense subBean = new OssComponentsLicense();
String licenseName = getCellData(row.getCell(licenseCol));
if (isSPDXSpreadsheet(sheet)){
licenseName = StringUtil.join(Arrays.asList(licenseName.split("\\(|\\)| ")).stream().filter(l -> !isEmpty(l) && !l.equals("AND") && !l.equals("OR")).collect(Collectors.toList()), ",");
} else if (licenseName.contains(",")) {
licenseName = StringUtil.join(Arrays.asList(licenseName.split(",")).stream().filter(l -> !isEmpty(l)).collect(Collectors.toList()), ",");
}
if (!licenseName.matches("\\A\\p{ASCII}*\\z")) {
byte[] asciiValues = licenseName.getBytes(StandardCharsets.US_ASCII);
byte[] asciiValuesRetry = new byte[asciiValues.length];
for (int i=0; i < asciiValues.length ; i++) {
if (asciiValues[i] == 63) {
asciiValuesRetry[i] = 32;
} else {
asciiValuesRetry[i] = asciiValues[i];
}
}
licenseName = new String(asciiValuesRetry);
}
subBean.setLicenseName(licenseCol < 0 ? "" : licenseName);
subBean.setLicenseText(licenseTextCol < 0 ? "" : getCellData(row.getCell(licenseTextCol)));
if ("false".equals(subBean.getLicenseText()) || "-".equals(subBean.getLicenseText())) {
subBean.setLicenseText("");
}
if ("false".equals(bean.getCopyrightText())) {
bean.setCopyrightText("");
}
// file path에 개행이 있는 경우 콤마로 변경
if (!isEmpty(bean.getFilePath()) && (bean.getFilePath().indexOf("\r\n") > -1 || bean.getFilePath().indexOf("\n") > -1)) {
String _tmpFilePath = bean.getFilePath().trim().replaceAll("\r\n", "\n");
String _replaceFilePath = "";
for (String s : _tmpFilePath.split("\n")) {
if (!isEmpty(s)) {
if (!isEmpty(_replaceFilePath)) {
_replaceFilePath += ",";
}
_replaceFilePath += s.trim();
}
}
bean.setFilePath(_replaceFilePath);
}
// empty row check
if (isEmpty(bean.getOssName()) && isEmpty(bean.getOssVersion()) && isEmpty(subBean.getLicenseName()) && isEmpty(bean.getBinaryName()) && isEmpty(bean.getFilePath())
&& isEmpty(bean.getDownloadLocation()) && isEmpty(bean.getHomepage()) && isEmpty(bean.getCopyrightText())) {
continue;
}
// 기존 레포트에서 load on product 칼럼이 있는 경우, X선택된 row는 제외
// 또는 신분석결과서의 exclude 칼럼
if ( (loadOnProductCol > 0 && "X".equalsIgnoreCase(getCellData(row.getCell(loadOnProductCol))))
|| (excludeCol > -1 && "Exclude".equalsIgnoreCase(getCellData(row.getCell(excludeCol)))) ) {
bean.setExcludeYn(CoConstDef.FLAG_YES);
}
// default
bean.setExcludeYn(avoidNull(bean.getExcludeYn(), CoConstDef.FLAG_NO));
if (dependenciesCol > -1) {
bean.setDependencies(dependenciesCol < 0 ? "" : avoidNull(getCellData(row.getCell(dependenciesCol))).trim().replaceAll("\t", ""));
}
// homepage와 download location이 http://로 시작하지 않을 경우 자동으로 체워줌
// if (!isEmpty(bean.getHomepage())
// && !(bean.getHomepage().toLowerCase().startsWith("http://")
// || bean.getHomepage().toLowerCase().startsWith("https://")
// || bean.getHomepage().toLowerCase().startsWith("ftp://"))
// && !bean.getDownloadLocation().toLowerCase().startsWith("git://")) {
// bean.setHomepage("http://" + bean.getHomepage());
// }
//
// if (!isEmpty(bean.getDownloadLocation())
// && !(bean.getDownloadLocation().toLowerCase().startsWith("http://")
// || bean.getDownloadLocation().toLowerCase().startsWith("https://")
// || bean.getDownloadLocation().toLowerCase().startsWith("ftp://")
// )
// && !bean.getDownloadLocation().toLowerCase().startsWith("git://")) {
// bean.setDownloadLocation("http://" + bean.getDownloadLocation());
// }
// 이슈 처리로 인해 주석처리함. OSS Name, OSS Version을 작성하지 않은 OSS Info는 상단 OSS Info와 merge하지 않음.
bean.addOssComponentsLicense(subBean);
list.add(bean);
lastOssName = bean.getOssName();
lastOssVersion = bean.getOssVersion();
lastFilePath = bean.getFilePath();
lastBinaryName = bean.getBinaryName();
lastExcludeYn = bean.getExcludeYn();
} catch (Exception e) {
errRow.add("Row : " + String.valueOf(rowIdx) + ", Message : " + e.getMessage());
}
}
if (!errRow.isEmpty()) {
String msg = errRow.toString();
msg = "Error Sheet. Sheet Name : [".concat(sheet.getSheetName()).concat("], ").concat(msg);
errMsg.put("errRow", msg);
}
if (list.isEmpty()) {
errMsg.put("emptySheet", sheet.getSheetName());
}
}
return errMsg;
}
private static boolean isSPDXSpreadsheet(Sheet sheet) {
return sheet.getSheetName().equals("Package Info") || sheet.getSheetName().equals("Per File Info");
}
private static boolean hasSameLicense(OssComponents ossComponents, OssComponentsLicense subBean) {
if (ossComponents != null && subBean != null) {
if (ossComponents.getOssComponentsLicense() == null || ossComponents.getOssComponentsLicense().isEmpty()) {
return false;
}
// license name이 닉네임으로 등록될 수 있어서 알단, DB에 등록되어 있는 라이선스의 경우 정식 명칭을 기준으로 비교
// 둘중에 하나라도 db에 등록되어 있지 않은 경우, 원본을 기준으로 비교
for (OssComponentsLicense license : ossComponents.getOssComponentsLicense()) {
if (avoidNull(subBean.getLicenseName()).equalsIgnoreCase(license.getLicenseName())) {
return true;
}
String _temp1 = avoidNull(license.getLicenseName());
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(_temp1.toUpperCase())) {
_temp1 = CoCodeManager.LICENSE_INFO_UPPER.get(_temp1.toUpperCase()).getLicenseId();
}
String _temp2 = avoidNull(subBean.getLicenseName());
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(_temp2.toUpperCase())) {
_temp2 = CoCodeManager.LICENSE_INFO_UPPER.get(_temp2.toUpperCase()).getLicenseId();
}
if (_temp1.equals(_temp2)) {
return true;
}
}
}
return false;
}
private static void readAndroidBuildImageSheet(Sheet sheet, List<OssComponents> list, List<String> errMsgList) {
int DefaultHeaderRowIndex = 2; // default header index
int ossNameCol = -1;
int ossVersionCol = -1;
int downloadLocationCol = -1;
int homepageCol = -1;
int licenseCol = -1;
int licenseTextCol = -1;
int copyrightTextCol = -1;
int pathOrFileCol = -1;
int binaryFileCol = -1;
// 기존 레프트 load시 제외대상 처리 여부
// "Loaded on Product" 가 X 인 row는 제외 처리
int loadOnProductCol = -1;
int noCol = -1;
int noticeHtmlCol = -1;
int excludeCol = -1;
int commentCol = -1;
DefaultHeaderRowIndex = findHeaderRowIndex(sheet);
if (DefaultHeaderRowIndex < 0) {
errMsgList.add("Can not found Header Row, Sheet Name : " + sheet.getSheetName());
return;
}
// set column index
Row headerRow = sheet.getRow(DefaultHeaderRowIndex);
Iterator<Cell> iter = headerRow.cellIterator();
int colIdx = 0;
while (iter.hasNext()) {
Cell cell = (Cell) iter.next();
String value = avoidNull(getCellData(cell)).toUpperCase();
// 각 컬럼별 colindex 찾기
// 기존 report와 해더 칼럼명 호환 처리가 필요한 경우 여기에 추가
switch (value) {
case "OSS COMPONENT":
case "OSS NAME":
if (ossNameCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
ossNameCol = colIdx;
break;
case "OSS VERSION":
if (ossVersionCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
ossVersionCol = colIdx;
break;
case "DOWNLOAD LOCATION":
if (downloadLocationCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
downloadLocationCol = colIdx;
break;
case "HOMEPAGE":
case "OSS WEBSITE":
if (homepageCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
homepageCol = colIdx;
break;
case "LICENSE":
if (licenseCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
licenseCol = colIdx;
break;
case "LICENSE TEXT":
if (licenseTextCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
licenseTextCol = colIdx;
break;
case "COPYRIGHT TEXT":
case "COPYRIGHT & LICENSE":
if (copyrightTextCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
copyrightTextCol = colIdx;
break;
case "BINARY/LIBRARY FILE":
case "BINARY NAME":
if (binaryFileCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
binaryFileCol = colIdx;
break;
case "DIRECTORY":
case "SOURCE CODE PATH":
if (pathOrFileCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
pathOrFileCol = colIdx;
break;
case "LOADED ON PRODUCT":
if (loadOnProductCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
loadOnProductCol = colIdx;
break;
case "NO":
case "ID":
if (noCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
noCol = colIdx;
break;
case "NOTICE.HTML":
if (noticeHtmlCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
noticeHtmlCol = colIdx;
break;
case "EXCLUDE":
if (excludeCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
excludeCol = colIdx;
break;
case "COMMENT":
if (commentCol > -1) {
throw new ColumnNameDuplicateException(sheet.getSheetName() + "." + value);
}
commentCol = colIdx;
break;
default:
break;
}
colIdx++;
}
// 필수 header 누락 시 Exception
List<String> colNames = new ArrayList<String>();
if (ossNameCol < 0) {
colNames.add("OSS NAME");
}
if (ossVersionCol < 0) {
colNames.add("OSS VERSION");
}
if (licenseCol < 0) {
colNames.add("LICENSE");
}
if (colNames.size() > 0) {
String colNameTxt = "";
for (int j = 0 ; j < colNames.size() ; j++) {
colNameTxt += (j==0?"":", ") + colNames.get(j);
}
throw new ColumnMissingException("No required fields were found in the report file.<br/>Sheet Name: " + sheet.getSheetName() + ", Filed Name: " + colNameTxt);
}
String lastOssName = "";
String lastOssVersion = "";
String lastFilePath = "";
String lastBinaryName = "";
for (int rowIdx = DefaultHeaderRowIndex+1; rowIdx < sheet.getPhysicalNumberOfRows(); rowIdx++) {
try {
Row row = sheet.getRow(rowIdx);
// 신분석결과서 대응 (작성 가이드 row는 제외)
if (noCol > -1 && "-".equals(avoidNull(getCellData(row.getCell(noCol))))) {
continue;
}
OssComponents bean = new OssComponents();
// android bin의 경우 binary name을 무조건 수정할 수 있다.
// [MC요청] 2. Project List – OSS List에서 Binary DB 검색 결과 제공
// BIN[Android] binary name 수정 가능(최종변경)
bean.setCustomBinaryYn(CoConstDef.FLAG_YES);
// 기본정보
bean.setOssName(ossNameCol < 0 ? "" : getCellData(row.getCell(ossNameCol)));
bean.setOssVersion(ossVersionCol < 0 ? "" : getCellData(row.getCell(ossVersionCol)));
bean.setFilePath(pathOrFileCol < 0 ? "" : getCellData(row.getCell(pathOrFileCol)));
bean.setBinaryName(binaryFileCol < 0 ? "" : getCellData(row.getCell(binaryFileCol)));
bean.setBinaryNotice(noticeHtmlCol < 0 ? "" : getCellData(row.getCell(noticeHtmlCol)));
bean.setHomepage(homepageCol < 0 ? "" : getCellData(row.getCell(homepageCol)));
bean.setDownloadLocation(downloadLocationCol < 0 ? "" : getCellData(row.getCell(downloadLocationCol)));
bean.setCopyrightText(copyrightTextCol < 0 ? "" : getCellData(row.getCell(copyrightTextCol)));
bean.setComments(commentCol < 0 ? "" : getCellData(row.getCell(commentCol)));
// android 의 경우는 list에는 포함시키고 exclude하는 것으로 변경
// 기존 레포트에서 load on product 칼럼이 있는 경우, X선택된 row는 제외
if ( (loadOnProductCol > 0 && "X".equalsIgnoreCase(getCellData(row.getCell(loadOnProductCol))))
|| (excludeCol > -1 && "Exclude".equalsIgnoreCase(getCellData(row.getCell(excludeCol))) ) ) {
bean.setExcludeYn(CoConstDef.FLAG_YES);
}
// default
bean.setExcludeYn(avoidNull(bean.getExcludeYn(), CoConstDef.FLAG_NO));
// oss Name을 입력하지 않거나, 이전 row와 oss name, oss version이 동일한 경우, 멀티라이선스로 판단
// license 정보
OssComponentsLicense subBean = new OssComponentsLicense();
String licenseName = getCellData(row.getCell(licenseCol));
if (licenseName.contains(",")) {
licenseName = StringUtil.join(Arrays.asList(licenseName.split(",")).stream().filter(l -> !isEmpty(l)).collect(Collectors.toList()), ",");
}
subBean.setLicenseName(licenseCol < 0 ? "" : licenseName);
subBean.setLicenseText(licenseTextCol < 0 ? "" : getCellData(row.getCell(licenseTextCol)));
if ("false".equals(subBean.getLicenseText()) || "-".equals(subBean.getLicenseText())) {
subBean.setLicenseText("");
}
if ("false".equals(bean.getCopyrightText())) {
bean.setCopyrightText("");
}
if (isEmpty(bean.getBinaryName()) && isEmpty(bean.getOssName()) && isEmpty(bean.getOssVersion()) && isEmpty(subBean.getLicenseName()) && isEmpty(bean.getFilePath())
&& isEmpty(bean.getDownloadLocation()) && isEmpty(bean.getHomepage()) && isEmpty(bean.getCopyrightText())) {
continue;
}
// homepage와 download location이 http://로 시작하지 않을 경우 자동으로 체워줌(* download location의 경우 git으로 시작 시 http://를 붙이지 않음.)
// if (!isEmpty(bean.getHomepage())
// && !(bean.getHomepage().toLowerCase().startsWith("http://")
// || bean.getHomepage().toLowerCase().startsWith("https://"))
// && !bean.getDownloadLocation().toLowerCase().startsWith("git://")) {
// bean.setHomepage("http://" + bean.getHomepage());
// }
//
// if (!isEmpty(bean.getDownloadLocation())
// && !(bean.getDownloadLocation().toLowerCase().startsWith("http://")
// || bean.getDownloadLocation().toLowerCase().startsWith("https://"))
// && !bean.getDownloadLocation().toLowerCase().startsWith("git://")) {
// bean.setDownloadLocation("http://" + bean.getDownloadLocation());
// }
bean.addOssComponentsLicense(subBean);
list.add(bean);
lastOssName = bean.getOssName();
lastOssVersion = bean.getOssVersion();
lastFilePath = bean.getFilePath();
lastBinaryName = bean.getBinaryName();
} catch (Exception e) {
errMsgList.add("Error Row -> Sheet : ["+sheet.getSheetName()+"], Row : ["+rowIdx+"] message : ["+e.getMessage()+"]" );
}
}
if (list.isEmpty()) {
errMsgList.add("There are no OSS listed. Sheet Name : " + sheet.getSheetName());
}
}
/**
* Sheet명이 final list이고, ref. columns 칼럼을 포함하고 있을 경우, son system의 final list로 판단.
* @param targetSheetNums
* @param wb
* @return
*/
private static boolean hasFileListSheet(String[] targetSheetNums, Workbook wb) {
for (String sheetIdx : targetSheetNums) {
if (StringUtil.isNotNumeric(sheetIdx)) {
continue;
}
Sheet sheet = wb.getSheetAt(Integer.parseInt(sheetIdx));
if ("Final List".equalsIgnoreCase(sheet.getSheetName()) && hasCol(sheet, "Ref. Columns")) {
return true;
}
}
return false;
}
/**
* Sheet 내에서 calVal에 해당하는 cell이 존재하는지 체크한다.
* 최대 row 10개, cell 20개 까지만 체크해서 존재하지 않을 경우 false를 반환한다.
* @param sheet
* @param colVal
* @return
*/
private static boolean hasCol(Sheet sheet, String colVal) {
int rowCheckMaxCnt = 10;
int cellCheckMaxCnt = 20;
int rowCnt = 0;
for (Row row : sheet) {
int cellcnt = 0;
for (Cell cell : row) {
if (colVal.equalsIgnoreCase(getCellData(cell))) {
return true;
}
if (cellcnt > cellCheckMaxCnt) {
break;
}
cellcnt ++;
}
if (rowCnt > rowCheckMaxCnt ) {
break;
}
rowCnt ++;
}
return false;
}
/**
* row의 시작지점을 찾는다. (NO cell이 포함되어 있는 row)
* @param sheet
* @return
*/
private static int findHeaderRowIndex(Sheet sheet) {
// 최대 10번째 row 까지만 검색
for (Row row : sheet) {
// 최대 5개까지만 확인
int maxCnt = 0;
for (Cell cell : row) {
String id = avoidNull(getCellData(cell)).trim().toUpperCase();
if ("NO".equalsIgnoreCase(id) || "ID".equalsIgnoreCase(id) || "PACKAGE NAME".equalsIgnoreCase(id) || "FILE NAME".equalsIgnoreCase(id)) {
return row.getRowNum();
}
if (maxCnt > 5) {
break;
}
}
}
// 찾지못한경우 신규 report 양식으로 지정
return -1;
}
private static String getCellData(Cell cell) {
String value = "";
if (cell == null) {
} else {
CellType cellType = cell.getCellType();
switch (cellType) {
case FORMULA:
if (CellType.NUMERIC == cell.getCachedFormulaResultType()) {
cell.setCellType(CellType.STRING);
value = cell.getStringCellValue();
} else if (CellType.STRING == cell.getCachedFormulaResultType()) {
value = cell.getStringCellValue();
}
break;
case NUMERIC:
value = Double.toString(cell.getNumericCellValue());
Cell _tempCell = cell;
_tempCell.setCellType(CellType.STRING);
String _temp = _tempCell.getStringCellValue();
if (_temp.indexOf(".") == -1 && value.indexOf(".") > -1) {
value = value.substring(0, value.indexOf("."));
}
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = cell.getStringCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
case BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
default:
break;
}
}
if (value == null) {
value = "";
}
// 트림으로 공백 제거 되지 않는것들 정규식으로 앞 뒤 공백만 제거 한다
return "false".equals(value) ? "" : StringUtil.isNumeric(value) ? StringUtil.trim(value) : StringUtil.trim(value).replaceAll("(^\\p{Z}+|\\p{Z}+$)", "");
}
public static Map<String, List<Project>> getModelList(MultipartFile multipart, String localPath, String distributionType, String prjId, String modelListAppendFlag, String modelSeq) {
List<Project> resultModel = new ArrayList<Project>();
List<Project> resultModelDelete = new ArrayList<Project>();
Map<String, List<Project>> result = readModelList(multipart, localPath, prjId, modelListAppendFlag, modelSeq, distributionType);
return result;
}
public static Map<String, List<Project>> getModelList(MultipartHttpServletRequest req, String localPath, String distributionType, String prjId, String modelListAppendFlag, String modelSeq) {
Map<String, List<Project>> result = new HashMap<>();
List<Project> resultModel = new ArrayList<Project>();
List<Project> resultModelDelete = new ArrayList<Project>();
Iterator<String> fileNames = req.getFileNames();
while (fileNames.hasNext()) {
Map<String, List<Project>> tempResult = readModelList(req.getFile(fileNames.next()), localPath, prjId, modelListAppendFlag, modelSeq, distributionType);
resultModelDelete.addAll(tempResult.get("delModelList"));
resultModel.addAll(tempResult.get("currentModelList"));
}
result.put("currentModelList", resultModel);
result.put("delModelList", resultModelDelete);
return result;
}
public static List<String[]> getModelList(MultipartFile multipart, String localPath) {
List<String[]> models = new ArrayList<>();
String fileName = multipart.getOriginalFilename();
String[] ext = StringUtil.split(fileName, ".");
String extType = ext[ext.length - 1];
String codeExt[] = StringUtil.split(codeMapper.selectExtType("11"), ",");
int count = 0;
for (int i = 0; i < codeExt.length; i++) {
if (codeExt[i].equals(extType)) {
count++;
}
}
SimpleDateFormat dateFormatParser = new SimpleDateFormat("yyyyMMdd");
dateFormatParser.setLenient(false);
if (count == 1) {
if (fileName.indexOf("/") > -1) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
log.debug("File upload OriginalFileName Substring with File.separator : " + fileName);
}
if (fileName.indexOf("\\") > -1) {
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
log.debug("File upload OriginalFileName Substring with File.separator : " + fileName);
}
File file = new File(localPath + "/" + fileName);
FileUtil.transferTo(multipart, file);
Workbook wb = null;
try {
wb = WorkbookFactory.create(file);
int colindex = 0;
Sheet sheet = wb.getSheetAt(0);
Row row = null;
for (int idx = 1; idx <= sheet.getPhysicalNumberOfRows(); idx++) {
row = sheet.getRow(idx);
if (row == null) {
continue;
}
int maxcols = row.getLastCellNum();
String[] model = new String[]{"", "", "", ""};
for (colindex = 0; colindex < maxcols; colindex++) {
Cell cell = row.getCell(colindex);
String value = null;
if (colindex == 2) {
value = getReleaseData(cell, dateFormatParser);
} else {
value = getCellData(cell);
}
if (colindex < model.length && value != null) {
model[colindex] = value;
}
}
if (!model[0].isEmpty() && !model[1].isEmpty()) {
models.add(model);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
wb.close();
} catch (Exception e) {
}
}
}
return models;
}
private static String getReleaseData(Cell cell, SimpleDateFormat dateFormatParser) {
String value = "";
DataFormatter formatter = new DataFormatter();
boolean releaseDataFlag = false;
if (cell == null) {
} else {
CellType cellType = cell.getCellType();
switch (cellType) {
case NUMERIC:
value = formatter.formatCellValue(cell);
try {
dateFormatParser.parse(value);
releaseDataFlag = true;
} catch (Exception e) {
releaseDataFlag = false;
}
if (!releaseDataFlag) {
value = "false";
}
break;
case STRING:
value = cell.getStringCellValue() + "";
try {
dateFormatParser.parse(value);
releaseDataFlag = true;
} catch (Exception e) {
releaseDataFlag = false;
}
if (!releaseDataFlag) {
value = "false";
}
break;
case BLANK:
value = cell.getStringCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
case BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
default:
break;
}
}
if (value == null) {
value = "";
}
return "false".equals(value) ? "" : StringUtil.isNumeric(value) ? StringUtil.trim(value) : StringUtil.trim(value).replaceAll("(^\\p{Z}+|\\p{Z}+$)", "");
}
public static Map<String, List<Project>> readModelFromList(List<String[]> models, String prjId, String modelListAppendFlag, String modelSeq, String distributionType) {
Map<String, List<Project>> result = new HashMap<>();
List<Project> resultModel = new ArrayList<Project>();
List<Project> resultModelDelete = new ArrayList<Project>();
List<Project> deDuplicateModelList = new ArrayList<Project>();
ArrayList<String> duplicateModel = new ArrayList<String>();
List<Project> modelList = projectMapper.selectModelList(prjId);
List<Project> modelDeleteList = projectMapper.selectDeleteModelList(prjId);
Map<String, Project> osddModelInfo = new HashMap<>();
String modelCode = CoConstDef.CD_DISTRIBUTE_SITE_SKS.equals(distributionType) ? CoConstDef.CD_MODEL_TYPE2 : CoConstDef.CD_MODEL_TYPE;
if (modelList != null) {
for (Project bean : modelList) {
if (CoConstDef.FLAG_YES.equals(bean.getOsddSyncYn())) {
osddModelInfo.put(bean.getCategory() + "|" + bean.getModelName().trim().toUpperCase(), bean);
}
}
for (Project bean : modelDeleteList) {
if (CoConstDef.FLAG_YES.equals(bean.getOsddSyncYn())) {
osddModelInfo.put(bean.getCategory() + "|" + bean.getModelName().trim().toUpperCase(), bean);
}
}
}
int rowIdx = Integer.parseInt(avoidNull(modelSeq, "0"));
for (String[] model : models) {
Project param = new Project();
for (int colIdx = 0; colIdx < model.length; colIdx++) {
String value = model[colIdx];
if (colIdx == 0) {
param.setModelName(value.trim().toUpperCase());
} else if (colIdx == 1) {
String main = StringUtil.trim(StringUtil.split(value, ">")[0]);
String sub = StringUtil.trim(StringUtil.split(value, ">")[1]);
for (String s : CoCodeManager.getCodes(modelCode)) {
if (CoCodeManager.getCodeString(modelCode, s).equals(main)) {
main = s;
String subCdNo = CoCodeManager.getSubCodeNo(modelCode, s);
for (String subCode : CoCodeManager.getCodes(subCdNo)) {
if (CoCodeManager.getCodeString(subCdNo, subCode).equals(sub)) {
sub = subCode;
break;
}
}
break;
}
}
param.setCategory(main + sub);
} else if (colIdx == 2) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
param.setReleaseDate(formatter.format(value));
} catch (Exception e) {
param.setReleaseDate(value);
}
} else if (colIdx == 3) { // delete
value = avoidNull(value).trim();
if (!isEmpty(value) && CoConstDef.FLAG_YES.equals(value) || "1".equals(value)) {
param.setDelYn(CoConstDef.FLAG_YES);
} else {
param.setDelYn(CoConstDef.FLAG_NO);
}
}
}
String key = param.getCategory() + "|" + param.getModelName();
if (osddModelInfo.containsKey(key)) {
if (CoConstDef.FLAG_YES.equals(modelListAppendFlag)) {
continue;
}
Project modelBean = osddModelInfo.get(key);
param.setOsddSyncYn(CoConstDef.FLAG_YES);
param.setModifier(modelBean.getModifier());
param.setModifiedDate(modelBean.getModifiedDate());
}
if (!CoConstDef.FLAG_YES.equals(param.getDelYn())) {
if (!duplicateModel.contains(key)) {
param.setGridId(prjId + CoConstDef.FLAG_NO + ++rowIdx);
resultModel.add(param);
duplicateModel.add(key);
}
} else {
param.setGridId(prjId + CoConstDef.FLAG_YES + ++rowIdx);
resultModelDelete.add(param);
}
}
if (CoConstDef.FLAG_YES.equals(modelListAppendFlag)) {
deDuplicateModelList = modelList
.stream()
.filter(before ->
resultModel
.stream()
.filter(after ->
(before.getCategory() + "|" + before.getModelName()).equalsIgnoreCase(after.getCategory() + "|" + after.getModelName())
).collect(Collectors.toList()).size() == 0
).collect(Collectors.toList());
deDuplicateModelList.addAll(resultModel);
}
if (CoConstDef.FLAG_YES.equals(modelListAppendFlag)) {
result.put("currentModelList", deDuplicateModelList);
} else {
result.put("currentModelList", resultModel);
}
result.put("delModelList", resultModelDelete);
return result;
}
public static Map<String, List<Project>> readModelList(MultipartFile multipart, String localPath, String prjId, String modelListAppendFlag, String modelSeq, String distributionType) {
List<String[]> models = getModelList(multipart, localPath);
Map<String, List<Project>> result = readModelFromList(models, prjId, modelListAppendFlag, modelSeq, distributionType);
return result;
}
public static List<OssComponents> getVerificationList(MultipartHttpServletRequest req, List<OssComponents> ossComponents, String localPath) {
List<ProjectIdentification> result = new ArrayList<ProjectIdentification>();
Iterator<String> fileNames = req.getFileNames();
while (fileNames.hasNext()){
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String extType = FilenameUtils.getExtension(fileName);
UUID randomUUID = UUID.randomUUID();
File file = FileUtil.writeFile(multipart, localPath, randomUUID + "." + extType);
Workbook wb = null;
try {
wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheetAt(0);
int startRowIdx = findHeaderRowIndex(sheet);
if (startRowIdx < 0) {
log.warn("Can not found Header Row, fileName : " + fileName + " , Sheet Name : " + sheet.getSheetName());
return null;
}
Row headerRow = sheet.getRow(startRowIdx);
Iterator<Cell> iter = headerRow.cellIterator();
int _componentId = -1;
int _filePath = -1;
int _ossName = -1;
int _ossVersion = -1;
int _license = -1;
int colIdx = 0;
while (iter.hasNext()) {
Cell cell = (Cell) iter.next();
String value = avoidNull(getCellData(cell)).toUpperCase();
switch (value) {
case "ID": _componentId = colIdx; break;
case "PATH": _filePath = colIdx; break;
case "OSS NAME": _ossName = colIdx; break;
case "OSS VERSION": _ossVersion = colIdx; break;
case "LICENSE": _license = colIdx; break;
}
colIdx++;
}
if (_componentId < 0 || _filePath < 0) {
return null;
}
for (int rowIdx = startRowIdx +1; rowIdx <= sheet.getPhysicalNumberOfRows(); rowIdx++){
Row row = sheet.getRow(rowIdx);
if (row == null) {
continue;
}
ProjectIdentification param = new ProjectIdentification();
param.setComponentId(getCellData(row.getCell(_componentId)));
param.setFilePath(getCellData(row.getCell(_filePath)));
param.setOssName(getCellData(row.getCell(_ossName)));
param.setOssVersion(getCellData(row.getCell(_ossVersion)));
param.setLicenseName(getCellData(row.getCell(_license)));
if (!StringUtil.isEmpty(param.getComponentId())){
result.add(param);
}
}
} catch (IOException ioe) {
log.error(ioe.getMessage(), ioe);
}
}
if ((result != null && !result.isEmpty()) && (ossComponents != null && !ossComponents.isEmpty())) {
List<String> duplicateCheckList = new ArrayList<>();
for (OssComponents oc : ossComponents) {
List<String> licenseNameList = Arrays.asList(oc.getLicenseName().split(","));
Collections.sort(licenseNameList);
String licenseName = String.join(",", licenseNameList);
String key = (oc.getOssName() + "|" + oc.getOssVersion() + "|" + licenseName).toUpperCase();
if (!duplicateCheckList.contains(key)) {
for (ProjectIdentification pi : result) {
List<String> lmList = Arrays.asList(pi.getLicenseName().split(","));
Collections.sort(lmList);
String lm = String.join(",", lmList);
String key2 = (pi.getOssName() + "|" + pi.getOssVersion() + "|" + lm).toUpperCase();
if (key.equals(key2)) {
oc.setFilePath(pi.getFilePath());
duplicateCheckList.add(key);
break;
}
}
}
}
}
return ossComponents;
}
/**
* Read Android Build Image
* @param readType
* @param checkId
* @param targetSheetNums
* @param fileSeq
* @param resultFileSeq
* @param list
* @param errMsg
* @return
*/
public static boolean readAndroidBuildImage(String readType, boolean checkId, String[] targetSheetNums, String fileSeq, String resultFileSeq, List<OssComponents> list, List<String> errMsgList, Map<String, Object> checkHeaderSheetName) {
T2File fileInfo = fileService.selectFileInfoById(fileSeq);
if (fileInfo == null) {
log.error("파일정보를 찾을 수 없습니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("파일 정보를 찾을 수 없습니다.");
return false;
}
if (!Arrays.asList("XLS", "XLSX", "XLSM").contains(avoidNull(fileInfo.getExt()).toUpperCase())) {
log.error("허용하지 않는 파일 입니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("허용하지 않는 파일 입니다.");
return false;
}
File file = new File(fileInfo.getLogiPath() + "/" + fileInfo.getLogiNm());
if (!file.exists() || !file.isFile()) {
log.error("파일정보를 찾을 수 없습니다. fileSeq : " + avoidNull(fileSeq));
errMsgList.add("파일 정보를 찾을 수 없습니다.");
return false;
}
Workbook wb = null;
try {
wb = WorkbookFactory.create(file);
int sheetSeq = 0;
// Son System의 Final List 시트가 선택되어 잇을 경우, 다른 sheet는 무시한다.
for (String sheetIdx : targetSheetNums) {
// get target sheet
Sheet sheet = null;
try {
sheet = wb.getSheetAt(StringUtil.string2integer(sheetIdx));
} catch (Exception e) {
sheetSeq = wb.getSheetIndex(readType);
sheet = wb.getSheetAt(sheetSeq);
}
readAndroidBuildFindHeaderRowIndex(sheet, checkHeaderSheetName);
readAndroidBuildImageSheet(sheet, list, errMsgList);
}
} catch (ColumnNameDuplicateException e) {
log.error("There are duplicated header rows in the OSS Report. Please check it.<br/>" + e.getMessage());
errMsgList.add("There are duplicated header rows in the OSS Report. Please check it.<br/>" + e.getMessage());
return false;
} catch (ColumnMissingException e) {
log.error(e.getMessage());
errMsgList.add(e.getMessage());
return false;
} catch (Exception e) {
log.error("Failed Read Excel File, file seq : " + fileSeq);
log.error(e.getMessage(), e);
errMsgList.add("report 파일에 오류가 있습니다. <br/>" + e.getMessage());
return false;
} finally {
try {
wb.close();
} catch (Exception e2) {}
}
// 사용자 입력 값을 기준으로 OSS Master 정보를 비교 ID를 설정한다.
if (checkId && list != null && !list.isEmpty()) {
// result.txt를 기준으로 삭제 또는 추가
// result text가 있는 경우
// <Removed>로 시작하는 row는 삭제
List<String> removedCheckList = new ArrayList<>(); // 더이상 사용하지 않음, 공통함수에서 사용하지 않도록 처리(CommonFunction.getAndroidResultFileInfo)
List<OssComponents> addCheckList = new ArrayList<>();
List<String> existsResultTextBinaryName = null;
if (!isEmpty(resultFileSeq)) {
List<String> existsBinaryName = new ArrayList<>();
for (OssComponents bean : list) {
if (!isEmpty(bean.getBinaryName())) {
existsBinaryName.add(bean.getBinaryName());
}
}
T2File resultFileInfo = fileService.selectFileInfoById(resultFileSeq);
Map<String, Object> _resultFileInfoMap = CommonFunction.getAndroidResultFileInfo(resultFileInfo, existsBinaryName);
if (_resultFileInfoMap.containsKey("removedCheckList")) {
removedCheckList = (List<String>) _resultFileInfoMap.get("removedCheckList");
}
if (_resultFileInfoMap.containsKey("addCheckList")) {
addCheckList = (List<OssComponents>) _resultFileInfoMap.get("addCheckList");
}
if (_resultFileInfoMap.containsKey("existsResultTextBinaryNameList")) {
existsResultTextBinaryName = (List<String>) _resultFileInfoMap.get("existsResultTextBinaryNameList");
}
}
String addedByResultTxtStr = "";
String deletedByResultTxtStr = "";
String excludeCheckResultTxtStr = "";
// result text에서 추가된 binary
// result.txt에 있으나 OSS Report에 없는 경우 => load되는 OSS List에 해당 Binary를 추가. 팝업을 띄우고 Comment로 추가된 binary목록을 남김.
if (!addCheckList.isEmpty()) {
list.addAll(addCheckList);
addedByResultTxtStr = "<b>The following binaries were added to OSS List automatically because they exist in the fosslight_binary.txt.</b>";
for (OssComponents bean : addCheckList) {
addedByResultTxtStr += "<br> - " + bean.getBinaryName();
}
}
// 더이상 사용하지 않음
if (!removedCheckList.isEmpty()) {
// result list에서 삭제 대상 제외
for (OssComponents bean : list) {
if (removedCheckList.contains(bean.getBinaryName())) {
bean.setExcludeYn(CoConstDef.FLAG_YES);
deletedByResultTxtStr += bean.getBinaryName() + " is excluded by fosslight_binary.txt file.<br>";
}
}
}
// result.txt에 있으나 OSS Report에서 exclude 처리된 경우 => Exclude체크 된 것을 유지. 2번의 Comment내용과 함께 팝업에도 뜨고 Comment로 exclude되어있음을 남김.
if (existsResultTextBinaryName != null) {
boolean isFirst = true;
for (OssComponents bean : list) {
if (existsResultTextBinaryName.contains(bean.getBinaryName()) && CoConstDef.FLAG_YES.equals(bean.getExcludeYn())) {
if (isFirst) {
excludeCheckResultTxtStr = "<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>";
isFirst = false;
}
excludeCheckResultTxtStr += "<br> - " + bean.getBinaryName();
}
}
}
// result.txt에 의해 추가 삭제된 oss의 경우 세션에 격납
// client 화면에 표시 및 save시 코멘트 내용에 추가함
if (!isEmpty(addedByResultTxtStr) || !isEmpty(deletedByResultTxtStr) || !isEmpty(excludeCheckResultTxtStr)) {
String _sessionData = "<b>OSS List has been changed by fosslight_binary.txt file. </b><br><br>";
if (!isEmpty(addedByResultTxtStr)) {
_sessionData += addedByResultTxtStr;
}
if (!isEmpty(deletedByResultTxtStr)) {
if (!isEmpty(_sessionData)) {
_sessionData += "<br><br>";
}
_sessionData += deletedByResultTxtStr;
}
if (!isEmpty(excludeCheckResultTxtStr)) {
if (!isEmpty(_sessionData)) {
_sessionData += "<br><br>";
}
_sessionData += excludeCheckResultTxtStr;
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileSeq), _sessionData);
}
// AutoIdentification 처리중 라이선스명이 사용자설정 명칭(닉네임)이 DB에 등록된 정식명칭등으로 치환되는 내용을 사용자에게 표시하기 위해
// 엑셀 파일의 원본 내용을 보관한다.
List<OssComponents> orgList = new ArrayList<>();
orgList = list;
try {
OssComponentUtil.getInstance().makeOssComponent(list, true);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
log.error(e.getMessage(), e);
deleteSession(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_ANDROID_CHANGED_RESULTTEXT, resultFileSeq));
errMsgList.add("오픈소슨 또는 라이선스 검출시 애러가 발생했습니다." + e.getMessage());
return false;
}
// checkLicenseNameChanged(orgList, list, fileSeq);
}
return true;
}
private static void checkLicenseNameChanged(List<OssComponents> orgList, List<OssComponents> list, String fileSeq) {
Map<String, String> orgLikeMap = new HashMap<>();
List<String> licenseCheckParam = new ArrayList<>();
for (OssComponents bean : orgList) {
if (isEmpty(bean.getOssName())) {
continue;
}
String _key = avoidNull(bean.getOssName()) + "_" + avoidNull(bean.getOssVersion());
if (bean.getOssComponentsLicense() != null) {
for (OssComponentsLicense license : bean.getOssComponentsLicense()) {
if (!isEmpty(license.getLicenseName()) && !licenseCheckParam.contains(license.getLicenseName())) {
licenseCheckParam.add(license.getLicenseName());
}
// bsd-like, mit-like 처리
if (!orgLikeMap.containsKey(_key)
&& !isEmpty(license.getLicenseName())
&& (license.getLicenseName().toUpperCase().startsWith("MIT-LIKE") || license.getLicenseName().toUpperCase().startsWith("BSD-LIKE"))) {
orgLikeMap.put(_key, license.getLicenseName());
}
}
}
}
List<String> licenseNickNameCheckResult = new ArrayList<>();
for (String licenseName : licenseCheckParam) {
if (CoCodeManager.LICENSE_INFO_UPPER.containsKey(licenseName.toUpperCase())) {
LicenseMaster licenseMaster = CoCodeManager.LICENSE_INFO_UPPER.get(licenseName.toUpperCase());
if (licenseMaster.getLicenseNicknameList() != null && !licenseMaster.getLicenseNicknameList().isEmpty()) {
for (String s : licenseMaster.getLicenseNicknameList()) {
String newName = avoidNull(licenseMaster.getShortIdentifier(), licenseMaster.getLicenseName());
if (licenseName.equalsIgnoreCase(s) && !licenseName.equals(newName)) {
String disp = licenseName + " => " + newName;
if (!licenseNickNameCheckResult.contains(disp)) {
licenseNickNameCheckResult.add(disp);
break;
}
}
}
}
}
}
if (!orgLikeMap.isEmpty()) {
Map<String, String> convertLikeMap = new HashMap<>();
// bsd, mit like 계열의 라이선스가 포함되어 있으면, convert된 list에서 like계열의 라이선스 정보를 격납한다.
for (OssComponents bean : list) {
if (isEmpty(bean.getOssName())) {
continue;
}
if (bean.getOssComponentsLicense() != null) {
String _key = avoidNull(bean.getOssName()) + "_" + avoidNull(bean.getOssVersion());
for (OssComponentsLicense license : bean.getOssComponentsLicense()) {
if (!convertLikeMap.containsKey(_key)
&& !isEmpty(license.getLicenseName())
&& (license.getLicenseName().toUpperCase().startsWith("MIT-LIKE") || license.getLicenseName().toUpperCase().startsWith("BSD-LIKE"))) {
convertLikeMap.put(_key, license.getLicenseName());
}
}
}
}
for (String ossKey : orgLikeMap.keySet()) {
if (convertLikeMap.containsKey(ossKey)) {
if (!orgLikeMap.get(ossKey).equals(convertLikeMap.get(ossKey))) {
String disp = orgLikeMap.get(ossKey) + " => " + convertLikeMap.get(ossKey);
if (!licenseNickNameCheckResult.contains(disp)) {
licenseNickNameCheckResult.add(disp);
}
}
}
}
}
if (!licenseNickNameCheckResult.isEmpty()) {
StringBuffer changedNick = new StringBuffer();
changedNick.append("<b>The following license names will be changed to names registered on the system for efficient management.</b><br><br>");
changedNick.append("<b>License Names</b><br>");
for (String s : licenseNickNameCheckResult) {
changedNick.append(s).append("<br>");
}
putSessionObject(CommonFunction.makeSessionKey(loginUserName(), CoConstDef.SESSION_KEY_UPLOAD_REPORT_CHANGEDLICENSE, fileSeq), changedNick.toString());
}
}
public static List<Project> getModelList(MultipartHttpServletRequest req, String localPath) {
List<Project> result = new ArrayList<Project>();
Iterator<String> fileNames = req.getFileNames();
while (fileNames.hasNext()){
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String extType = FilenameUtils.getExtension(fileName);
UUID randomUUID = UUID.randomUUID();
File file = FileUtil.writeFile(multipart, localPath, randomUUID + "." + extType);
Workbook wb = null;
try {
wb = WorkbookFactory.create(file);
int sheetIdx = wb.getSheetIndex("All Model(Software) List");
Sheet sheet = wb.getSheetAt(sheetIdx);
int startRowIdx = findHeaderRowIndex(sheet);
if (startRowIdx < 0) {
log.warn("Can not found Header Row, fileName : " + fileName + " , Sheet Name : " + sheet.getSheetName());
return null;
}
Row headerRow = sheet.getRow(startRowIdx);
Iterator<Cell> iter = headerRow.cellIterator();
int productGroup = -1;
int modelName = -1;
int colIdx = 0;
while (iter.hasNext()) {
Cell cell = (Cell) iter.next();
String value = avoidNull(getCellData(cell)).toUpperCase();
switch (value) {
case "PRODUCT GROUP": productGroup = colIdx; break;
case "MODEL(SOFTWARE) NAME": modelName = colIdx; break;
}
colIdx++;
}
if (modelName < 0) {
return null;
}
for (int rowIdx = startRowIdx +1; rowIdx <= sheet.getPhysicalNumberOfRows(); rowIdx++){
Row row = sheet.getRow(rowIdx);
if (row == null) {
continue;
}
Project param = new Project();
param.setModelName(getCellData(row.getCell(modelName)));
param.setProductGroup(getCellData(row.getCell(productGroup)));
if (!StringUtil.isEmpty(param.getModelName())){
result.add(param);
}
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
return result;
}
public static Map<String, Object> getAnalysisResultList(Map<String, Object> map) {
String analysisResultListPath = (String) map.get("analysisResultListPath");
Map<String, Object> readData = new HashMap<>();
File file = new File(analysisResultListPath);
if (!file.exists()) {
log.error("파일정보를 찾을 수 없습니다. file path : " + analysisResultListPath);
return map;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
String[] fileName = f.getName().split("\\.");
String fileExt = (fileName[fileName.length-1]).toUpperCase();
switch(fileExt) {
case "CSV":
file = f;
break;
default: // 기존 생성되어있던 file은 삭제하지 않고 존재여부만 log로 기록함.
log.debug("File Name : " + f.getName() + " , File Ext : " + fileExt);
break;
}
}
}
try (
FileReader csvFile = new FileReader(file); // CSV File만 가능함.
CSVReader csvReader = new CSVReader(csvFile, '|');
) {
List<String[]> allData = csvReader.readAll();
readData = readAnalysisList(allData, (List<OssAnalysis>) map.get("rows"));
if (!readData.isEmpty()) {
// isValid - false(throws 발생) || true(data 조합)
if ((boolean) readData.get("isValid")) {
CommonFunction.setAnalysisResultList(readData);
readData.put("page", (int) map.get("page"));
readData.put("total", (int) map.get("total"));
readData.put("records", (int) map.get("records"));
} else {
readData.put("rows", new ArrayList<OssAnalysis>());
}
}
} catch(Exception e) {
log.error(e.getMessage());
}
return readData;
}
public static Map<String, Object> readAnalysisList(List<String[]> csvDataList, List<OssAnalysis> analysisList) {
int gridIdCol = -1;
int resultCol = -1;
int ossNameCol = -1;
int nickNameCol = -1;
int ossVersionCol = -1;
int licenseCol = -1;
int concludedLicenseCol = -1;
int askalonoLicenseCol = -1;
int scancodeLicenseCol = -1;
int needReviewLicenseAskalonoCol = -1;
int needReviewLicenseScancodeCol = -1;
int downloadLocationCol = -1;
int homepageCol = -1;
int copyrightTextCol = -1;
int commentCol = -1;
Map<String, Object> result = new HashMap<>();
List<OssAnalysis> analysisResultList = new ArrayList<OssAnalysis>();
int colIdx = 0;
List<String> dupColList = new ArrayList<>();
String[] titleRow = csvDataList.get(0); // titleRow 추출
for (String col : titleRow) {
col = col.toUpperCase().replaceAll("\\,", "");
// 각 컬럼별 colindex 찾기
// 기존 report와 해더 칼럼명 호환 처리가 필요한 경우 여기에 추가
switch (col) {
case "ID":
if (gridIdCol > -1) {
dupColList.add(col);
}
gridIdCol = colIdx;
break;
case "RESULT":
if (resultCol > -1) {
dupColList.add(col);
}
resultCol = colIdx;
break;
case "OSS NAME":
if (ossNameCol > -1) {
dupColList.add(col);
}
ossNameCol = colIdx;
break;
case "NICKNAME":
if (nickNameCol > -1) {
dupColList.add(col);
}
nickNameCol = colIdx;
break;
case "OSS VERSION":
if (ossVersionCol > -1) {
dupColList.add(col);
}
ossVersionCol = colIdx;
break;
case "LICENSE":
if (licenseCol > -1) {
dupColList.add(col);
}
licenseCol = colIdx;
break;
case "CONCLUDED LICENSE":
if (concludedLicenseCol > -1) {
dupColList.add(col);
}
concludedLicenseCol = colIdx;
break;
case "MAIN LICENSE":
if (askalonoLicenseCol > -1) {
dupColList.add(col);
}
askalonoLicenseCol = colIdx;
break;
case "LICENSE(SCANCODE)":
if (scancodeLicenseCol > -1) {
dupColList.add(col);
}
scancodeLicenseCol = colIdx;
break;
case "NEED REVIEW LICENSE(ASKALONO)":
if (needReviewLicenseAskalonoCol > -1) {
dupColList.add(col);
}
needReviewLicenseAskalonoCol = colIdx;
break;
case "NEED REVIEW LICENSE(SCANCODE)":
if (needReviewLicenseScancodeCol > -1) {
dupColList.add(col);
}
needReviewLicenseScancodeCol = colIdx;
break;
case "DOWNLOAD LOCATION":
if (downloadLocationCol > -1) {
dupColList.add(col);
}
downloadLocationCol = colIdx;
break;
case "HOMEPAGE":
if (homepageCol > -1) {
dupColList.add(col);
}
homepageCol = colIdx;
break;
case "COPYRIGHT TEXT":
if (copyrightTextCol > -1) {
dupColList.add(col);
}
copyrightTextCol = colIdx;
break;
case "COMMENT":
if (commentCol > -1) {
dupColList.add(col);
}
commentCol = colIdx;
break;
default:
break;
}
colIdx++;
}
// header 중복 체크
if (!dupColList.isEmpty()) {
String msg = dupColList.toString();
msg = "There are duplicated. Filed Name : ".concat(msg);
result.put("isValid", false);
result.put("errorMsg", msg);
return result;
}
// 필수 header 누락 시 Exception
List<String> colNames = new ArrayList<String>();
if (ossNameCol < 0) {
colNames.add("OSS NAME");
}
if (ossVersionCol < 0) {
colNames.add("OSS VERSION");
}
if (licenseCol < 0) {
colNames.add("LICENSE");
}
if (!colNames.isEmpty()) {
String msg = colNames.toString();
msg = "Column Name Empty : ".concat(msg);
result.put("isValid", false);
result.put("errorMsg", msg);
return result;
}
List<String> errRow = new ArrayList<>();
List<String> analysisListIds = new ArrayList<String>();
for (OssAnalysis analysisBean : analysisList) {
analysisListIds.add(analysisBean.getGridId());
}
int rowSeq = 0;
for (String[] row : csvDataList) {
try {
if (rowSeq < 2) {
rowSeq++;
continue;
}
OssAnalysis bean = new OssAnalysis();
// 기본정보
String gridId = gridIdCol < 0 ? "" : avoidNull(row[gridIdCol]).trim().replaceAll("\t", "");
int checkLength = analysisListIds.stream().filter(a -> a.equals(gridId)).collect(Collectors.toList()).size();
if (checkLength == 1) {
bean.setGridId(gridId);
bean.setResult(resultCol < 0 ? "" : avoidNull(row[resultCol]).trim().replaceAll("\t", ""));
bean.setOssName(ossNameCol < 0 ? "" : avoidNull(row[ossNameCol]).trim().replaceAll("\t", ""));
bean.setOssNickname(nickNameCol < 0 ? "" : row[nickNameCol]);
bean.setOssVersion(ossVersionCol < 0 ? "" : avoidNull(row[ossVersionCol]).trim().replaceAll("\t", ""));
bean.setLicenseName(licenseCol < 0 ? "" : avoidNull(row[licenseCol]).trim().replaceAll("\t", ""));
bean.setConcludedLicense(concludedLicenseCol < 0 ? "" : avoidNull(row[concludedLicenseCol]).trim().replaceAll("\t", ""));
bean.setAskalonoLicense(askalonoLicenseCol < 0 ? "" : avoidNull(row[askalonoLicenseCol]).trim().replaceAll("\t", ""));
bean.setScancodeLicense(scancodeLicenseCol < 0 ? "" : avoidNull(row[scancodeLicenseCol]).trim().replaceAll("\t", ""));
bean.setNeedReviewLicenseAskalono(needReviewLicenseAskalonoCol < 0 ? "" : avoidNull(row[needReviewLicenseAskalonoCol]).trim().replaceAll("\t", ""));
bean.setNeedReviewLicenseScanode(needReviewLicenseScancodeCol < 0 ? "" : avoidNull(row[needReviewLicenseScancodeCol]).trim().replaceAll("\t", ""));
bean.setDownloadLocation(downloadLocationCol < 0 ? "" : avoidNull(row[downloadLocationCol]).trim().replaceAll("\t", ""));
bean.setHomepage(homepageCol < 0 ? "" : avoidNull(row[homepageCol]).trim().replaceAll("\t", ""));
bean.setOssCopyright(copyrightTextCol < 0 ? "" : avoidNull(row[copyrightTextCol]).trim().replaceAll("\t", ""));
bean.setComment(commentCol < 0 ? "" : avoidNull(row[commentCol]).trim().replaceAll("\\,", "").replaceAll("\t", ""));
analysisResultList.add(bean);
}
} catch (Exception e) {
errRow.add("Row : " + String.valueOf(rowSeq) + ", Message : " + e.getMessage());
}
}
if (!errRow.isEmpty()) {
String msg = errRow.toString();
msg = "Error Row : ".concat(msg);
result.put("isValid", false);
result.put("errorMsg", msg);
return result;
}
if (analysisResultList.isEmpty()) {
result.put("isValid", false);
result.put("errorMsg", "empty Row");
return result;
}
result.put("isValid", true);
result.put("rows", analysisResultList); // analysisResultList
result.put("analysisList", analysisList);
return result;
}
public static OssMaster getOssDataByColumn(Iterator<Cell> cellIterator) {
OssMaster ossMaster = new OssMaster();
int colIndex = 0;
int nullCol = 0;
for (; cellIterator.hasNext(); colIndex++) {
Cell cell = (Cell) cellIterator.next();
String value = getCellData(cell);
if (value == null || value.trim().isEmpty()) {
nullCol++;
continue;
}
if (colIndex == 0) {
ossMaster.setOssName(value);
} else if (colIndex == 1) {
String[] nicknames = StringUtil.delimitedStringToStringArray(value, ",");
ossMaster.setOssNicknames(nicknames);
} else if (colIndex == 2) {
ossMaster.setOssVersion(value);
} else if (colIndex == 3) {
ossMaster.setDeclaredLicense(value);
} else if (colIndex == 4) {
ossMaster.setDetectedLicense(value);
} else if (colIndex == 5) {
ossMaster.setCopyright(value);
ossMaster.setOssCopyright(value);
} else if (colIndex == 6) {
String homepage = value.replaceAll("(\r\n|\r|\n|\n\r)", "");
ossMaster.setHomepage(homepage);
} else if (colIndex == 7) {
String location = value.replaceAll("(\r\n|\r|\n|\n\r)", "");
ossMaster.setDownloadLocation(location);
} else if (colIndex == 8) {
ossMaster.setSummaryDescription(value);
} else if (colIndex == 9) {
ossMaster.setAttribution(value);
} else if (colIndex == 10) {
ossMaster.setComment(value);
}
}
if (nullCol == 11) {
return null;
}
return ossMaster;
}
public static boolean checkHeaderColumnValidate(Iterator<Cell> cellIterator) {
String[] definedColData = new String[] {"OSS NAME", "NICKNAME", "VERSION", "DECLARED LICENSE", "DETECTED LICENSE", "COPYRIGHT", "HOMEPAGE",
"DOWNLOAD URL", "SUMMARY DESCRIPTION", "ATTRIBUTION", "COMMENT"};
boolean allColumnsExist = true;
List<String> firstRowColData = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
firstRowColData.add(getCellData(cell));
}
for (int cIdx = 0; cIdx < definedColData.length; cIdx++) {
String colData = firstRowColData.get(cIdx);
if (colData != null && definedColData[cIdx].equals(colData.toUpperCase())){
continue;
} else {
allColumnsExist = false;
break;
}
}
return allColumnsExist;
}
public static List<OssMaster> readOssList(MultipartHttpServletRequest req, String excelLocalPath) throws InvalidFormatException, IOException {
Iterator<String> fileNames = req.getFileNames();
List<OssMaster> ossMasterList = new ArrayList<>();
while (fileNames.hasNext()) {
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String[] fileNameArray = StringUtil.split(fileName, File.separator);
fileName = fileNameArray[fileNameArray.length - 1];
File file = new File( "."+excelLocalPath +fileName);
FileUtil.transferTo(multipart, file);
HSSFWorkbook wbHSSF = null;
XSSFWorkbook wbXSSF = null;
String[] ext = StringUtil.split(fileName, ".");
String extType = ext[ext.length - 1];
String codeExt[] = StringUtil.split(codeMapper.selectExtType("11"), ","); // The codeExt array contains the allowed extension types.
int count = 0;
for (int i = 0; i < codeExt.length; i++) {
if (codeExt[i].equalsIgnoreCase(extType)) {
count++;
}
}
if (count != 1) {
return null;
} else if ("xls".equals(extType) || "XLS".equals(extType)) {
try {
wbHSSF = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = wbHSSF.getSheetAt(0);
int rowSize = sheet.getPhysicalNumberOfRows();
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
HSSFRow row = sheet.getRow(rowIndex);
if (rowIndex == 0) {
boolean validHeader = checkHeaderColumnValidate(row.cellIterator());
if (!validHeader){
log.info("The order and content of header columns must match.");
return null;
}
} else {
OssMaster ossMaster = getOssDataByColumn(row.cellIterator());
if (ossMaster != null) {
ossMasterList.add(ossMaster);
}
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbHSSF.close();
} catch (Exception e) {
}
}
} else if ("xlsx".equals(extType) || "XLSX".equals(extType)) {
try {
wbXSSF = new XSSFWorkbook(new FileInputStream(file));
XSSFSheet sheet = wbXSSF.getSheetAt(0);
int rowSize = sheet.getPhysicalNumberOfRows();
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (rowIndex == 0) {
boolean validHeader = checkHeaderColumnValidate(row.cellIterator());
if (!validHeader) {
log.info("The order and content of header columns must match.");
return null;
}
} else {
OssMaster ossMaster = getOssDataByColumn(row.cellIterator());
if (ossMaster != null) {
ossMasterList.add(ossMaster);
}
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbXSSF.close();
} catch (Exception e2) {
}
}
}
}
return ossMasterList;
}
/**Excel 헤더 체크*/
public static boolean checkHeaderLicenseColumnValidate(Iterator<Cell> cellIterator, Map<Integer, String> columnCheckMap) {
List<String> definedColData = Arrays.asList(new String[] {"LICENSE NAME", "LICENSE TYPE", "NOTICE", "SOURCE CODE",
"SPDX SHORT IDENTIFIER", "NICKNAME", "WEBSITE FOR THE LICENSE",
"USER GUIDE", "LICENSE TEXT", "ATTRIBUTION", "COMMENT"});
List<String> firstRowColData = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
firstRowColData.add(getCellData(cell));
}
int validationCnt = 0;
for (int cIdx = 0; cIdx < firstRowColData.size(); cIdx++) {
String colData = firstRowColData.get(cIdx);
if (colData != null && definedColData.contains(colData.toUpperCase())){
validationCnt++;
columnCheckMap.put(cIdx, colData.toUpperCase());
}
}
return validationCnt > 0 ? true : false;
}
/**make Grid data to return UI*/
public static List<LicenseMaster> readLicenseList(MultipartHttpServletRequest req, String excelLocalPath) throws InvalidFormatException, IOException {
Iterator<String> fileNames = req.getFileNames();
List<LicenseMaster> licenseMasterList = new ArrayList<>();
while (fileNames.hasNext()) {
MultipartFile multipart = req.getFile(fileNames.next());
String fileName = multipart.getOriginalFilename();
String[] fileNameArray = StringUtil.split(fileName, File.separator);
fileName = fileNameArray[fileNameArray.length - 1];
File file = new File( "."+excelLocalPath +fileName);
FileUtil.transferTo(multipart, file);
HSSFWorkbook wbHSSF = null;
XSSFWorkbook wbXSSF = null;
String[] ext = StringUtil.split(fileName, ".");
String extType = ext[ext.length - 1];
String codeExt[] = StringUtil.split(codeMapper.selectExtType("11"), ","); // The codeExt array contains the allowed extension types.
int count = 0;
Map<Integer, String> columnCheckMap = new HashMap<>();
for (int i = 0; i < codeExt.length; i++) {
if (codeExt[i].equalsIgnoreCase(extType)) {
count++;
}
}
if (count != 1) {
return null;
} else if ("xls".equals(extType) || "XLS".equals(extType)) {
try {
wbHSSF = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = wbHSSF.getSheetAt(0);
int rowSize = sheet.getPhysicalNumberOfRows();
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
HSSFRow row = sheet.getRow(rowIndex);
if (rowIndex == 0) {
//check header in here
boolean validHeader = checkHeaderLicenseColumnValidate(row.cellIterator(), columnCheckMap);
if (!validHeader){
log.info("The order and content of header columns must match.");
return null;
}
} else {
short firstCell = row.getFirstCellNum();
short lastCell = row.getLastCellNum();
for (short cellIdx = firstCell; cellIdx <= lastCell; cellIdx++) {
HSSFCell cell = row.getCell(cellIdx);
if (cell == null) {
row.createCell(cellIdx);
}
}
LicenseMaster licenseMaster = getLicenseDataByColumn(row.cellIterator(), columnCheckMap);
if (licenseMaster != null) {
licenseMasterList.add(licenseMaster);
}
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbHSSF.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} else if ("xlsx".equals(extType) || "XLSX".equals(extType)) {
try {
wbXSSF = new XSSFWorkbook(new FileInputStream(file));
XSSFSheet sheet = wbXSSF.getSheetAt(0);
int rowSize = sheet.getPhysicalNumberOfRows();
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (rowIndex == 0) {
boolean validHeader = checkHeaderLicenseColumnValidate(row.cellIterator(), columnCheckMap);
if (!validHeader) {
log.info("The order and content of header columns must match.");
return null;
}
} else {
short firstCell = row.getFirstCellNum();
short lastCell = row.getLastCellNum();
for (short cellIdx = firstCell; cellIdx <= lastCell; cellIdx++) {
XSSFCell cell = row.getCell(cellIdx);
if (cell == null) {
row.createCell(cellIdx);
}
}
//licenseMaster Object
LicenseMaster licenseMaster = getLicenseDataByColumn(row.cellIterator(), columnCheckMap);
if (licenseMaster != null) {
licenseMasterList.add(licenseMaster);
}
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
wbXSSF.close();
} catch (Exception e2) {
log.error(e2.getMessage(), e2);
}
}
}
}
return licenseMasterList;
}
public static LicenseMaster getLicenseDataByColumn(Iterator<Cell> cellIterator, Map<Integer, String> columnCheckMap) {
LicenseMaster licenseMaster = new LicenseMaster();
int colIndex = 0;
Integer maxKey = Collections.max(columnCheckMap.keySet());
for (; cellIterator.hasNext(); colIndex++) {
if (colIndex > maxKey) break;
if (!columnCheckMap.containsKey(colIndex)) {
cellIterator.next();
continue;
} else {
String columnName = columnCheckMap.get(colIndex);
Cell cell = (Cell) cellIterator.next();
String value = getCellData(cell);
switch (columnName) {
case "LICENSE NAME" :
if (value == null || value.trim().isEmpty()) {
log.debug("License Name must not be null.");
return null;
} else {
licenseMaster.setLicenseName(value);
}
break;
case "LICENSE TYPE" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setLicenseType(value);
break;
case "NOTICE" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setObligationNotificationYn(value);
break;
case "SOURCE CODE" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setObligationDisclosingSrcYn(value);
break;
case "SPDX SHORT IDENTIFIER" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setShortIdentifier(value);
break;
case "NICKNAME" :
if (value == null || value.trim().isEmpty()) {
continue;
}
String[] nicknames = StringUtil.delimitedStringToStringArray(value, ",");
licenseMaster.setLicenseNicknames(nicknames);
break;
case "WEBSITE FOR THE LICENSE" :
if (value == null || value.trim().isEmpty()) {
continue;
}
String[] webpages = StringUtil.delimitedStringToStringArray(value, ",");
Arrays.stream(webpages).forEach((webpage)->{
webpage.replaceAll("(\r\n|\r|\n|\n\r)", "");
});
licenseMaster.setWebpages(webpages);
break;
case "USER GUIDE" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setDescription(value);
break;
case "LICENSE TEXT" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setLicenseText(value);
break;
case "ATTRIBUTION" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setAttribution(value);
break;
case "COMMENT" :
if (value == null || value.trim().isEmpty()) {
continue;
}
licenseMaster.setComment(value);
break;
}
}
}
return licenseMaster;
}
private static void readAndroidBuildFindHeaderRowIndex(Sheet sheet, Map<String, Object> checkHeaderSheetName) {
int DefaultHeaderRowIndex = 2; // default header index
DefaultHeaderRowIndex = findHeaderRowIndex(sheet);
if (DefaultHeaderRowIndex > -1) {
Row row = sheet.getRow(DefaultHeaderRowIndex);
int binaryNameCnt = 0;
int sourceCodePathCnt = 0;
int ossNameCnt = 0;
int ossVersionCnt = 0;
int licenseNameCnt = 0;
for (Cell cell : row) {
String header = avoidNull(getCellData(cell)).trim().toUpperCase();
switch(header) {
case "BINARY/LIBRARY FILE":
case "BINARY NAME": binaryNameCnt++;
break;
case "DIRECTORY":
case "SOURCE CODE PATH": sourceCodePathCnt++;
break;
case "OSS COMPONENT":
case "OSS NAME": ossNameCnt++;
break;
case "OSS VERSION": ossVersionCnt++;
break;
case "LICENSE": licenseNameCnt++;
break;
default:break;
}
}
if (binaryNameCnt == 0 || sourceCodePathCnt == 0 || ossNameCnt == 0 || ossVersionCnt == 0 || licenseNameCnt == 0) {
if (checkHeaderSheetName.containsKey("checkHeaderSheetName")) {
String orgSheetName = (String) checkHeaderSheetName.get("checkHeaderSheetName");
checkHeaderSheetName.put("checkHeaderSheetName", orgSheetName + ", " + sheet.getSheetName());
} else {
checkHeaderSheetName.put("checkHeaderSheetName", sheet.getSheetName());
}
}
}
}
public static Map<String, Object> getCsvData(Map<String, Object> map, OssMaster ossMaster) {
String analysisResultListPath = (String) map.get("analysisResultListPath");
File file = new File(analysisResultListPath);
if (!file.exists()) {
log.error("파일정보를 찾을 수 없습니다. file path : " + analysisResultListPath);
map.clear();
return map;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
String[] fileName = f.getName().split("\\.");
String fileExt = (fileName[fileName.length-1]).toUpperCase();
switch(fileExt) {
case "CSV":
file = f;
break;
default: // 기존 생성되어있던 file은 삭제하지 않고 존재여부만 log로 기록함.
log.debug("File Name : " + f.getName() + " , File Ext : " + fileExt);
break;
}
}
}
try (
FileReader csvFile = new FileReader(file); // CSV File만 가능함.
CSVReader csvReader = new CSVReader(csvFile, '|');
) {
List<String[]> allData = csvReader.readAll();
if (allData != null) {
map.put("csvData", allData);
List<Integer> componentIdsForCsvData = new ArrayList<>();
String componentId = "";
int idx = 0;
for (String[] csvArr : allData) {
if (idx < 2) {
idx++;
continue;
}
componentId = csvArr[0].trim().replaceAll("\t", "");
componentIdsForCsvData.add(Integer.parseInt(componentId));
}
if (componentIdsForCsvData.size() > 0) {
int[] csvComponentIdList = componentIdsForCsvData.stream().mapToInt(Integer::intValue).toArray();
ossMaster.setCsvComponentIdList(csvComponentIdList);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return map;
}
}
| 113,174 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
JwtUtil.java | /FileExtraction/Java_unseen/fosslight_fosslight/src/main/java/oss/fosslight/util/JwtUtil.java | /*
* Copyright (c) 2021 LG Electronics Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
package oss.fosslight.util;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
public class JwtUtil {
private Key key;
public JwtUtil(String secret){
this.key = Keys.hmacShaKeyFor(secret.getBytes());
}
public String createToken(String id, String email) {
String token = Jwts.builder()
.claim("userId", id)
.claim("email", email)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
return token;
}
}
| 711 | Java | .java | fosslight/fosslight | 172 | 114 | 89 | 2021-04-29T09:49:47Z | 2024-05-09T06:51:21Z |
ClientProxy.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/ClientProxy.java | package igwmod;
import igwmod.api.WikiRegistry;
import igwmod.gui.GuiWiki;
import igwmod.gui.tabs.BlockAndItemWikiTab;
import igwmod.gui.tabs.EntityWikiTab;
import igwmod.gui.tabs.IGWWikiTab;
import igwmod.lib.Constants;
import igwmod.lib.IGWLog;
import igwmod.lib.Paths;
import igwmod.recipeintegration.IntegratorComment;
import igwmod.recipeintegration.IntegratorCraftingRecipe;
import igwmod.recipeintegration.IntegratorFurnace;
import igwmod.recipeintegration.IntegratorImage;
import igwmod.recipeintegration.IntegratorStack;
import igwmod.render.TooltipOverlayHandler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.registries.IForgeRegistry;
import org.lwjgl.input.Keyboard;
public class ClientProxy implements IProxy{
public static KeyBinding openInterfaceKey;
@Override
public void preInit(FMLPreInitializationEvent event){
MinecraftForge.EVENT_BUS.register(new TickHandler());
MinecraftForge.EVENT_BUS.register(new TooltipOverlayHandler());
//Not being used, as it doesn't really add anything...
// MinecraftForge.EVENT_BUS.register(new HighlightHandler());
openInterfaceKey = new KeyBinding("igwmod.keys.wiki", Constants.DEFAULT_KEYBIND_OPEN_GUI, "igwmod.keys.category");//TODO blend keybinding category in normal
ClientRegistry.registerKeyBinding(openInterfaceKey);
MinecraftForge.EVENT_BUS.register(this);//subscribe to key events.
ConfigHandler.init(event.getSuggestedConfigurationFile());
WikiRegistry.registerWikiTab(new IGWWikiTab());
WikiRegistry.registerWikiTab(new BlockAndItemWikiTab());
WikiRegistry.registerWikiTab(new EntityWikiTab());
WikiRegistry.registerRecipeIntegrator(new IntegratorImage());
WikiRegistry.registerRecipeIntegrator(new IntegratorCraftingRecipe());
WikiRegistry.registerRecipeIntegrator(new IntegratorFurnace());
WikiRegistry.registerRecipeIntegrator(new IntegratorStack());
WikiRegistry.registerRecipeIntegrator(new IntegratorComment());
}
@SubscribeEvent
public void onKeyBind(KeyInputEvent event){
if(openInterfaceKey.isPressed()) {
if(FMLClientHandler.instance().getClient().inGameHasFocus) {
TickHandler.openWikiGui();
} else {
// handleSlotPresses();
}
}
}
@SubscribeEvent
public void onGuiKeyBind(GuiScreenEvent.KeyboardInputEvent.Post event){
char chr = Keyboard.getEventCharacter();
int key = Keyboard.getEventKey();
if(((key == 0 && chr >= 32) || Keyboard.getEventKeyState()) && key == openInterfaceKey.getKeyCode()) {
handleSlotPresses();
}
}
private void handleSlotPresses(){
GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen;
if(guiScreen instanceof GuiContainer) {
GuiContainer guiContainer = (GuiContainer)guiScreen;
Slot slot = guiContainer.getSlotUnderMouse();
if(slot != null) {
ItemStack stack = slot.getStack();
if(!stack.isEmpty()) {
GuiWiki gui = new GuiWiki();
FMLCommonHandler.instance().showGuiScreen(gui);
gui.setCurrentFile(stack);
}
}
}
}
@Override
public void postInit(){
addDefaultKeys();
}
private void addDefaultKeys(){
//Register all basic items that have (default) pages to the item and blocks page.
// List<ItemStack> stackList = new ArrayList<ItemStack>();
NonNullList<ItemStack> allCreativeStacks = NonNullList.<ItemStack> create();
IForgeRegistry<Item> itemReg = GameRegistry.findRegistry(Item.class);
for(Item item : itemReg) {
if(item != null && item.getCreativeTab() != null) {
try {
item.getSubItems(CreativeTabs.SEARCH, allCreativeStacks);
} catch(Throwable e) {
e.printStackTrace();
}
}
}
for(ItemStack stack : allCreativeStacks) {
if(!stack.isEmpty() && stack.getItem() != null && Item.REGISTRY.getNameForObject(stack.getItem()) != null) {
String modid = Paths.MOD_ID.toLowerCase();
ResourceLocation id = Item.REGISTRY.getNameForObject(stack.getItem());
if(id != null && id.getResourceDomain() != null) modid = id.getResourceDomain().toLowerCase();
if(stack.getUnlocalizedName() != null) {
List<String> info = InfoSupplier.getInfo(modid, WikiUtils.getNameFromStack(stack), true);
if(info != null) WikiRegistry.registerBlockAndItemPageEntry(stack);
}
}
}
//Register all entities that have (default) pages to the entity page.
for(ResourceLocation entry : EntityList.getEntityNameList()) {
String modid = entry.getResourceDomain(); //Util.getModIdForEntity(entry.());
if(InfoSupplier.getInfo(modid, "entity/" + entry.getResourcePath(), true) != null) WikiRegistry.registerEntityPageEntry(EntityList.getClass(entry));
}
//Add automatically generated crafting recipe key mappings.
for(IRecipe recipe : GameRegistry.findRegistry(IRecipe.class)) {
if(recipe.getRecipeOutput() != null && recipe.getRecipeOutput().getItem() != null) {
try {
if(recipe.getRecipeOutput().getUnlocalizedName() == null) {
IGWLog.error("Item has no unlocalized name: " + recipe.getRecipeOutput().getItem());
} else {
String blockCode = WikiUtils.getNameFromStack(recipe.getRecipeOutput());
if(!IntegratorCraftingRecipe.autoMappedRecipes.containsKey(blockCode)) IntegratorCraftingRecipe.autoMappedRecipes.put(blockCode, recipe);
}
} catch(Throwable e) {
IGWLog.error("IGW-Mod failed to add recipe handling support for " + recipe.getRecipeOutput());
e.printStackTrace();
}
}
}
//Add automatically generated furnace recipe key mappings.
for(Map.Entry<ItemStack, ItemStack> entry : FurnaceRecipes.instance().getSmeltingList().entrySet()) {
if(entry.getValue() != null && entry.getValue().getItem() != null) {
String blockCode = WikiUtils.getNameFromStack(entry.getValue());
if(!IntegratorFurnace.autoMappedFurnaceRecipes.containsKey(blockCode)) IntegratorFurnace.autoMappedFurnaceRecipes.put(blockCode, entry.getKey());
}
}
IGWLog.info("Registered " + WikiRegistry.getItemAndBlockPageEntries().size() + " Block & Item page entries.");
IGWLog.info("Registered " + WikiRegistry.getEntityPageEntries().size() + " Entity page entries.");
}
@Override
public void processIMC(IMCEvent event){
List<FMLInterModComms.IMCMessage> messages = event.getMessages();
for(FMLInterModComms.IMCMessage message : messages) {
try {
Class clazz = Class.forName(message.key);
try {
Method method = clazz.getMethod(message.getStringValue());
if(method == null) {
IGWLog.error("Couldn't find the \"" + message.key + "\" method. Make sure it's there and marked with the 'static' modifier!");
} else {
try {
method.invoke(null);
IGWLog.info("Successfully gave " + message.getSender() + " a nudge! Happy to be doing business!");
} catch(IllegalAccessException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the method can NOT be accessed: " + message.getStringValue());
} catch(IllegalArgumentException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the method has arguments or it isn't static: " + message.getStringValue());
} catch(InvocationTargetException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the method threw an exception: " + message.getStringValue());
e.printStackTrace();
}
}
} catch(NoSuchMethodException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the method can NOT be found: " + message.getStringValue());
} catch(SecurityException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the method can NOT be accessed: " + message.getStringValue());
}
} catch(ClassNotFoundException e) {
IGWLog.error(message.getSender() + " tried to register to IGW. Failed because the class can NOT be found: " + message.key);
}
}
}
@Override
public String getSaveLocation(){
try {
return Minecraft.getMinecraft().mcDataDir.getCanonicalPath();
} catch(IOException e) {
e.printStackTrace();
String mcDataLocation = Minecraft.getMinecraft().mcDataDir.getAbsolutePath();
return mcDataLocation.substring(0, mcDataLocation.length() - 2);
}
}
@Override
public EntityPlayer getPlayer(){
return Minecraft.getMinecraft().player;
}
}
| 11,139 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IProxy.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/IProxy.java | package igwmod;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
public interface IProxy{
public void preInit(FMLPreInitializationEvent event);
public void postInit();
public void processIMC(FMLInterModComms.IMCEvent event);
public String getSaveLocation();
public EntityPlayer getPlayer();
}
| 450 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ConfigHandler.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/ConfigHandler.java | package igwmod;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
public class ConfigHandler{
public static boolean shouldShowTooltip;
public static boolean debugMode;
private static Configuration conf;
public static void init(File configFile){
conf = new Configuration(configFile);
conf.load();
shouldShowTooltip = conf.get(Configuration.CATEGORY_GENERAL, "Should show tooltip", true).getBoolean(true);
debugMode = conf.get(Configuration.CATEGORY_GENERAL, "Debug mode", false).getBoolean(false);
conf.save();
}
public static void disableTooltip(){
conf.load();
conf.get(Configuration.CATEGORY_GENERAL, "Should show tooltip", true).set(false);
shouldShowTooltip = false;
conf.save();
}
}
| 820 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
WikiUtils.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/WikiUtils.java | package igwmod;
import java.util.HashMap;
import java.util.Iterator;
import igwmod.lib.IGWLog;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
public class WikiUtils{
private static HashMap<String, ItemStack> unlocMap;
public static ItemStack getStackFromName(String name){
if(unlocMap == null) {
unlocMap = new HashMap<String, ItemStack>();
// List<ItemStack> stackList = new ArrayList<ItemStack>();
NonNullList<ItemStack> stackList = NonNullList.<ItemStack> create();
Iterator iterator = Item.REGISTRY.iterator();
while(iterator.hasNext()) {
Item item = (Item)iterator.next();
if(item != null && item.getCreativeTab() != null) {
item.getSubItems(CreativeTabs.SEARCH, stackList);
}
}
for(ItemStack stack : stackList) {
if(stack.getItem() == null) continue;
String itemName = stack.getUnlocalizedName().replace("tile.", "block/").replace("item.", "item/");//TODO improve
unlocMap.put(itemName, stack);
unlocMap.put(getOwningModId(stack) + ":" + itemName, stack);
}
}
String[] splitName = name.contains("#") ? name.split("#") : new String[]{name};
ItemStack stack = unlocMap.getOrDefault(splitName[0], ItemStack.EMPTY);
if(!stack.isEmpty()) {
stack = stack.copy();
// if(splitName.length > 1) stack.stackSize = Integer.parseInt(splitName[1]);
if(splitName.length > 1) stack.setCount(Integer.parseInt(splitName[1]));
return stack;
} else {
return ItemStack.EMPTY;
}
}
public static String getNameFromStack(ItemStack stack){
return stack.getUnlocalizedName().replace("tile.", "block/").replace("item.", "item/");
}
public static String getOwningModId(ItemStack stack){
String modid = "minecraft";
if(stack.getItem() == null) {
IGWLog.warning("Found an ItemStack with a null item! This isn't supposed to happen!");
} else {
ResourceLocation id = Item.REGISTRY.getNameForObject(stack.getItem());
if(id != null && id.getResourceDomain() != null) modid = id.getResourceDomain().toLowerCase();
}
return modid;
}
}
| 2,532 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
WikiHooks.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/WikiHooks.java | package igwmod;
import igwmod.api.IWikiHooks;
import igwmod.gui.GuiWiki;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.FMLClientHandler;
public class WikiHooks implements IWikiHooks{
@Override
public void showWikiGui(String pageLocation){
GuiScreen gui = FMLClientHandler.instance().getClient().currentScreen;
GuiWiki guiWiki = new GuiWiki();
FMLClientHandler.instance().showGuiScreen(guiWiki);
guiWiki.setCurrentFile(pageLocation);
guiWiki.setPreviousScreen(gui);
}
}
| 560 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
TickHandler.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/TickHandler.java | package igwmod;
import igwmod.gui.GuiWiki;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class TickHandler{
private static int ticksHovered;
private static Entity lastEntityHovered;
private static BlockPos coordHovered;
public static int ticksExisted;
private static final int MIN_TICKS_HOVER = 50;
@SubscribeEvent
public void tick(TickEvent.PlayerTickEvent event){
if(event.phase == TickEvent.Phase.END) {
EntityPlayer player = event.player;
if(player == FMLClientHandler.instance().getClient().player) {
ticksExisted++;
RayTraceResult lookedObject = FMLClientHandler.instance().getClient().objectMouseOver;
if(lookedObject != null) {
if(lookedObject.typeOfHit == RayTraceResult.Type.ENTITY) {
if(lastEntityHovered == lookedObject.entityHit) {
ticksHovered++;
coordHovered = null;
} else {
lastEntityHovered = lookedObject.entityHit;
ticksHovered = 0;
coordHovered = null;
}
} else if(lookedObject.getBlockPos() != null) {
if(coordHovered != null && lookedObject.getBlockPos().equals(new BlockPos(coordHovered))) {
ticksHovered++;
lastEntityHovered = null;
} else {
if(!event.player.world.isAirBlock(lookedObject.getBlockPos())) {
ticksHovered = 0;
lastEntityHovered = null;
coordHovered = lookedObject.getBlockPos();
}
}
}
}
}
}
}
public static boolean showTooltip(){
return ticksHovered > MIN_TICKS_HOVER;
}
public static void openWikiGui(){
// if(showTooltip()) {
ConfigHandler.disableTooltip();
if(lastEntityHovered != null) {
GuiWiki gui = new GuiWiki();
FMLCommonHandler.instance().showGuiScreen(gui);
gui.setCurrentFile(lastEntityHovered);
} else if(coordHovered != null) {
World world = FMLClientHandler.instance().getClient().world;
if(world != null) {
if(!world.isAirBlock(coordHovered)) {
GuiWiki gui = new GuiWiki();
FMLCommonHandler.instance().showGuiScreen(gui);
gui.setCurrentFile(world, coordHovered);
}
}
} else {
FMLCommonHandler.instance().showGuiScreen(new GuiWiki());
}
}
public static String getCurrentObjectName(){
if(lastEntityHovered != null) {
return lastEntityHovered.getName();
} else {
try {
World world = FMLClientHandler.instance().getClient().world;
IBlockState blockState = world.getBlockState(coordHovered);
if(blockState != null) {
ItemStack idPicked = blockState.getBlock().getPickBlock(blockState, FMLClientHandler.instance().getClient().objectMouseOver, world, coordHovered, FMLClientHandler.instance().getClientPlayerEntity());
return (!idPicked.isEmpty() ? idPicked : new ItemStack(blockState.getBlock(), 1, blockState.getBlock().getMetaFromState(blockState))).getDisplayName(); //TODO test blockState.getBlock().getDamage()
}
} catch(Throwable e) {}
return TextFormatting.RED + "<ERROR>";
}
}
}
| 4,309 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
VariableHandler.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/VariableHandler.java | package igwmod;
import igwmod.api.VariableRetrievalEvent;
import net.minecraftforge.common.MinecraftForge;
public class VariableHandler{
public static String getVariable(String varName){
VariableRetrievalEvent event = new VariableRetrievalEvent(varName);
MinecraftForge.EVENT_BUS.post(event);
return event.replacementValue != null ? event.replacementValue : varName;
}
}
| 406 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
TextureSupplier.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/TextureSupplier.java | package igwmod;
import java.util.HashMap;
import net.minecraft.util.ResourceLocation;
public class TextureSupplier{
private static HashMap<String, ResourceLocation> textureMap = new HashMap<String, ResourceLocation>();
public static ResourceLocation getTexture(String objectName){
if(!textureMap.containsKey(objectName)) {
textureMap.put(objectName, new ResourceLocation(objectName));
}
return textureMap.get(objectName);
}
}
| 479 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IGWMod.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/IGWMod.java | package igwmod;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import igwmod.lib.Constants;
import igwmod.network.NetworkHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkCheckHandler;
import net.minecraftforge.fml.relauncher.Side;
@Mod(modid = Constants.MOD_ID, name = "In-Game Wiki Mod")
public class IGWMod{
@SidedProxy(clientSide = "igwmod.ClientProxy", serverSide = "igwmod.ServerProxy")
public static IProxy proxy;
@Instance(Constants.MOD_ID)
public IGWMod instance;
/**
* This method is used to reject connection when the server has server info available for IGW-mod. Unless the properties.txt explicitly says
* it's okay to connect without IGW-Mod, by setting "optional=true".
* @param installedMods
* @param side
* @return
*/
@NetworkCheckHandler
public boolean onConnectRequest(Map<String, String> installedMods, Side side){
if(side == Side.SERVER || proxy == null) return true;
File serverFolder = new File(proxy.getSaveLocation() + File.separator + "igwmod" + File.separator);
if(serverFolder.exists() || new File(proxy.getSaveLocation() + File.separator + "igwmodServer" + File.separator).exists()) {//TODO remove legacy
String str = proxy.getSaveLocation() + File.separator + "igwmod" + File.separator + "properties.txt";
File file = new File(str);
if(!file.exists()) {
file = new File(proxy.getSaveLocation() + File.separator + "igwmodServer" + File.separator + "properties.txt");//TODO remove legacy
}
if(file.exists()) {
try {
FileInputStream stream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
List<String> textList = new ArrayList<String>();
String line = br.readLine();
while(line != null) {
textList.add(line);
line = br.readLine();
}
br.close();
if(textList != null) {
for(String s : textList) {
String[] entry = s.split("=");
if(entry[0].equals("optional")) {
if(Boolean.parseBoolean(entry[1])) return true;
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
String version = installedMods.get(Constants.MOD_ID);
if(version.equals("${version}")) return true;
return version != null && version.equals(Constants.fullVersionString());
} else {
return true;
}
}
@EventHandler
public void preInit(FMLPreInitializationEvent event){
event.getModMetadata().version = Constants.fullVersionString();
proxy.preInit(event);
NetworkHandler.init();
}
@EventHandler
public void init(FMLInitializationEvent event){
}
@EventHandler
public void postInit(FMLPostInitializationEvent event){
proxy.postInit();
}
@EventHandler
public void processIMCRequests(FMLInterModComms.IMCEvent event){
proxy.processIMC(event);
}
}
| 4,008 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
InfoSupplier.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/InfoSupplier.java | package igwmod;
import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import igwmod.api.IRecipeIntegrator;
import igwmod.api.ITextInterpreter;
import igwmod.api.WikiRegistry;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import igwmod.lib.IGWLog;
import igwmod.lib.Paths;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class InfoSupplier{
private static HashMap<String, ResourceLocation> infoMap = new HashMap<String, ResourceLocation>();
private static final int MAX_TEXT_X = 475;
private static int currentTextColor;
private static String curPrefix = "";
private static String curLink = "";
/**
* Returns a wikipage for an object name.
* @param objectName
* @return
*/
public static List<String> getInfo(String modid, String objectName, boolean returnNullIfUnavailable){
String language = FMLClientHandler.instance().getCurrentLanguage();
//First try to look up the page where it should be, in the assets folder of the owning mod, local language.
List<String> info = getInfo(modid, objectName, language);
if(info != null) return info;
//If we failed, we might have a backup page in english lying around.
if(!language.equals("en_US")) {
info = getInfo(modid, objectName, "en_US");
if(info != null) return info;
}
//Let's see if we can find the page where it used to be by default, in the igwmod folder.
if(!modid.equals("igwmod")) {
info = getInfo("igwmod", objectName, language);
if(info != null) {
if(ConfigHandler.debugMode) IGWLog.warning("IGW-Mod had to look in the igwmod/assets/wiki/ folder to find the " + objectName + " page. This is deprecated. now you should use " + modid + "/assets/wiki/ instead!");
return info;
}
if(!language.equals("en_US")) {
info = getInfo("igwmod", objectName, "en_US");
if(info != null) {
if(ConfigHandler.debugMode) IGWLog.warning("IGW-Mod had to look in the igwmod/assets/wiki/ folder to find the " + objectName + " page. This is deprecated. now you should use " + modid + "/assets/wiki/ instead!");
return info;
}
}
}
if(returnNullIfUnavailable) return null;
objectName = "/assets/" + modid + "/wiki/" + language + "/" + objectName.replace(":", "/") + ".txt";
if(objectName.length() > 50) {
objectName = objectName.substring(0, objectName.length() / 2) + " " + objectName.substring(objectName.length() / 2, objectName.length());
}
return Arrays.asList("No info available about this topic. IGW-Mod is currently looking for " + objectName + ".");
}
public static List<String> getInfo(String modid, String objectName, String language){
String oldObjectName = objectName;
objectName = modid + Paths.WIKI_PATH + language + "/" + objectName.replace(":", "/") + ".txt";
if(!infoMap.containsKey(objectName)) {
infoMap.put(objectName, new ResourceLocation(objectName));
}
try {
InputStream stream;
if(oldObjectName.startsWith("server/")) {
String s = IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator + oldObjectName.substring(7) + ".txt";
stream = new FileInputStream(new File(s));
} else {
IResourceManager manager = FMLClientHandler.instance().getClient().getResourceManager();
ResourceLocation location = infoMap.get(objectName);
IResource resource = manager.getResource(location);
stream = resource.getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
List<String> textList = new ArrayList<String>();
String line = br.readLine();
while(line != null) {
textList.add(line);
line = br.readLine();
}
br.close();
return textList;
} catch(Exception e) {
return null;
}
}
@SideOnly(Side.CLIENT)
public static void analyseInfo(FontRenderer fontRenderer, List<String> fileInfo, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures){
for(ITextInterpreter ti : WikiRegistry.textInterpreters) {
if(ti.interpret(fontRenderer, fileInfo, reservedSpaces, locatedStrings, locatedStacks, locatedTextures)) return;
}
currentTextColor = 0xFF000000;
curPrefix = "";
curLink = "";
locatedStacks.clear();
locatedStrings.clear();
locatedTextures.clear();
for(int k = 0; k < fileInfo.size(); k++) {
String line = fileInfo.get(k);
for(int i = 0; i < line.length(); i++) {
if(line.charAt(i) == '[') {
for(int j = i; j < line.length(); j++) {
if(line.charAt(j) == ']') {
try {
String code = line.substring(i + 1, j);
if(decomposeTemplate(code, reservedSpaces, locatedStrings, locatedStacks, locatedTextures)) {
String cutString = line.substring(0, i) + line.substring(j + 1, line.length());
if(cutString.equals("")) fileInfo.remove(k--);
else fileInfo.set(k, cutString);
} else {
if(code.startsWith("variable{")) {
String cutString = line.substring(0, i) + VariableHandler.getVariable(code.substring("variable{".length(), code.length() - 1)) + line.substring(j + 1, line.length());
fileInfo.set(k, cutString);
}
}
} catch(IllegalArgumentException e) {
fileInfo.add(TextFormatting.RED + "Problem when parsing \"" + line.substring(i + 1, j) + "\":");
fileInfo.add(TextFormatting.RED + e.getMessage());
IGWLog.warning(e.getMessage());
}
break;
}
}
}
}
}
int currentY = 20;
for(int k = 0; k < fileInfo.size(); k++) {
String line = " " + fileInfo.get(k);
List<String> sentenceWordList = new ArrayList<String>(Arrays.asList(line.split(" ")));
for(int i = 0; i < sentenceWordList.size(); i++) {
String word = sentenceWordList.get(i);
int index = word.indexOf("[");
int otherIndex = word.indexOf("]");
if(otherIndex > 0) {
otherIndex++;
}
if(index == -1) {
index = otherIndex;
} else if(otherIndex != -1) {
index = Math.min(index, otherIndex);
}
if(index > 0 && index < word.length() - 1) {
sentenceWordList.set(i, word.substring(0, index));
sentenceWordList.add(i + 1, word.substring(index));
}
}
String[] sentenceWords = sentenceWordList.toArray(new String[sentenceWordList.size()]);
int currentWord = 0;
int currentX = 0;
String textPart = "";
int newX = 0;
while(currentWord < sentenceWords.length || sentenceWords.length == 0) {
int curTextColor = currentTextColor;
String prefix = curPrefix;
String link = curLink;
boolean newLine = false;
while(true) {
String potentialString = currentWord >= sentenceWords.length ? "" : textPart + (textPart.equals("") ? "" : " ") + sentenceWords[currentWord];
if(currentWord >= sentenceWords.length || fontRenderer.getStringWidth(prefix + potentialString) + currentX > MAX_TEXT_X && fontRenderer.getStringWidth(prefix + sentenceWords[currentWord]) <= MAX_TEXT_X - 200) {
newLine = true;
newX = 0;
break;
}
newX = getNewXFromIntersection(new Rectangle(currentX, currentY, fontRenderer.getStringWidth(prefix + potentialString), fontRenderer.FONT_HEIGHT), reservedSpaces, locatedStacks, locatedTextures);
if(textPart.equals("") && fontRenderer.getStringWidth(prefix + potentialString) + newX <= MAX_TEXT_X) {
currentX = newX;
} else if(newX != currentX) {
break;
}
currentWord++;
textPart = potentialString;
boolean foundCode = false;
if(currentWord < sentenceWords.length) {
String potentialCode = sentenceWords[currentWord];
int i = potentialCode.indexOf('[');
int j = potentialCode.indexOf(']');
while(i != -1 && j != -1) {
try {
sentenceWords[currentWord] = potentialCode.substring(0, i) + potentialCode.substring(j + 1, potentialCode.length());
decomposeInLineTemplate(potentialCode.substring(i + 1, j));
newX += fontRenderer.getStringWidth(textPart + " ");
foundCode = true;
} catch(IllegalArgumentException e) {
fileInfo.add(TextFormatting.RED + e.getMessage());
IGWLog.warning(e.getMessage());
}
potentialCode = sentenceWords[currentWord];
i = potentialCode.indexOf('[');
j = potentialCode.indexOf(']');
}
if(foundCode) break;
}
}
locatedStrings.add(link.equals("") ? new LocatedString(prefix + textPart, currentX, currentY, curTextColor, false) : new LocatedString(prefix + textPart, currentX, currentY, false, link));
if(newLine) currentY += fontRenderer.FONT_HEIGHT + 1;
currentX = newX;
textPart = "";
if(sentenceWords.length == 0) break;
}
// currentY += fontRenderer.FONT_HEIGHT + 1;
}
}
private static int getNewXFromIntersection(Rectangle rect, List<IReservedSpace> reservedSpaces, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures){
int oldX = rect.x;
boolean modified = false;
for(IReservedSpace reservedSpace : reservedSpaces) {
Rectangle space = reservedSpace.getReservedSpace();
if(space.x + space.width > rect.x && space.intersects(rect)) {
rect = new Rectangle(space.x + space.width, rect.y, rect.width, rect.height);
modified = true;
}
}
for(LocatedStack locatedStack : locatedStacks) {
Rectangle space = locatedStack.getReservedSpace();
if(space.x + space.width > rect.x && space.intersects(rect)) {
//rect = new Rectangle(rect.x, rect.y, space.x + space.width - rect.x, rect.height);
rect = new Rectangle(space.x + space.width, rect.y, rect.width, rect.height);
modified = true;
}
}
for(IWidget locatedTexture : locatedTextures) {
if(locatedTexture instanceof IReservedSpace) {
Rectangle space = ((IReservedSpace)locatedTexture).getReservedSpace();
if(space.x + space.width > rect.x && space.intersects(rect)) {
// rect = new Rectangle(rect.x, rect.y, space.x + space.width - rect.x, rect.height);
rect = new Rectangle(space.x + space.width, rect.y, rect.width, rect.height);
modified = true;
}
}
}
return modified ? rect.x : oldX;
}
private static boolean decomposeTemplate(String code, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
for(IRecipeIntegrator integrator : WikiRegistry.recipeIntegrators) {
if(code.startsWith(integrator.getCommandKey() + "{")) {
String[] args = code.substring(integrator.getCommandKey().length() + 1, code.length() - 1).split(",");
for(int i = 0; i < args.length; i++) {
args[i] = args[i].trim();
}
integrator.onCommandInvoke(args, reservedSpaces, locatedStrings, locatedStacks, locatedTextures);
return true;
}
}
return false;
}
private static void decomposeInLineTemplate(String code) throws IllegalArgumentException{
if(!code.endsWith("}")) throw new IllegalArgumentException("Code misses a '}' at the end! Full code: " + code);
if(code.startsWith("color{")) {
colorCommand(code);
} else if(code.startsWith("prefix{")) {
prefixCommand(code);
} else if(code.startsWith("link{")) {
curLink = code.substring(5, code.length() - 1);
}
}
private static void colorCommand(String code) throws IllegalArgumentException{
String colorCode = code.substring(6, code.length() - 1);
if(colorCode.startsWith("0x")) colorCode = colorCode.substring(2);
try {
currentTextColor = 0xFF000000 | Integer.parseInt(colorCode, 16);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("Using an invalid color parameter. Only use hexadecimal (0123456789ABCDEF) numbers! Also only use 6 digits (no alpha digits). Full code: " + code + ", color code: " + colorCode);
}
}
private static void prefixCommand(String code) throws IllegalArgumentException{
String prefixCode = code.substring(7, code.length() - 1);
curPrefix = "";
for(int i = 0; i < prefixCode.length(); i++) {
if(prefixCode.charAt(i) != 'r') curPrefix += "\u00a7" + prefixCode.charAt(i);
}
}
}
| 15,504 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ServerProxy.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/ServerProxy.java | package igwmod;
import java.io.File;
import igwmod.lib.IGWLog;
import igwmod.network.MessageSendServerTab;
import igwmod.network.NetworkHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.server.FMLServerHandler;
public class ServerProxy implements IProxy{
@Override
public void preInit(FMLPreInitializationEvent event){
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void onJoinWorld(EntityJoinWorldEvent event){
if(!event.getWorld().isRemote && event.getEntity() instanceof EntityPlayer) {
File serverFolder = new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator);
if(!serverFolder.exists()) {
serverFolder = new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmodServer" + File.separator);//TODO legacy remove
if(serverFolder.exists()) {
IGWLog.warning("Found IGW Mod server page in the 'igwmodServer' folder. This is deprecated! Rename the folder to 'igwmod' instead.");
}
}
if(serverFolder.exists()) {
NetworkHandler.sendTo(new MessageSendServerTab(serverFolder), (EntityPlayerMP)event.getEntity());
}
}
}
@Override
public void postInit(){
}
@Override
public void processIMC(IMCEvent event){}
@Override
public String getSaveLocation(){
String mcDataLocation = FMLServerHandler.instance().getSavesDirectory().getAbsolutePath();
return mcDataLocation.substring(0, mcDataLocation.length() - 2);
}
@Override
public EntityPlayer getPlayer(){
return null;
}
}
| 2,096 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
TessWrapper.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/TessWrapper.java | package igwmod;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
public class TessWrapper{
public static void startDrawingTexturedQuads(){
Tessellator.getInstance().getBuffer().begin(7, DefaultVertexFormats.POSITION_TEX);
}
public static void addVertexWithUV(double x, double y, double z, double u, double v){
Tessellator.getInstance().getBuffer().pos(x, y, z).tex(u, v).endVertex();
}
public static void draw(){
Tessellator.getInstance().draw();
}
}
| 570 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IGWLog.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/lib/IGWLog.java | package igwmod.lib;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class IGWLog{
private static Logger logger = LogManager.getLogger(Constants.MOD_ID);
public static void info(String message){
logger.log(Level.INFO, message);
}
public static void error(String message){
logger.log(Level.ERROR, message);
}
public static void warning(String message){
logger.log(Level.WARN, message);
}
}
| 527 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
Paths.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/lib/Paths.java | package igwmod.lib;
public class Paths{
public static final String MOD_ID = "igwmod";
public static final String MOD_ID_WITH_COLON = MOD_ID + ":";
public static final String WIKI_PATH = ":wiki/";
}
| 211 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
Util.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/lib/Util.java | package igwmod.lib;
import java.net.URI;
import java.util.HashMap;
import net.minecraft.entity.Entity;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry.EntityRegistration;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
public class Util{
public static Entity getEntityForClass(Class<? extends Entity> entityClass){
try {
return entityClass.getConstructor(World.class).newInstance(FMLClientHandler.instance().getClient().world);
} catch(Exception e) {
IGWLog.error("[LocatedEntity.java] An entity class doesn't have a constructor with a single World parameter! Entity = " + entityClass.getName());
e.printStackTrace();
return null;
}
}
private static HashMap<String, ModContainer> entityNames;
private static boolean reflectionFailed;
public static String getModIdForEntity(Class<? extends Entity> entity){
if(reflectionFailed) return "minecraft";
if(entityNames == null) {
try {
entityNames = (HashMap<String, ModContainer>)ReflectionHelper.findField(EntityRegistry.class, "entityNames").get(EntityRegistry.instance());
} catch(Exception e) {
IGWLog.warning("IGW-Mod failed to perform reflection! A result of this is that wiki pages related to Entities will not be found. Report to MineMaarten please!");
e.printStackTrace();
reflectionFailed = true;
return "minecraft";
}
}
EntityRegistration entityReg = EntityRegistry.instance().lookupModSpawn(entity, true);
if(entityReg == null) return "minecraft";
ModContainer mod = entityNames.get(entityReg.getEntityName());
if(mod == null) {
IGWLog.info("Couldn't find the owning mod of the entity " + entityReg.getEntityName() + " even though it's registered through the EntityRegistry!");
return "minecraft";
} else {
return mod.getModId().toLowerCase();
}
}
public static void openBrowser(String url){
try {
Class oclass = Class.forName("java.awt.Desktop");
Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]);
oclass.getMethod("browse", new Class[]{URI.class}).invoke(object, new Object[]{new URI(url)});
} catch(Throwable throwable) {
IGWLog.error("Couldn\'t open link");
throwable.printStackTrace();
}
}
}
| 2,744 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
Constants.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/lib/Constants.java | package igwmod.lib;
import org.lwjgl.input.Keyboard;
public class Constants{
public static final String MOD_ID = "igwmod";
private static final String MASSIVE = "@MASSIVE@";
private static final String MAJOR = "@MAJOR@";
private static final String MINOR = "@MINOR@";
private static final String BUILD = "@BUILD_NUMBER@";
private static final String MC_VERSION = "@MC_VERSION@";
// public static final String WIKI_PAGE_LOCATION = "https://github.com/MineMaarten/IGW-mod/archive/master.zip";// "http://www.minemaarten.com/wp-content/uploads/2013/12/WikiPages.zip";
// public static final String ZIP_NAME = "igw";
// public static final int CONNECTION_TIMEOUT = 3000;
// public static final int READ_TIMEOUT = 5000;
// public static final String INTERNET_UPDATE_CONFIG_KEY = "Update pages via internet";
// public static final String USE_OFFLINE_WIKIPAGES_KEY = "Use offline wikipages";
public static final int DEFAULT_KEYBIND_OPEN_GUI = Keyboard.KEY_I;
public static final int TEXTURE_MAP_ID = 15595;
public static String fullVersionString(){
return String.format("%s-%s.%s.%s-%s", MC_VERSION, MASSIVE, MAJOR, MINOR, BUILD);
}
}
| 1,214 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
Textures.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/lib/Textures.java | package igwmod.lib;
import net.minecraft.util.ResourceLocation;
public class Textures{
public static final String GUI_LOCATION = Paths.MOD_ID_WITH_COLON + "textures/gui";
public static final ResourceLocation GUI_WIKI = new ResourceLocation(GUI_LOCATION + "/GuiWiki.png");
public static final ResourceLocation GUI_ACTIVE_TAB = new ResourceLocation(GUI_LOCATION + "/GuiActiveTab.png");
public static final ResourceLocation GUI_NON_ACTIVE_TAB = new ResourceLocation(GUI_LOCATION + "/GuiNonActiveTab.png");
public static final ResourceLocation GUI_PAGE_BROWSER = new ResourceLocation(GUI_LOCATION + "/GuiPageBrowser.png");
public static final ResourceLocation GUI_ITEMS_AND_BLOCKS = new ResourceLocation(GUI_LOCATION + "/GuiItemsAndBlocks.png");
public static final ResourceLocation GUI_ENTITIES = new ResourceLocation(GUI_LOCATION + "/GuiEntities.png");
}
| 883 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocationIntPacket.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/LocationIntPacket.java | package igwmod.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
/**
*
* @author MineMaarten
*/
public abstract class LocationIntPacket<REQ extends IMessage> extends AbstractPacket<REQ>{
protected int x, y, z;
public LocationIntPacket(){
}
public LocationIntPacket(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
@Override
public void toBytes(ByteBuf buf){
buf.writeInt(x);
buf.writeInt(y);
buf.writeInt(z);
}
@Override
public void fromBytes(ByteBuf buf){
x = buf.readInt();
y = buf.readInt();
z = buf.readInt();
}
public NetworkRegistry.TargetPoint getTargetPoint(World world){
return getTargetPoint(world, 64);
}
public NetworkRegistry.TargetPoint getTargetPoint(World world, double updateDistance){
return new NetworkRegistry.TargetPoint(world.provider.getDimension(), x, y, z, updateDistance);
}
}
| 1,135 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
MessageMultiHeader.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/MessageMultiHeader.java | package igwmod.network;
import igwmod.IGWMod;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.EntityPlayer;
public class MessageMultiHeader extends AbstractPacket<MessageMultiHeader>{
private int size;
public static byte[] totalMessage;
public static int offset = 0;
public MessageMultiHeader(){
}
public MessageMultiHeader(int size){
this.size = size;
}
@Override
public void fromBytes(ByteBuf buf){
size = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf){
buf.writeInt(size);
}
@Override
public void handleClientSide(MessageMultiHeader message, EntityPlayer player){
totalMessage = new byte[message.size];
offset = 0;
}
@Override
public void handleServerSide(MessageMultiHeader message, EntityPlayer player){}
public static void receivePayload(byte[] payload){
System.arraycopy(payload, 0, totalMessage, offset, payload.length);
offset += NetworkHandler.MAX_SIZE;
if(offset >= totalMessage.length) {
MessageSendServerTab m = new MessageSendServerTab();
ByteBuf buf = Unpooled.wrappedBuffer(totalMessage);
m.fromBytes(buf);
m.handleClientSide(m, IGWMod.proxy.getPlayer());
}
}
}
| 1,354 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
NetworkHandler.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/NetworkHandler.java | /*
* This file is part of Blue Power.
*
* Blue Power is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Blue Power is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Blue Power. If not, see <http://www.gnu.org/licenses/>
*/
package igwmod.network;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import igwmod.lib.Constants;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
/**
*
* @author MineMaarten
*/
public class NetworkHandler{
public static final SimpleNetworkWrapper INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(Constants.MOD_ID);
private static int discriminant;
/*
* The integer is the ID of the message, the Side is the side this message will be handled (received) on!
*/
public static void init(){
INSTANCE.registerMessage(MessageSendServerTab.class, MessageSendServerTab.class, discriminant++, Side.CLIENT);
INSTANCE.registerMessage(MessageMultiHeader.class, MessageMultiHeader.class, discriminant++, Side.CLIENT);
INSTANCE.registerMessage(MessageMultiPart.class, MessageMultiPart.class, discriminant++, Side.CLIENT);
}
/*
* public static void INSTANCE.registerMessage(Class<? extends AbstractPacket<? extends IMessage>> clazz){ INSTANCE.registerMessage(clazz, clazz,
* discriminant++, Side.SERVER, discriminant++, Side.SERVER); }
*/
public static void sendToAll(IMessage message){
INSTANCE.sendToAll(message);
}
public static void sendTo(IMessage message, EntityPlayerMP player){
List<IMessage> messages = getSplitMessages(message);
for(IMessage m : messages) {
INSTANCE.sendTo(m, player);
}
}
@SuppressWarnings("rawtypes")
public static void sendToAllAround(LocationIntPacket message, World world, double distance){
sendToAllAround(message, message.getTargetPoint(world, distance));
}
@SuppressWarnings("rawtypes")
public static void sendToAllAround(LocationIntPacket message, World world){
sendToAllAround(message, message.getTargetPoint(world));
}
@SuppressWarnings("rawtypes")
public static void sendToAllAround(LocationDoublePacket message, World world){
sendToAllAround(message, message.getTargetPoint(world));
}
public static void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point){
INSTANCE.sendToAllAround(message, point);
}
public static void sendToDimension(IMessage message, int dimensionId){
INSTANCE.sendToDimension(message, dimensionId);
}
public static void sendToServer(IMessage message){
INSTANCE.sendToServer(message);
}
public static final int MAX_SIZE = 65530;
private static List<IMessage> getSplitMessages(IMessage message){
List<IMessage> messages = new ArrayList<IMessage>();
ByteBuf buf = Unpooled.buffer();
message.toBytes(buf);
byte[] bytes = buf.array();
if(bytes.length < MAX_SIZE) {
messages.add(message);
} else {
messages.add(new MessageMultiHeader(bytes.length));
int offset = 0;
while(offset < bytes.length) {
messages.add(new MessageMultiPart(Arrays.copyOfRange(bytes, offset, Math.min(offset + MAX_SIZE, bytes.length))));
offset += MAX_SIZE;
}
}
return messages;
}
}
| 4,266 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocationDoublePacket.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/LocationDoublePacket.java | package igwmod.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
/**
*
* @author MineMaarten
*/
public abstract class LocationDoublePacket<REQ extends IMessage> extends AbstractPacket<REQ>{
protected double x, y, z;
public LocationDoublePacket(){
}
public LocationDoublePacket(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
@Override
public void toBytes(ByteBuf buf){
buf.writeDouble(x);
buf.writeDouble(y);
buf.writeDouble(z);
}
@Override
public void fromBytes(ByteBuf buf){
x = buf.readDouble();
y = buf.readDouble();
z = buf.readDouble();
}
public NetworkRegistry.TargetPoint getTargetPoint(World world){
return getTargetPoint(world, 64);
}
public NetworkRegistry.TargetPoint getTargetPoint(World world, double updateDistance){
return new NetworkRegistry.TargetPoint(world.provider.getDimension(), x, y, z, updateDistance);
}
}
| 1,174 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
MessageSendServerTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/MessageSendServerTab.java | package igwmod.network;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import igwmod.IGWMod;
import igwmod.api.WikiRegistry;
import igwmod.gui.tabs.ServerWikiTab;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.network.ByteBufUtils;
public class MessageSendServerTab extends AbstractPacket<MessageSendServerTab>{
private File serverFolder;
public MessageSendServerTab(){
}
public MessageSendServerTab(File serverFolder){
this.serverFolder = serverFolder;
}
@Override
public void toBytes(ByteBuf buf){
File[] files = serverFolder.listFiles();
buf.writeInt(files.length);
for(File file : files) {
try {
ByteBufUtils.writeUTF8String(buf, file.getName());
FileInputStream stream = new FileInputStream(file);
byte[] byteArray = IOUtils.toByteArray(stream);
buf.writeInt(byteArray.length);
buf.writeBytes(byteArray);
stream.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
@Override
public void fromBytes(ByteBuf buf){
File folder = new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator);
folder.mkdirs();
try {
FileUtils.deleteDirectory(folder);//clear the folder
} catch(IOException e1) {
e1.printStackTrace();
}
folder.mkdirs();
int fileAmount = buf.readInt();
for(int i = 0; i < fileAmount; i++) {
try {
File file = new File(folder.getAbsolutePath() + File.separator + ByteBufUtils.readUTF8String(buf));
byte[] fileBytes = new byte[buf.readInt()];
buf.readBytes(fileBytes);
FileOutputStream stream = new FileOutputStream(file);
IOUtils.write(fileBytes, stream);
stream.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
@Override
public void handleClientSide(MessageSendServerTab message, EntityPlayer player){
WikiRegistry.registerWikiTab(new ServerWikiTab());
}
@Override
public void handleServerSide(MessageSendServerTab message, EntityPlayer player){
// TODO Auto-generated method stub
}
}
| 2,587 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
MessageMultiPart.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/MessageMultiPart.java | package igwmod.network;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
public class MessageMultiPart extends AbstractPacket<MessageMultiPart>{
private byte[] payload;
public MessageMultiPart(){
}
public MessageMultiPart(byte[] payload){
this.payload = payload;
}
@Override
public void fromBytes(ByteBuf buf){
payload = new byte[buf.readInt()];
buf.readBytes(payload);
}
@Override
public void toBytes(ByteBuf buf){
buf.writeInt(payload.length);
buf.writeBytes(payload);
}
@Override
public void handleClientSide(MessageMultiPart message, EntityPlayer player){
MessageMultiHeader.receivePayload(message.payload);
}
@Override
public void handleServerSide(MessageMultiPart message, EntityPlayer player){
}
}
| 864 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
AbstractPacket.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/network/AbstractPacket.java | package igwmod.network;
import igwmod.IGWMod;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
/**
*
* @author MineMaarten
*/
public abstract class AbstractPacket<REQ extends IMessage> implements IMessage, IMessageHandler<REQ, REQ>{
@Override
public REQ onMessage(REQ message, MessageContext ctx){
if(ctx.side == Side.SERVER) {
handleServerSide(message, ctx.getServerHandler().player);
} else {
handleClientSide(message, IGWMod.proxy.getPlayer());
}
return null;
}
/**
* Handle a packet on the client side.
*
* @param message
* TODO
* @param player
* the player reference
*/
public abstract void handleClientSide(REQ message, EntityPlayer player);
/**
* Handle a packet on the server side.
*
* @param message
* TODO
* @param player
* the player reference
*/
public abstract void handleServerSide(REQ message, EntityPlayer player);
}
| 1,301 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocatedTexture.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/LocatedTexture.java | package igwmod.gui;
import igwmod.IGWMod;
import igwmod.TessWrapper;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class LocatedTexture implements IReservedSpace, IWidget{
public ResourceLocation texture;
public int x, y, width, height;
private int textureId;
public LocatedTexture(ResourceLocation texture, int x, int y, int width, int height){
this.texture = texture;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
if(texture.getResourcePath().startsWith("server")) {
try {
BufferedImage image = ImageIO.read(new FileInputStream(new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator + texture.getResourcePath().substring(7))));
DynamicTexture t = new DynamicTexture(image);
textureId = t.getGlTextureId();
} catch(Exception e) {
e.printStackTrace();
}
}
}
public LocatedTexture(ResourceLocation texture, int x, int y){
this(texture, x, y, 1);
}
public LocatedTexture(ResourceLocation texture, int x, int y, double scale){
this(texture, x, y, 0, 0);
try {
BufferedImage bufferedimage;
if(texture.getResourcePath().startsWith("server")) {
bufferedimage = ImageIO.read(new FileInputStream(new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator + texture.getResourcePath().substring(7))));
} else {
IResource iresource = Minecraft.getMinecraft().getResourceManager().getResource(texture);
InputStream inputstream = iresource.getInputStream();
bufferedimage = ImageIO.read(inputstream);
}
width = (int)(bufferedimage.getWidth() * scale);
height = (int)(bufferedimage.getHeight() * scale);
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public Rectangle getReservedSpace(){
return new Rectangle(x, y, width, height);
}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){
if(texture.getResourcePath().startsWith("server")) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
} else {
gui.mc.getTextureManager().bindTexture(texture);
}
drawTexture(x, y, width, height);
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){}
public static void drawTexture(int x, int y, int width, int heigth){
int minYCap = Math.max(0, GuiWiki.MIN_TEXT_Y - y);
int maxYCap = Math.min(heigth, GuiWiki.MAX_TEXT_Y - y);
TessWrapper.startDrawingTexturedQuads();
TessWrapper.addVertexWithUV(x, y + maxYCap, 0, 0.0, (float)maxYCap / heigth);//TODO render at right Z level
TessWrapper.addVertexWithUV(x + width, y + maxYCap, 0, 1.0, (float)maxYCap / heigth);
TessWrapper.addVertexWithUV(x + width, y + minYCap, 0, 1, (float)minYCap / heigth);
TessWrapper.addVertexWithUV(x, y + minYCap, 0, 0, (float)minYCap / heigth);
TessWrapper.draw();
// this.drawTexturedModalRect(x, y, 0, 0, 16, 16);
}
@Override
public void setX(int x){
this.x = x;
}
@Override
public void setY(int y){
this.y = y;
}
@Override
public int getX(){
return x;
}
@Override
public int getY(){
return y;
}
@Override
public int getHeight(){
return height;
}
}
| 3,972 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocatedEntity.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/LocatedEntity.java | package igwmod.gui;
import java.awt.Rectangle;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import igwmod.gui.tabs.EntityWikiTab;
import igwmod.lib.Util;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraftforge.fml.client.FMLClientHandler;
public class LocatedEntity extends Gui implements IReservedSpace, IPageLink{
protected static FontRenderer fontRenderer = FMLClientHandler.instance().getClient().fontRenderer;
public final Entity entity;
private int x, y;
private final float scale;
public LocatedEntity(Class<? extends Entity> clazz, int x, int y){
this(clazz, x, y, 0.5F);
}
public LocatedEntity(Class<? extends Entity> clazz, int x, int y, float scale){
entity = Util.getEntityForClass(clazz);
this.x = x;
this.y = y;
this.scale = scale;
}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){
if(GuiWiki.MIN_TEXT_Y < y && GuiWiki.MAX_TEXT_Y > y + 16 * scale) {
EntityWikiTab.drawEntity(entity, x + 16, y + 27, scale, 0);
}
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){
if(getReservedSpace().contains(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop())) {
drawCreativeTabHoveringText(entity.getName(), mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop());
}
}
@Override
public void setX(int x){
this.x = x;
}
@Override
public void setY(int y){
this.y = y;
}
@Override
public int getX(){
return x;
}
@Override
public int getY(){
return y;
}
@Override
public boolean onMouseClick(GuiWiki gui, int x, int y){
if(getReservedSpace().contains(x, y)) {
gui.setCurrentFile(entity);
return true;
}
return false;
}
@Override
public Rectangle getReservedSpace(){
return new Rectangle(x, y, 32, 32);
}
@Override
public String getName(){
return entity.getName();
}
@Override
public String getLinkAddress(){
return "entity/" + EntityList.getEntityString(entity);
}
protected void drawCreativeTabHoveringText(String par1Str, int par2, int par3){
func_102021_a(Arrays.asList(new String[]{par1Str}), par2, par3);
}
protected void func_102021_a(List par1List, int par2, int par3){
drawHoveringText(par1List, par2, par3, fontRenderer);
}
protected void drawHoveringText(List par1List, int par2, int par3, FontRenderer font){
if(!par1List.isEmpty()) {
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int k = 0;
Iterator iterator = par1List.iterator();
while(iterator.hasNext()) {
String s = (String)iterator.next();
int l = font.getStringWidth(s);
if(l > k) {
k = l;
}
}
int i1 = par2 + 12;
int j1 = par3 - 12;
int k1 = 8;
if(par1List.size() > 1) {
k1 += 2 + (par1List.size() - 1) * 10;
}
/* if(i1 + k > width) {
i1 -= 28 + k;
}
if(j1 + k1 + 6 > height) {
j1 = height - k1 - 6;
}*/
zLevel = 300.0F;
// itemRenderer.zLevel = 300.0F;
int l1 = -267386864;
drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1);
drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1);
int i2 = 1347420415;
int j2 = (i2 & 16711422) >> 1 | i2 & -16777216;
drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2);
drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2);
for(int k2 = 0; k2 < par1List.size(); ++k2) {
String s1 = (String)par1List.get(k2);
font.drawStringWithShadow(s1, i1, j1, -1);
if(k2 == 0) {
j1 += 2;
}
j1 += 10;
}
zLevel = 0.0F;
//itemRenderer.zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
@Override
public int getHeight(){
return 32;
}
}
| 5,353 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
BrowseHistory.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/BrowseHistory.java | package igwmod.gui;
import java.util.ArrayList;
import java.util.List;
import igwmod.gui.tabs.IWikiTab;
public class BrowseHistory{
public final String link;
public final IWikiTab tab;
public final Object[] meta;
public float scroll;
private static int curIndex;
private BrowseHistory(String link, IWikiTab tab, Object... meta){
this.link = link;
this.meta = meta;
this.tab = tab;
}
public static void updateHistory(float scroll){
if(history.size() > 0) history.get(history.size() - 1).scroll = scroll;
}
private static List<BrowseHistory> history = new ArrayList<BrowseHistory>();
public static void addHistory(String link, IWikiTab tab, Object... meta){
if(history.size() > 0) history = history.subList(0, curIndex + 1);
curIndex = history.size();
history.add(new BrowseHistory(link, tab, meta));
}
public static BrowseHistory previous(){
if(canGoPrevious()) {
curIndex--;
return history.get(curIndex);
} else {
throw new IllegalArgumentException("It's not possible to go to the previous page here. Check for 'canGoPrevious()' first!");
}
}
public static BrowseHistory next(){
if(canGoNext()) {
curIndex++;
return history.get(curIndex);
} else {
throw new IllegalArgumentException("It's not possible to go to the next page here. Check for 'canGoNext()' first!");
}
}
public static boolean canGoPrevious(){
return curIndex > 0;
}
public static boolean canGoNext(){
return curIndex + 1 < history.size();
}
}
| 1,692 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IReservedSpace.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/IReservedSpace.java | package igwmod.gui;
import java.awt.Rectangle;
public interface IReservedSpace{
public Rectangle getReservedSpace();
}
| 125 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocatedString.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/LocatedString.java | package igwmod.gui;
import java.awt.Rectangle;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.client.FMLClientHandler;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class LocatedString extends Gui implements IPageLink, GuiYesNoCallback{
protected static FontRenderer fontRenderer = FMLClientHandler.instance().getClient().fontRenderer;
private final String string;
private String cappedText;
private int x;
private int y;
private int color;
private final boolean shadow;
private String linkAddress;
private GuiScreen parentGui;
/**
* A constructor for linked located strings. Color doesn't matter as these will always be the same for linked strings.
* @param string
* @param x
* @param y
* @param shadow
* @param linkAddress
*/
public LocatedString(String string, int x, int y, boolean shadow, String linkAddress){
this.string = string;
cappedText = string;
this.x = x;
this.y = y;
this.shadow = shadow;
this.linkAddress = linkAddress;
}
/**
* A constructor for unlinked located strings. You can specify a color.
* @param string
* @param x
* @param y
* @param color
* @param shadow
*/
public LocatedString(String string, int x, int y, int color, boolean shadow){
this.string = string;
cappedText = string;
this.x = x;
this.y = y;
this.color = color;
this.shadow = shadow;
}
public LocatedString capTextWidth(int maxWidth){
cappedText = string;
if(fontRenderer.getStringWidth(cappedText) <= maxWidth) return this;
while(fontRenderer.getStringWidth(cappedText + "...") > maxWidth) {
cappedText = cappedText.substring(0, cappedText.length() - 1);
}
cappedText += "...";
return this;
}
@Override
public boolean onMouseClick(GuiWiki gui, int x, int y){
if(linkAddress != null) {
if(getMouseSpace().contains(x, y)) {
if(linkAddress.contains("www") || linkAddress.startsWith("http://") || linkAddress.startsWith("https://")) {
parentGui = Minecraft.getMinecraft().currentScreen;
Minecraft.getMinecraft().displayGuiScreen(new GuiConfirmOpenLink(this, linkAddress, 0, false));
} else {
gui.setCurrentFile(linkAddress);
}
return true;
}
}
return false;
}
@Override
public void confirmClicked(boolean result, int value){
if(result) igwmod.lib.Util.openBrowser(linkAddress);
Minecraft.getMinecraft().displayGuiScreen(parentGui);
}
private Rectangle getMouseSpace(){
return new Rectangle((int)(x * GuiWiki.TEXT_SCALE), (int)(y * GuiWiki.TEXT_SCALE), (int)(fontRenderer.getStringWidth(cappedText) * GuiWiki.TEXT_SCALE), (int)(fontRenderer.FONT_HEIGHT * GuiWiki.TEXT_SCALE));
}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){
GL11.glPushMatrix();
GL11.glScaled(GuiWiki.TEXT_SCALE, GuiWiki.TEXT_SCALE, 1);
//GlStateManager.enableLighting();
// RenderHelper.enableStandardItemLighting();
if(getLinkAddress() != null) {
Rectangle mouseSpace = getMouseSpace();
fontRenderer.drawString(TextFormatting.UNDERLINE + cappedText, x, y, mouseSpace.contains(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop()) ? 0xFFFFFF00 : 0xFF3333FF, shadow);
} else {
GL11.glColor4d(0, 0, 0, 1);
fontRenderer.drawString(cappedText, x, y, color, shadow);
}
GL11.glPopMatrix();
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){
if(!cappedText.equals(string) && getMouseSpace().contains(mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop())) {
drawCreativeTabHoveringText(string, mouseX - gui.getGuiLeft(), mouseY - gui.getGuiTop());
}
}
@Override
public Rectangle getReservedSpace(){
return new Rectangle(x, y, fontRenderer.getStringWidth(cappedText), fontRenderer.FONT_HEIGHT);
}
@Override
public String getName(){
return string;
}
@Override
public String getLinkAddress(){
return linkAddress;
}
@Override
public String toString(){
return x + ", " + y + ", string: " + string;
}
@Override
public void setX(int x){
this.x = x;
}
@Override
public void setY(int y){
this.y = y;
}
@Override
public int getX(){
return x;
}
@Override
public int getY(){
return y;
}
protected void drawCreativeTabHoveringText(String par1Str, int par2, int par3){
func_102021_a(Arrays.asList(new String[]{par1Str}), par2, par3);
}
protected void func_102021_a(List par1List, int par2, int par3){
drawHoveringText(par1List, par2, par3, fontRenderer);
}
protected void drawHoveringText(List par1List, int par2, int par3, FontRenderer font){
if(!par1List.isEmpty()) {
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.disableStandardItemLighting();
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
int k = 0;
Iterator iterator = par1List.iterator();
while(iterator.hasNext()) {
String s = (String)iterator.next();
int l = font.getStringWidth(s);
if(l > k) {
k = l;
}
}
int i1 = par2 + 12;
int j1 = par3 - 12;
int k1 = 8;
if(par1List.size() > 1) {
k1 += 2 + (par1List.size() - 1) * 10;
}
/* if(i1 + k > width) {
i1 -= 28 + k;
}
if(j1 + k1 + 6 > height) {
j1 = height - k1 - 6;
}*/
zLevel = 300.0F;
// itemRenderer.zLevel = 300.0F;
int l1 = -267386864;
drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1);
drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1);
drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1);
int i2 = 1347420415;
int j2 = (i2 & 16711422) >> 1 | i2 & -16777216;
drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2);
drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2);
drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2);
for(int k2 = 0; k2 < par1List.size(); ++k2) {
String s1 = (String)par1List.get(k2);
font.drawStringWithShadow(s1, i1, j1, -1);
if(k2 == 0) {
j1 += 2;
}
j1 += 10;
}
zLevel = 0.0F;
//itemRenderer.zLevel = 0.0F;
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
RenderHelper.enableStandardItemLighting();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
@Override
public int getHeight(){
return fontRenderer.FONT_HEIGHT;
}
}
| 8,108 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ContainerBlockWiki.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/ContainerBlockWiki.java | package igwmod.gui;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
/**
* This class is derived from Vanilla's ContainerCreative class.
*/
class ContainerBlockWiki extends Container{
public void updateStacks(List<LocatedStack> stacks, List<IPageLink> pageLinks){
int invSize = 0;
for(LocatedStack stack : stacks)
if(stack.y >= GuiWiki.MIN_TEXT_Y * GuiWiki.TEXT_SCALE && 16 + stack.y <= GuiWiki.MAX_TEXT_Y * GuiWiki.TEXT_SCALE) invSize++;
for(IPageLink link : pageLinks)
if(link instanceof LocatedStack) invSize++;
InventoryBasic inventory = new InventoryBasic("tmp", true, invSize);
inventorySlots = new ArrayList();
inventoryItemStacks = NonNullList.<ItemStack> create();
int curSlot = 0;
for(LocatedStack stack : stacks) {
if(stack.y >= GuiWiki.MIN_TEXT_Y * GuiWiki.TEXT_SCALE && 16 + stack.y <= GuiWiki.MAX_TEXT_Y * GuiWiki.TEXT_SCALE) {
addSlotToContainer(new Slot(inventory, curSlot, stack.x, stack.y){
@Override
public boolean isItemValid(ItemStack par1ItemStack){
return false;
}
});
if(stack.stack.getItemDamage() == 32767)//TODO better way to handle wildcard value.
{
stack.stack.setItemDamage(0);
}
inventory.setInventorySlotContents(curSlot++, stack.stack);
}
}
for(IPageLink pageLink : pageLinks) {
if(pageLink instanceof LocatedStack) {
LocatedStack stack = (LocatedStack)pageLink;
addSlotToContainer(new Slot(inventory, curSlot, stack.x, stack.y){
@Override
public boolean isItemValid(ItemStack par1ItemStack){
return false;
}
});
inventory.setInventorySlotContents(curSlot++, stack.stack);
}
}
}
@Override
public boolean canInteractWith(EntityPlayer par1EntityPlayer){
return true;
}
/**
* Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that.
*/
@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2){
return ItemStack.EMPTY;
}
@Override
public void putStackInSlot(int par1, ItemStack par2ItemStack){} //override this to do nothing, as NEI tries to place items in this container which makes it crash.
}
| 2,849 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocatedStack.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/LocatedStack.java | package igwmod.gui;
import java.awt.Rectangle;
import igwmod.api.WikiRegistry;
import net.minecraft.item.ItemStack;
public class LocatedStack implements IReservedSpace, IPageLink{
public final ItemStack stack;
public int x, y;
public LocatedStack(ItemStack stack, int x, int y){
this.stack = stack;
this.x = x;
this.y = y;
}
@Override
public Rectangle getReservedSpace(){
return new Rectangle((int)(x / GuiWiki.TEXT_SCALE), (int)(y / GuiWiki.TEXT_SCALE), (int)(16 / GuiWiki.TEXT_SCALE), (int)(16 / GuiWiki.TEXT_SCALE));
}
@Override
public boolean onMouseClick(GuiWiki gui, int x, int y){
return false;//Don't do anything, as pagelinking will be handled by the container call when a slot gets clicked.
}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){} //Rendering will be done by the GuiContainer.
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){}
@Override
public String getName(){
return stack.getItem() == null ? "<STACK HAS NO ITEM!>" : stack.getDisplayName();
}
@Override
public String getLinkAddress(){
return WikiRegistry.getPageForItemStack(stack);
}
@Override
public void setX(int x){
this.x = x;
}
@Override
public void setY(int y){
this.y = y;
}
@Override
public int getX(){
return x;
}
@Override
public int getY(){
return y;
}
@Override
public int getHeight(){
return 16;
}
}
| 1,596 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
GuiWiki.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/GuiWiki.java | package igwmod.gui;
import igwmod.ClientProxy;
import igwmod.ConfigHandler;
import igwmod.InfoSupplier;
import igwmod.TickHandler;
import igwmod.WikiUtils;
import igwmod.api.BlockWikiEvent;
import igwmod.api.EntityWikiEvent;
import igwmod.api.ItemWikiEvent;
import igwmod.api.PageChangeEvent;
import igwmod.api.WikiRegistry;
import igwmod.gui.tabs.IWikiTab;
import igwmod.lib.IGWLog;
import igwmod.lib.Textures;
import igwmod.lib.Util;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderEntityItem;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.inventory.ClickType;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.FMLClientHandler;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
/**
* Derived from Vanilla's GuiContainerCreative
*/
public class GuiWiki extends GuiContainer{
private static String currentFile = ""; //path (ResourceLocation) of the current wikipage
private static List<String> fileInfo = new ArrayList<String>(); //The raw info directly retrieved from the .txt file.
public static List<IWikiTab> wikiTabs = new ArrayList<IWikiTab>();//A list of all the tabs registered.
private static IWikiTab currentTab;
private static int currentTabPage = 0;
private static String currentModIdPage = "igwmod";
private static List<IPageLink> visibleWikiPages = new ArrayList<IPageLink>();
private static int matchingWikiPages;
private static final List<LocatedStack> locatedStacks = new ArrayList<LocatedStack>();
private static final List<LocatedString> locatedStrings = new ArrayList<LocatedString>();
private static final List<IWidget> locatedTextures = new ArrayList<IWidget>();
private static final ResourceLocation scrollbarTexture = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png");
private static float currentPageLinkScroll;
private static float currentPageScroll;
private static int currentPageTranslation;
/** True if the scrollbar is being dragged */
private boolean isScrollingPageLink;
private boolean isScrollingPage;
private boolean wasClicking;
private int lastMouseX;
private int oldGuiScale;
private GuiScreen prevGui;
private GuiButton previousButton, nextButton;
private static GuiTextField searchField;
private static final int PAGE_LINK_SCROLL_X = 80;
private static final int PAGE_LINK_SCROLL_HEIGHT = 214;
private static final int PAGE_LINK_SCROLL_Y = 14;
private static final int PAGE_SCROLL_X = 240;
private static final int PAGE_SCROLL_HEIGHT = 230;
private static final int PAGE_SCROLL_Y = 4;
public static final double TEXT_SCALE = 0.5D;
public static final int MAX_TEXT_Y = 453;
public static final int MIN_TEXT_Y = 10;
public GuiWiki(){
super(new ContainerBlockWiki());
allowUserInput = true;
ySize = 238;
xSize = 256;
if(currentTab == null) currentTab = wikiTabs.get(0);
}
@Override
public void initGui(){
if(mc.gameSettings.guiScale != 0) {
oldGuiScale = mc.gameSettings.guiScale;
mc.gameSettings.guiScale = 0;
mc.displayGuiScreen(this);
} else {
super.initGui();
buttonList.clear();
Keyboard.enableRepeatEvents(true);
String lastSearch = "";
if(searchField != null) lastSearch = searchField.getText();
searchField = new GuiTextField(0, fontRenderer, guiLeft + 40, guiTop + currentTab.getSearchBarAndScrollStartY(), 53, fontRenderer.FONT_HEIGHT);
searchField.setMaxStringLength(15);
searchField.setEnableBackgroundDrawing(true);
searchField.setVisible(true);
searchField.setFocused(false);
searchField.setCanLoseFocus(true);
searchField.setText(lastSearch);
updateSearch();
previousButton = new GuiButton(0, guiLeft + 40, guiTop + 4, 25, 10, "<--");
nextButton = new GuiButton(1, guiLeft + 68, guiTop + 4, 25, 10, "-->");
previousButton.enabled = BrowseHistory.canGoPrevious();
nextButton.enabled = BrowseHistory.canGoNext();
buttonList.add(previousButton);
buttonList.add(nextButton);
}
}
public FontRenderer getFontRenderer(){
return fontRenderer;
}
@Override
public int getGuiLeft(){
return guiLeft;
}
@Override
public int getGuiTop(){
return guiTop;
}
public void setPreviousScreen(GuiScreen gui){
prevGui = gui;
}
@Override
public void actionPerformed(GuiButton button){
BrowseHistory history;
if(button.id == 0) {
history = BrowseHistory.previous();
} else {
history = BrowseHistory.next();
}
currentFile = history.link;
currentTab = history.tab;
currentTabPage = getPageNumberForTab(currentTab);
currentTab.onPageChange(this, currentFile, history.meta);
updateWikiPage(history.meta);
updateSearch();
initGui();//update the textfield location.
currentPageScroll = history.scroll;
updatePageScrolling();
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
@Override
public void onGuiClosed(){
super.onGuiClosed();
Keyboard.enableRepeatEvents(false);
mc.gameSettings.guiScale = oldGuiScale;
}
@Override
protected void handleMouseClick(Slot slot, int slotId, int mouseButton, ClickType type){
if(slot != null && slot.getHasStack()) {
setCurrentFile(slot.getStack());
}
}
@Override
protected void mouseClicked(int x, int y, int button) throws IOException{
super.mouseClicked(x, y, button);
searchField.mouseClicked(x, y, button);
if(searchField.isFocused() && button == 1) {
searchField.setText("");
currentPageLinkScroll = 0;
updateSearch();
}
List<IWikiTab> visibleTabs = getVisibleTabs();
for(int i = 0; i < visibleTabs.size(); i++) {
if(x <= 33 + guiLeft && x >= 1 + guiLeft && y >= 8 + guiTop + i * 35 && y <= 43 + guiTop + i * 35) {
currentTab = visibleTabs.get(i);
currentPageLinkScroll = 0;
updateSearch();
initGui();//update the textfield location.
break;
}
}
for(IPageLink link : visibleWikiPages) {
if(link.onMouseClick(this, -guiLeft + x, -guiTop + y)) return;
}
for(LocatedString link : locatedStrings) {
if(link.onMouseClick(this, -guiLeft + x, -guiTop + y)) return;
}
if(hasMultipleTabPages() && x < 33 + guiLeft && x >= 1 + guiLeft && y >= 214 + guiTop && y <= 236 + guiTop) {
if(button == 0) {
if(++currentTabPage >= getTotalTabPages()) currentTabPage = 0;
} else if(button == 1) {
if(--currentTabPage < 0) currentTabPage = getTotalTabPages() - 1;
}
}
}
public void setCurrentFile(World world, BlockPos pos){
BlockWikiEvent wikiEvent = new BlockWikiEvent(world, pos);
if(wikiEvent.drawnStack.getItem() == null) return;
wikiEvent.pageOpened = WikiRegistry.getPageForItemStack(wikiEvent.drawnStack);
if(wikiEvent.pageOpened == null) wikiEvent.pageOpened = wikiEvent.drawnStack.getUnlocalizedName().replace("tile.", "block/").replace("item.", "item/");
MinecraftForge.EVENT_BUS.post(wikiEvent);
setCurrentFile(wikiEvent.pageOpened, wikiEvent.drawnStack);
}
public void setCurrentFile(Entity entity){
EntityWikiEvent wikiEvent = new EntityWikiEvent(entity);
wikiEvent.pageOpened = WikiRegistry.getPageForEntityClass(entity.getClass());
MinecraftForge.EVENT_BUS.post(wikiEvent);
setCurrentFile(wikiEvent.pageOpened, entity);
}
public void setCurrentFile(ItemStack stack){
String defaultName = WikiRegistry.getPageForItemStack(stack);
if(defaultName == null) defaultName = stack.getUnlocalizedName().replace("tile.", "block/").replace("item.", "item/");
ItemWikiEvent wikiEvent = new ItemWikiEvent(stack, defaultName);
MinecraftForge.EVENT_BUS.post(wikiEvent);
if(stack != null) {
stack = stack.copy();
// stack.stackSize = 1;
stack.setCount(1);
}
setCurrentFile(wikiEvent.pageOpened, stack);
}
public void setCurrentFile(String file, Object... metadata){
if(file == null) return;
BrowseHistory.updateHistory(currentPageScroll);
if(metadata.length == 0) {
ItemStack displayedStack = WikiUtils.getStackFromName(file);
if(!displayedStack.isEmpty()) metadata = new Object[]{displayedStack};
}
currentFile = file;
IWikiTab tab = getTabForPage(currentFile);
if(tab != null) currentTab = tab;
currentTabPage = getPageNumberForTab(currentTab);
currentTab.onPageChange(this, file, metadata);
updateWikiPage(metadata);
updateSearch();
BrowseHistory.addHistory(file, currentTab, metadata);
initGui();//update the textfield location.
}
/**
* Fired when a key is typed. This is the equivalent of KeyListener.keyTyped(KeyEvent e).
*/
@Override
protected void keyTyped(char par1, int keyCode) throws IOException{
if(searchField.textboxKeyTyped(par1, keyCode)) {
currentPageLinkScroll = 0;
updateSearch();
} else {
if(keyCode == ClientProxy.openInterfaceKey.getKeyCode() || keyCode == 1) {
FMLClientHandler.instance().showGuiScreen(prevGui);
} else {
super.keyTyped(par1, keyCode);
}
}
}
private void updateSearch(){
List<IPageLink> pages = currentTab.getPages(null);//request all pages.
if(pages != null) {
List<Integer> matchingIndexes = new ArrayList<Integer>();
for(int i = 0; i < pages.size(); i++) {
if(searchField.getText().toLowerCase().equals("")) {
matchingIndexes.add(i);
} else if(pages.get(i).getName().toLowerCase().contains(searchField.getText().toLowerCase()) && !(pages.get(i) instanceof LocatedSectionString)) {
matchingIndexes.add(i);
}
}
matchingWikiPages = matchingIndexes.size();
int firstListedPageIndex = (int)(getScrollStates() * currentPageLinkScroll + 0.5F) * currentTab.pagesPerScroll();
int[] indexes = new int[Math.min(Math.min(matchingIndexes.size() - firstListedPageIndex, matchingIndexes.size()), currentTab.pagesPerTab())];
for(int i = 0; i < indexes.length; i++) {
indexes[i] = matchingIndexes.get(firstListedPageIndex + i);
}
visibleWikiPages = currentTab.getPages(indexes);
} else {
visibleWikiPages = new ArrayList<IPageLink>();
matchingWikiPages = 0;
}
((ContainerBlockWiki)inventorySlots).updateStacks(locatedStacks, visibleWikiPages);
}
private void updatePageScrolling(){
int translation = -(int)(currentPageScroll * getMaxPageTranslation() / 2 + 0.5F) * 2 - currentPageTranslation;
currentPageTranslation += translation;
for(LocatedStack stack : locatedStacks) {
stack.setY(stack.getY() + translation / 2);
}
for(LocatedString string : locatedStrings) {
string.setY(string.getY() + translation);
}
for(IWidget image : locatedTextures) {
image.setY(image.getY() + translation);
}
((ContainerBlockWiki)inventorySlots).updateStacks(locatedStacks, visibleWikiPages);
}
private int getMaxPageTranslation(){
int maxTranslation = -100000;
for(IWidget texture : locatedTextures) {
maxTranslation = Math.max(maxTranslation, texture.getY() + texture.getHeight());
}
for(LocatedString string : locatedStrings) {
maxTranslation = Math.max(maxTranslation, string.getY() + fontRenderer.FONT_HEIGHT);
}
return Math.max(maxTranslation - currentPageTranslation - MAX_TEXT_Y, 0);
}
private boolean needsPageLinkScrollBars(){
return matchingWikiPages > currentTab.pagesPerTab();
}
private boolean needsPageScrollBars(){
return getMaxPageTranslation() > 0;
}
@Override
public void handleMouseInput() throws IOException{
super.handleMouseInput();
int i = Mouse.getEventDWheel();
if(i != 0) {
if(i > 0) {
i = 1;
}
if(i < 0) {
i = -1;
}
if(lastMouseX < PAGE_LINK_SCROLL_X + guiLeft + 14) {
if(needsPageLinkScrollBars()) {
int j = getScrollStates();
currentPageLinkScroll = (float)(currentPageLinkScroll - (double)i / (double)j);
if(currentPageLinkScroll < 0.0F) {
currentPageLinkScroll = 0.0F;
}
if(currentPageLinkScroll > 1.0F) {
currentPageLinkScroll = 1.0F;
}
updateSearch();
}
} else {
if(needsPageScrollBars()) {
int maxTranslation = getMaxPageTranslation();
currentPageScroll -= (float)i / maxTranslation * 40;
if(currentPageScroll > 1F) currentPageScroll = 1F;
else if(currentPageScroll < 0F) currentPageScroll = 0F;
updatePageScrolling();
}
}
}
}
private int getScrollStates(){
return (1 + matchingWikiPages - currentTab.pagesPerTab()) / currentTab.pagesPerScroll();
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks){
drawDefaultBackground();
lastMouseX = mouseX;
boolean leftClicking = Mouse.isButtonDown(0);
int pageLinkScrollX1 = guiLeft + PAGE_LINK_SCROLL_X;
int pageLinkScrollY1 = guiTop + PAGE_LINK_SCROLL_Y + currentTab.getSearchBarAndScrollStartY();
int pageLinkScrollX2 = pageLinkScrollX1 + 14;
int pageLinkScrollY2 = pageLinkScrollY1 + PAGE_LINK_SCROLL_HEIGHT - currentTab.getSearchBarAndScrollStartY();
int pageScrollX1 = guiLeft + PAGE_SCROLL_X;
int pageScrollY1 = guiTop + PAGE_SCROLL_Y;
int pageScrollX2 = pageScrollX1 + 14;
int pageScrollY2 = pageScrollY1 + PAGE_SCROLL_HEIGHT;
if(!wasClicking && leftClicking) {
if(mouseX >= pageLinkScrollX1 && mouseY >= pageLinkScrollY1 && mouseX < pageLinkScrollX2 && mouseY < pageLinkScrollY2) {
isScrollingPageLink = needsPageLinkScrollBars();
} else if(mouseX >= pageScrollX1 && mouseY >= pageScrollY1 && mouseX < pageScrollX2 && mouseY < pageScrollY2) {
isScrollingPage = needsPageScrollBars();
}
}
if(!leftClicking) {
isScrollingPageLink = false;
isScrollingPage = false;
}
wasClicking = leftClicking;
if(isScrollingPageLink) {
currentPageLinkScroll = (mouseY - pageLinkScrollY1 - 7.5F) / (pageLinkScrollY2 - pageLinkScrollY1 - 15.0F);
if(currentPageLinkScroll < 0.0F) {
currentPageLinkScroll = 0.0F;
}
if(currentPageLinkScroll > 1.0F) {
currentPageLinkScroll = 1.0F;
}
updateSearch();
} else if(isScrollingPage) {
currentPageScroll = (mouseY - pageScrollY1 - 7.5F) / (pageScrollY2 - pageScrollY1 - 15.0F);
if(currentPageScroll < 0.0F) {
currentPageScroll = 0.0F;
}
if(currentPageScroll > 1.0F) {
currentPageScroll = 1.0F;
}
updatePageScrolling();
}
super.drawScreen(mouseX, mouseY, partialTicks);
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glDisable(GL11.GL_LIGHTING);
}
/**
* Draw the background layer for the GuiContainer (everything behind the items)
*/
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// RenderHelper.enableGUIStandardItemLighting();
//Draw the wiki tabs.
mc.getTextureManager().bindTexture(Textures.GUI_WIKI);
drawTexturedModalRect(guiLeft + 33, guiTop, 33, 0, xSize - 33, ySize);
List<IWikiTab> visibleTabs = getVisibleTabs();
for(int i = 0; i < visibleTabs.size(); i++) {
drawTexturedModalRect(guiLeft, guiTop + 4 + i * 35, 0, currentTab == visibleTabs.get(i) ? 0 : 35, 33, 35);
}
//Draw the change tabpage tab.
if(hasMultipleTabPages()) {
drawTexturedModalRect(guiLeft, guiTop + 214, 0, 70, 33, 22);
}
//draw the pagelink scrollbar
if(needsPageLinkScrollBars()) {
drawTexturedModalRect(guiLeft + PAGE_LINK_SCROLL_X - 1, guiTop + PAGE_LINK_SCROLL_Y + currentTab.getSearchBarAndScrollStartY() - 1, PAGE_SCROLL_X - 1, PAGE_SCROLL_Y - 1, 14, PAGE_LINK_SCROLL_HEIGHT - currentTab.getSearchBarAndScrollStartY() - 1);
drawTexturedModalRect(guiLeft + PAGE_LINK_SCROLL_X - 1, guiTop + PAGE_LINK_SCROLL_Y + PAGE_LINK_SCROLL_HEIGHT - 2, PAGE_SCROLL_X - 1, PAGE_SCROLL_Y + PAGE_SCROLL_HEIGHT - 2, 14, 1);
} else {
drawVerticalLine(guiLeft + PAGE_LINK_SCROLL_X + 13, guiTop + PAGE_LINK_SCROLL_Y + currentTab.getSearchBarAndScrollStartY(), PAGE_LINK_SCROLL_HEIGHT + 20, 0xFF888888);
}
//Draw the text field.
searchField.drawTextBox();
drawWikiPage(mouseX, mouseY);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY){
super.drawGuiContainerForegroundLayer(mouseX, mouseY);
GL11.glColor4d(1, 1, 1, 1);
//Draw the scroll bar widgets.
mc.getTextureManager().bindTexture(scrollbarTexture);
if(needsPageLinkScrollBars()) {
drawTexturedModalRect(PAGE_LINK_SCROLL_X, PAGE_LINK_SCROLL_Y + currentTab.getSearchBarAndScrollStartY() + (int)((PAGE_LINK_SCROLL_HEIGHT - currentTab.getSearchBarAndScrollStartY() - 17) * currentPageLinkScroll), 232 + (needsPageLinkScrollBars() ? 0 : 12), 0, 12, 15);
}
drawTexturedModalRect(PAGE_SCROLL_X, PAGE_SCROLL_Y + (int)((PAGE_SCROLL_Y + PAGE_SCROLL_HEIGHT - PAGE_SCROLL_Y - 17) * currentPageScroll), 232 + (needsPageScrollBars() ? 0 : 12), 0, 12, 15);
GL11.glEnable(GL11.GL_LIGHTING);
//draw the tab page browse text if necessary
if(hasMultipleTabPages()) {
fontRenderer.drawString(currentTabPage + 1 + "/" + getTotalTabPages(), 10, 221, 0xFF000000);
}
//Draw the wiki page stacks.
for(LocatedStack locatedStack : locatedStacks) {
locatedStack.renderBackground(this, mouseX, mouseY);
}
//draw the wikipage
currentTab.renderForeground(this, mouseX, mouseY);
GL11.glPushMatrix();
GL11.glTranslated(guiLeft, guiTop, 0);
for(LocatedString locatedString : locatedStrings) {
if(locatedString.getY() > MIN_TEXT_Y && locatedString.getReservedSpace().height + locatedString.getY() <= MAX_TEXT_Y) {
locatedString.renderForeground(this, mouseX, mouseY);
}
}
GL11.glPopMatrix();
// Draw the wiki page images.
GL11.glColor4d(1, 1, 1, 1);
GL11.glPushMatrix();
GL11.glScaled(TEXT_SCALE, TEXT_SCALE, 1);
for(IWidget texture : locatedTextures) {
texture.renderForeground(this, mouseX, mouseY);
}
GL11.glPopMatrix();
//Draw wiki tab images.
List<IReservedSpace> reservedSpaces = currentTab.getReservedSpaces();
if(reservedSpaces != null) {
for(IReservedSpace space : reservedSpaces) {
if(space instanceof LocatedTexture) {
((LocatedTexture)space).renderForeground(this, mouseX, mouseY);
}
}
}
//render the wiki links
for(IPageLink link : visibleWikiPages) {
link.renderForeground(this, mouseX, mouseY);
}
drawTooltips(mouseX, mouseY);
//GL11.glDisable(GL12.GL_RESCALE_NORMAL);
// RenderHelper.disableStandardItemLighting();
// GL11.glDisable(GL11.GL_LIGHTING);
//GL11.glDisable(GL11.GL_DEPTH_TEST);
}
private void drawTooltips(int x, int y){
GlStateManager.enableLighting();
List<IWikiTab> visibleTabs = getVisibleTabs();
for(int i = 0; i < visibleTabs.size(); i++) {
if(x <= 33 + guiLeft && x >= 1 + guiLeft && y >= 4 + guiTop + i * 35 && y <= 39 + guiTop + i * 35) {
drawHoveringText(I18n.format(visibleTabs.get(i).getName()), x - guiLeft, y - guiTop);
}
}
if(hasMultipleTabPages() && x < 33 + guiLeft && x >= 1 + guiLeft && y >= 214 + guiTop && y <= 236 + guiTop) {
drawHoveringText(Arrays.asList(new String[]{I18n.format("igwmod.tooltip.tabPageBrowse.next"), I18n.format("igwmod.tooltip.tabPageBrowse.previous")}), x - guiLeft, y - guiTop);
}
/*
if(curSection == EnumWikiSection.ENTITIES) {
for(int i = 0; i < shownEntityList.size(); i++) {
if(x >= guiLeft + 41 && x <= guiLeft + 76 && y >= guiTop + 75 + i * 36 && y <= guiTop + 110 + i * 36) {
drawCreativeTabHoveringText(shownEntityList.get(i).getEntityName(), x - guiLeft, y - guiTop);
}
}
}*/
}
private void updateWikiPage(Object... metadata){
Object o = metadata.length > 0 ? metadata[0] : null;
ItemStack pageStack = o instanceof ItemStack ? (ItemStack)o : null;
Entity pageEntity = o instanceof Entity ? (Entity)o : null;
PageChangeEvent pageChangeEvent = new PageChangeEvent(currentFile, pageStack, pageEntity);
MinecraftForge.EVENT_BUS.post(pageChangeEvent);
currentFile = pageChangeEvent.currentFile;
fileInfo = pageChangeEvent.pageText;
if(fileInfo == null) {
String modid = currentModIdPage;
if(currentFile.contains(":")) {
String[] splitted = currentFile.split(":", 2);
modid = splitted[0];
currentFile = splitted[1];
} else {
if(pageStack != null) {
modid = WikiUtils.getOwningModId(pageStack);
} else if(pageEntity != null) {
modid = Util.getModIdForEntity(pageEntity.getClass());
} else if(o instanceof String) {
modid = (String)o;
} else {
ItemStack tabItem = currentTab.renderTabIcon(this);
if(tabItem != null && tabItem.getItem() != null) {
modid = WikiUtils.getOwningModId(tabItem);
}
if(ConfigHandler.debugMode && !currentFile.startsWith("server")) {
IGWLog.info("Tracked down the mod owner of the page \"" + currentFile + "\" by getting the mod owner of the tab ItemStack. This is not recommended. Please prefix page links with <modid>:, so for example: pneumaticcraft:menu/baseConcepts");
}
}
}
currentModIdPage = modid;
fileInfo = InfoSupplier.getInfo(modid, currentFile, false);
}
List<IReservedSpace> reservedSpaces = currentTab.getReservedSpaces();
if(reservedSpaces == null) reservedSpaces = new ArrayList<IReservedSpace>();
reservedSpaces.add(new ReservedSpace(new Rectangle(0, 0, 200, Integer.MAX_VALUE)));
InfoSupplier.analyseInfo(fontRenderer, fileInfo, reservedSpaces, locatedStrings, locatedStacks, locatedTextures);
((ContainerBlockWiki)inventorySlots).updateStacks(locatedStacks, visibleWikiPages);
currentPageTranslation = 0;
currentPageScroll = 0;
}
private void drawWikiPage(int mouseX, int mouseY){
currentTab.renderBackground(this, mouseX, mouseY);
GL11.glPushMatrix();
GL11.glTranslated(guiLeft, guiTop, 0);
// Draw the wiki page images.
GL11.glColor4d(1, 1, 1, 1);
GL11.glPushMatrix();
GL11.glScaled(TEXT_SCALE, TEXT_SCALE, 1);
for(IWidget texture : locatedTextures) {
texture.renderBackground(this, mouseX, mouseY);
}
GL11.glPopMatrix();
for(LocatedString locatedString : locatedStrings) {
if(locatedString.getY() > MIN_TEXT_Y && locatedString.getReservedSpace().height + locatedString.getY() <= MAX_TEXT_Y) {
locatedString.renderBackground(this, mouseX, mouseY);
}
}
GL11.glColor4d(1, 1, 1, 1);
//Draw wiki tab images.
List<IReservedSpace> reservedSpaces = currentTab.getReservedSpaces();
if(reservedSpaces != null) {
for(IReservedSpace space : reservedSpaces) {
if(space instanceof LocatedTexture) {
((LocatedTexture)space).renderBackground(this, mouseX, mouseY);
}
}
}
GL11.glPushMatrix();
GL11.glTranslated(0, 4, 0);
List<IWikiTab> visibleTabs = getVisibleTabs();
RenderHelper.enableGUIStandardItemLighting();
for(IWikiTab tab : visibleTabs) {
ItemStack drawingStack = tab.renderTabIcon(this);
if(drawingStack != null) {
if(drawingStack.getItem() instanceof ItemBlock) {
renderRotatingBlockIntoGUI(this, drawingStack, 11, 23, 1.5F);
} else {
boolean oldSetting = mc.gameSettings.fancyGraphics;
mc.gameSettings.fancyGraphics = true;
renderRotatingBlockIntoGUI(this, drawingStack, 12, 20, 1.2F);
mc.gameSettings.fancyGraphics = oldSetting;
}
}
GL11.glTranslated(0, 35, 0);
}
GL11.glPopMatrix();
//render the wiki links
for(IPageLink link : visibleWikiPages) {
link.renderBackground(this, mouseX, mouseY);
}
GL11.glPopMatrix();
}
private List<IWikiTab> getVisibleTabs(){
List<IWikiTab> tabs = new ArrayList<IWikiTab>();
for(int i = currentTabPage * 6; i < currentTabPage * 6 + 6 && i < wikiTabs.size(); i++) {
tabs.add(wikiTabs.get(i));
}
return tabs;
}
private IWikiTab getTabForPage(String page){
if(page == null) return null; //When there isn't a valid page just stay on the same page.
if(currentTab != null) {//give the current tab the highest priority.
List<IPageLink> links = currentTab.getPages(null);
if(links != null) {
for(IPageLink link : links) {
if(page.equals(link.getLinkAddress())) return currentTab;
}
}
}
for(int i = wikiTabs.size() - 1; i >= 0; i--) {
IWikiTab tab = wikiTabs.get(i);
List<IPageLink> links = tab.getPages(null);
if(links != null) {
for(IPageLink link : links) {
if(page.equals(link.getLinkAddress())) return tab;
}
}
}
return null;
}
private int getPageNumberForTab(IWikiTab tab){
int index = wikiTabs.indexOf(tab);
if(index == -1) {
return 0;
} else {
return index / 6;
}
}
private boolean hasMultipleTabPages(){
return wikiTabs.size() > 6;
}
private int getTotalTabPages(){
return wikiTabs.size() / 6 + 1;
}
/**
* This method was copied from Equivalent Exchange 3's RenderUtils.java class, https://github.com/pahimar/Equivalent-Exchange-3/blob/master/src/main/java/com/pahimar/ee3/client/renderer/RenderUtils.java
* @param fontRenderer
* @param stack
* @param x
* @param y
* @param zLevel
* @param scale
*/
/*
public void renderRotatingBlockIntoGUI(GuiWiki gui, ItemStack stack, int x, int y, float scale){
RenderBlocks renderBlocks = new RenderBlocks();
Block block = Block.blocksList[stack.itemID];
FMLClientHandler.instance().getClient().renderEngine.bindTexture(TextureMap.locationBlocksTexture);
GL11.glPushMatrix();
GL11.glTranslatef(x - 2, y + 3, -3.0F + gui.zLevel);
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F * scale, 1.0F * scale, -1.0F);
GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(-TickHandler.ticksExisted, 0.0F, 1.0F, 0.0F);
int var10 = Item.itemsList[stack.itemID].getColorFromItemStack(stack, 0);
float var16 = (var10 >> 16 & 255) / 255.0F;
float var12 = (var10 >> 8 & 255) / 255.0F;
float var13 = (var10 & 255) / 255.0F;
GL11.glColor4f(var16, var12, var13, 1.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
renderBlocks.useInventoryTint = true;
renderBlocks.renderBlockAsItem(block, stack.getItemDamage(), 1.0F);
renderBlocks.useInventoryTint = true;
GL11.glPopMatrix();
}*/
private static RenderEntityItem renderItem;
private static EntityItem entityItem;
public void renderRotatingBlockIntoGUI(GuiWiki gui, ItemStack stack, int x, int y, float scale){
if(entityItem == null) {
entityItem = new EntityItem(gui.mc.world);
renderItem = new RenderEntityItem(Minecraft.getMinecraft().getRenderManager(), Minecraft.getMinecraft().getRenderItem()){
@Override
public boolean shouldBob(){
return false;
}
};
}
entityItem.setItem(stack);
GlStateManager.pushMatrix();
GlStateManager.translate(x + 1, y + 13, 20);
GlStateManager.scale(40 * scale, 40 * scale, -40 * scale);
GlStateManager.rotate(180, 1, 0, 0);
GlStateManager.rotate(30, 1, 0, 0);
GlStateManager.translate(0.1, 0.1, gui.zLevel);
GlStateManager.rotate(-TickHandler.ticksExisted, 0, 1, 0);
renderItem.doRender(entityItem, 0.0, 0.0, 0, 0, 0);
GlStateManager.popMatrix();
/* RenderBlocks renderBlocks = new RenderBlocks();
Block block = Block.blocksList[stack.itemID];
FMLClientHandler.instance().getClient().renderEngine.bindTexture(TextureMap.locationBlocksTexture);
GL11.glPushMatrix();
GL11.glTranslatef(x - 2, y + 3, -3.0F + gui.zLevel);
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F * scale, 1.0F * scale, -1.0F);
GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(-TickHandler.ticksExisted, 0.0F, 1.0F, 0.0F);
int var10 = Item.itemsList[stack.itemID].getColorFromItemStack(stack, 0);
float var16 = (var10 >> 16 & 255) / 255.0F;
float var12 = (var10 >> 8 & 255) / 255.0F;
float var13 = (var10 & 255) / 255.0F;
GL11.glColor4f(var16, var12, var13, 1.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
renderBlocks.useInventoryTint = true;
renderBlocks.renderBlockAsItem(block, stack.getItemDamage(), 1.0F);
renderBlocks.useInventoryTint = true;
GL11.glPopMatrix();*/
}
}
| 32,997 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IClickable.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/IClickable.java | package igwmod.gui;
public interface IClickable extends IReservedSpace, IWidget{
public boolean onMouseClick(GuiWiki gui, int x, int y);
}
| 144 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IPageLink.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/IPageLink.java | package igwmod.gui;
public interface IPageLink extends IClickable{
/**
* String that is being used by the search bar.
* @return
*/
public String getName();
public String getLinkAddress();
}
| 220 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IWidget.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/IWidget.java | package igwmod.gui;
public interface IWidget{
public void renderBackground(GuiWiki gui, int mouseX, int mouseY);
public void renderForeground(GuiWiki gui, int mouseX, int mouseY);
public void setX(int x);
public void setY(int y);
public int getX();
public int getY();
public int getHeight();
}
| 329 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
LocatedSectionString.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/LocatedSectionString.java | package igwmod.gui;
import net.minecraft.util.text.TextFormatting;
/**
* Created by K-4U on 17-7-2015.
*/
public class LocatedSectionString extends LocatedString{
private String beforeFormat;
/**
* A constructor for unlinked located strings. You can specify a color.
* @param string
* @param x
* @param y
* @param color
* @param shadow
*/
public LocatedSectionString(String string, int x, int y, int color, boolean shadow){
super(TextFormatting.BOLD + string, x, y, color, shadow);
beforeFormat = string;
}
/**
* A constructor for unlinked located strings.
* @param string
* @param x
* @param y
* @param shadow
*/
public LocatedSectionString(String string, int x, int y, boolean shadow){
super(TextFormatting.BOLD + string, x, y, 0, shadow);
beforeFormat = string;
}
@Override
public String getName(){
return beforeFormat;
}
}
| 979 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ReservedSpace.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/ReservedSpace.java | package igwmod.gui;
import java.awt.Rectangle;
public class ReservedSpace implements IReservedSpace{
private final Rectangle reservedSpace;
public ReservedSpace(Rectangle reservedSpace){
this.reservedSpace = reservedSpace;
}
@Override
public Rectangle getReservedSpace(){
return reservedSpace;
}
}
| 343 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ServerWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/ServerWikiTab.java | package igwmod.gui.tabs;
import igwmod.IGWMod;
import igwmod.InfoSupplier;
import igwmod.gui.GuiWiki;
import igwmod.gui.LocatedTexture;
import igwmod.lib.IGWLog;
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.GameRegistry;
import org.lwjgl.opengl.GL11;
public class ServerWikiTab extends BaseWikiTab{
private String serverName;
private ItemStack iconStack = ItemStack.EMPTY;
private LocatedTexture icon;
public ServerWikiTab(){
List<String> info = InfoSupplier.getInfo("igwmod", "server/properties", true);
if(info != null) {
for(String s : info) {
String[] entry = s.split("=");
if(entry[0].equals("server_name")) serverName = entry[1];
if(entry[0].equals("icon_item")) {
String[] icon = entry[1].split(":");
// iconStack = new ItemStack(GameRegistry.findItem(icon[0], icon[1]));
iconStack = GameRegistry.makeItemStack(icon[0] + ":" + icon[1], 0, 1, "");
if(iconStack.isEmpty()) {
IGWLog.warning("Couldn't find a server tab icon item stack for the name: " + entry[1]);
}
}
}
}
if(iconStack.isEmpty()) {
icon = new LocatedTexture(new ResourceLocation("server/tab_icon.png"), 5, 10, 27, 27);
}
File[] files = new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod").listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String filename){
return filename.endsWith(".txt");
}
});
for(File file : files) {
if(!file.getName().equals("properties.txt")) {
pageEntries.add(file.getName().substring(0, file.getName().length() - 4));
}
}
}
@Override
public String getName(){
return serverName != null ? serverName : "Missing 'igwmod/properties.txt' with 'server_name=' key";
}
@Override
public ItemStack renderTabIcon(GuiWiki gui){
if(!iconStack.isEmpty()) {
return iconStack;
} else {
GL11.glPushMatrix();
GL11.glTranslated(0, -6, 0);
icon.renderBackground(null, 0, 0);
GL11.glPopMatrix();
return null;
}
}
@Override
protected String getPageName(String pageEntry){
return pageEntry;
}
@Override
protected String getPageLocation(String pageEntry){
return "server/" + pageEntry;
}
}
| 2,768 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
EntityWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/EntityWikiTab.java | package igwmod.gui.tabs;
import igwmod.TickHandler;
import igwmod.api.WikiRegistry;
import igwmod.gui.GuiWiki;
import igwmod.gui.IPageLink;
import igwmod.gui.IReservedSpace;
import igwmod.gui.LocatedEntity;
import igwmod.gui.LocatedTexture;
import igwmod.lib.Textures;
import igwmod.lib.Util;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
public class EntityWikiTab implements IWikiTab{
private static Entity curEntity;
private static Entity tabEntity;
public EntityWikiTab(){
}
@Override
public String getName(){
return "igwmod.wikitab.entities.name";
}
@Override
public ItemStack renderTabIcon(GuiWiki gui){
if(tabEntity == null) {
EntityPlayer player = gui.mc.player;
tabEntity = new EntityCreeper(player.world);
}
drawEntity(tabEntity, 18, 28, 0.6F, 0);
return null;
}
@Override
public List<IReservedSpace> getReservedSpaces(){
List<IReservedSpace> reservedSpaces = new ArrayList<IReservedSpace>();
reservedSpaces.add(new LocatedTexture(Textures.GUI_ENTITIES, 40, 74, 36, 153));
return reservedSpaces;
}
@Override
public List<IPageLink> getPages(int[] indexes){
List<Class<? extends Entity>> allEntries = WikiRegistry.getEntityPageEntries();
List<IPageLink> pages = new ArrayList<IPageLink>();
if(indexes == null) {
for(int i = 0; i < allEntries.size(); i++) {
pages.add(new LocatedEntity(allEntries.get(i), 41, 77 + i * 36));
}
} else {
for(int i = 0; i < indexes.length; i++) {
pages.add(new LocatedEntity(allEntries.get(indexes[i]), 41, 77 + i * 36));
}
}
return pages;
}
@Override
public int pagesPerTab(){
return 4;
}
@Override
public int pagesPerScroll(){
return 1;
}
@Override
public int getSearchBarAndScrollStartY(){
return 61;
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// RenderHelper.enableStandardItemLighting();
if(curEntity != null) drawEntity(curEntity, gui.getGuiLeft() + 65, gui.getGuiTop() + 49, 0.7F, 0);
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@Override
public void onMouseClick(GuiWiki gui, int mouseX, int mouseY, int mouseKey){}
/* public static void drawEntity(Entity entity, int x, int y, float size, float partialTicks){
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_DEPTH_TEST);
short short1 = 240;
short short2 = 240;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, short1 / 1.0F, short2 / 1.0F);
GL11.glPushMatrix();
GL11.glTranslated(x, y, 10);
float maxHitboxComponent = Math.max(1, Math.max(entity.width, entity.height));
GL11.glScaled(40 * size / maxHitboxComponent, -40 * size / maxHitboxComponent, -40 * size / maxHitboxComponent);
//GL11.glRotated(20, 1, 0, 1);
GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotated(TickHandler.ticksExisted + partialTicks, 0, 1, 0);
Minecraft.getMinecraft().getRenderManager().renderEntityWithPosYaw(entity, 0D, 0D, 0.0D, 0, partialTicks);
GL11.glPopMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_DEPTH_TEST);
}*/
public static void drawEntity(Entity entity, int x, int y, float size, float partialTicks){
//GL11.glEnable(GL11.GL_LIGHTING);
//x, y, scale, yaw, pitch
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
float maxHitboxComponent = Math.max(1, Math.max(entity.width, entity.height));
int scale = (int)(40 * size / maxHitboxComponent);
GlStateManager.enableColorMaterial();
GlStateManager.pushMatrix();
GL11.glTranslatef(x, y, 50.0F);
GL11.glScalef(-scale, scale, scale);
GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(30, 1, 0, 0);
GL11.glRotatef(135.0F, 0.0F, 1.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(-TickHandler.ticksExisted, 0, 1, 0);
/* GL11.glRotatef(-((float)Math.atan((double)(par4 / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F);
entity.renderYawOffset = (float)Math.atan((double)(par3 / 40.0F)) * 20.0F;
entity.rotationYaw = (float)Math.atan((double)(par3 / 40.0F)) * 40.0F;
entity.rotationPitch = -((float)Math.atan((double)(par4 / 40.0F))) * 20.0F;
entity.rotationYawHead = entity.rotationYaw;
entity.prevRotationYawHead = entity.rotationYaw;*/
GL11.glTranslatef(0.0F, (float)entity.getYOffset(), 0.0F);
RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager();
rendermanager.setRenderShadow(false);
Minecraft.getMinecraft().getRenderManager().playerViewY = 180.0F;
Minecraft.getMinecraft().getRenderManager().renderEntity(entity, 0.0D, 0.0D, 0.0D, 0.0F, 1.0F, false);
rendermanager.setRenderShadow(true);
/* entity.renderYawOffset = f2;
entity.rotationYaw = f3;
entity.rotationPitch = f4;
entity.prevRotationYawHead = f5;
entity.rotationYawHead = f6;*/
GlStateManager.popMatrix();
RenderHelper.disableStandardItemLighting();
GlStateManager.disableRescaleNormal();
GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit);
GlStateManager.disableTexture2D();
GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit);
// GL11.glDisable(GL11.GL_LIGHTING);
}
@Override
public void onPageChange(GuiWiki gui, String pageName, Object... metadata){
if(metadata.length > 0 && metadata[0] instanceof Entity) {
curEntity = Util.getEntityForClass(((Entity)metadata[0]).getClass());
}
}
}
| 6,636 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
BlockAndItemWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/BlockAndItemWikiTab.java | package igwmod.gui.tabs;
import igwmod.api.WikiRegistry;
import igwmod.gui.GuiWiki;
import igwmod.gui.IPageLink;
import igwmod.gui.IReservedSpace;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedTexture;
import igwmod.lib.Textures;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
public class BlockAndItemWikiTab implements IWikiTab{
private static ItemStack drawingStack = ItemStack.EMPTY;
@Override
public String getName(){
return "igwmod.wikitab.blocksAndItems.name";
}
@Override
public ItemStack renderTabIcon(GuiWiki gui){
return new ItemStack(Blocks.GRASS);
}
@Override
public List<IReservedSpace> getReservedSpaces(){
List<IReservedSpace> reservedSpaces = new ArrayList<IReservedSpace>();
reservedSpaces.add(new LocatedTexture(Textures.GUI_ITEMS_AND_BLOCKS, 40, 74, 36, 144));
return reservedSpaces;
}
@Override
public List<IPageLink> getPages(int[] indexes){
List<ItemStack> itemStacks = WikiRegistry.getItemAndBlockPageEntries();
List<IPageLink> pages = new ArrayList<IPageLink>();
if(indexes == null) {
for(int i = 0; i < itemStacks.size(); i++) {
pages.add(new LocatedStack(itemStacks.get(i), 41 + i % 2 * 18, 75 + i / 2 * 18));
}
} else {
for(int i = 0; i < indexes.length; i++) {
pages.add(new LocatedStack(itemStacks.get(indexes[i]), 41 + i % 2 * 18, 75 + i / 2 * 18));
}
}
return pages;
}
@Override
public int pagesPerTab(){
return 16;
}
@Override
public int pagesPerScroll(){
return 2;
}
@Override
public int getSearchBarAndScrollStartY(){
return 61;
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){
if(!drawingStack.isEmpty()) {
GlStateManager.enableLighting();
RenderHelper.enableGUIStandardItemLighting();
if(drawingStack.getItem() instanceof ItemBlock) {
gui.renderRotatingBlockIntoGUI(gui, drawingStack, 55, 58, 2.8F);
} else {
GL11.glPushMatrix();
GL11.glTranslated(49, 20, 0);
GL11.glScaled(2.2, 2.2, 2.2);
Minecraft.getMinecraft().getRenderItem().renderItemAndEffectIntoGUI(drawingStack, 0, 0);
GL11.glPopMatrix();
}
}
}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){}
@Override
public void onMouseClick(GuiWiki gui, int mouseX, int mouseY, int mouseKey){}
@Override
public void onPageChange(GuiWiki gui, String pageName, Object... metadata){
if(metadata.length > 0 && metadata[0] instanceof ItemStack) {
drawingStack = (ItemStack)metadata[0];
}
}
}
| 3,164 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/IWikiTab.java | package igwmod.gui.tabs;
import java.util.List;
import igwmod.gui.GuiWiki;
import igwmod.gui.IPageLink;
import igwmod.gui.IReservedSpace;
import igwmod.gui.LocatedTexture;
import net.minecraft.item.ItemStack;
public interface IWikiTab{
/**
* The returned string will be displayed on the tooltip when you hover over the tab.
* @return
*/
public String getName();
/**
* Will be called by the GUI to render the tab. The render matrix will already be translated dependant on where this tab is.
* @return When you return an ItemStack, this stack will be drawn rotating. Returning ItemStack.EMPTY is valid, nothing will be drawn (you will).
*/
public ItemStack renderTabIcon(GuiWiki gui);
/**
* With this you can specify which spaces in the wikipage are prohibited for text to occur. This method is also used to add standard widgets,
* like images that need to exist on every wikipage of this tab. Just add a {@link LocatedTexture} to this list and it will be rendered.
* @return
*/
public List<IReservedSpace> getReservedSpaces();
/**
* In here you should return the full list of pages. This will also define how people will be able to navigate through pages on this tab.
* The most simplest way is to use {@link LinkedLocatedString}.
* @param pageIndexes : This array will be null when every existing page is requested (used for search queries). When specific pages are
* requested (as a result of a search query), this array will contain the indexes it wants of the list returner earlier. Return a list
* with only the elements of the indexes given. This way, you can decide where you want to put pagelinks (spacings, only vertical or in pairs
* of two) however you want. You're in charge on the location of each of the elements.
* @return
*/
public List<IPageLink> getPages(int[] pageIndexes);
/**
* The value returned defines how high the textfield will appear. On a basic page this is on the top of the screen, on the item/block & entity
* page this is somewhere in the middle.
* @return
*/
public int getSearchBarAndScrollStartY();
/**
* Return the amount of page links that fit on one page (it will allow scrolling if there are more pages than that).
* @return
*/
public int pagesPerTab();
/**
* How many elements (page links) are being scrolled per scroll. This is usually 1, but for the Item/Blocks tab this is 2 (to move two items at once per scroll).
* @return
*/
public int pagesPerScroll();
/**
*
* @param gui
* @param mouseX
* @param mouseY
*/
public void renderForeground(GuiWiki gui, int mouseX, int mouseY);
/**
*
* @param gui
* @param mouseX
* @param mouseY
*/
public void renderBackground(GuiWiki gui, int mouseX, int mouseY);
/**
*
* @param gui
* @param mouseX
* @param mouseY
* @param mouseKey
*/
public void onMouseClick(GuiWiki gui, int mouseX, int mouseY, int mouseKey);
/**
* Called when navigated to a page of this tab. pageName is the actual path of the .txt file. metadata can be empty, or containing an itemstack or Class<? extends Entity>
* @param gui
* @param pageName
* @param metadata
*/
public void onPageChange(GuiWiki gui, String pageName, Object... metadata);
}
| 3,444 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
BaseWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/BaseWikiTab.java | package igwmod.gui.tabs;
import java.util.ArrayList;
import java.util.List;
import igwmod.gui.GuiWiki;
import igwmod.gui.IPageLink;
import igwmod.gui.IReservedSpace;
import igwmod.gui.LocatedSectionString;
import igwmod.gui.LocatedString;
public abstract class BaseWikiTab implements IWikiTab{
protected List<String> pageEntries = new ArrayList<String>();
@Override
public List<IReservedSpace> getReservedSpaces(){
return null;
}
@Override
public List<IPageLink> getPages(int[] pageIndexes){
List<IPageLink> pages = new ArrayList<IPageLink>();
if(pageIndexes == null) {
for(int i = 0; i < pageEntries.size(); i++) {
if(pageEntries.get(i).startsWith("#")) {
pages.add(new LocatedSectionString(getPageName(pageEntries.get(i)), 80, 64 + 11 * i, false));
} else if(pageEntries.get(i).equals("")) {
pages.add(new LocatedString("", 80, 64 + 11 * i, 0, false));
} else {
pages.add(new LocatedString(getPageName(pageEntries.get(i).toLowerCase()), 80, 64 + 11 * i, false, getPageLocation(pageEntries.get(i).toLowerCase())));
}
}
} else {
for(int i = 0; i < pageIndexes.length; i++) {
if(pageEntries.get(pageIndexes[i]).startsWith("#")) {
pages.add(new LocatedSectionString(getPageName(pageEntries.get(pageIndexes[i]).toLowerCase()), 80, 64 + 11 * i, false).capTextWidth(pagesPerTab() > pageIndexes.length ? 100 : 77));
} else if(pageEntries.get(pageIndexes[i]).equals("")) {
pages.add(new LocatedString("", 80, 64 + 11 * i, 0, false));
} else {
pages.add(new LocatedString(getPageName(pageEntries.get(pageIndexes[i]).toLowerCase()), 80, 64 + 11 * i, false, getPageLocation(pageEntries.get(pageIndexes[i]).toLowerCase())).capTextWidth(pagesPerTab() > pageIndexes.length ? 100 : 77));
}
}
}
return pages;
}
protected void skipLine(){
pageEntries.add("");
}
protected void addSectionHeader(String header){
pageEntries.add("#" + header);
}
@Override
public int pagesPerTab(){
return 36;
}
@Override
public int pagesPerScroll(){
return 1;
}
@Override
public int getSearchBarAndScrollStartY(){
return 18;
}
@Override
public void renderForeground(GuiWiki gui, int mouseX, int mouseY){}
@Override
public void renderBackground(GuiWiki gui, int mouseX, int mouseY){}
@Override
public void onMouseClick(GuiWiki gui, int mouseX, int mouseY, int mouseKey){}
@Override
public void onPageChange(GuiWiki gui, String pageName, Object... metadata){}
protected abstract String getPageName(String pageEntry);
protected abstract String getPageLocation(String pageEntry);
}
| 2,964 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IGWWikiTab.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/gui/tabs/IGWWikiTab.java | package igwmod.gui.tabs;
import igwmod.ConfigHandler;
import igwmod.gui.GuiWiki;
import net.minecraft.client.resources.I18n;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
public class IGWWikiTab extends BaseWikiTab{
public IGWWikiTab(){
pageEntries.add("intro");
pageEntries.add("forServers");
if(ConfigHandler.debugMode) {
pageEntries.add("devIntro");
pageEntries.add("devItemAndBlock");
pageEntries.add("devPageCommands");
pageEntries.add("devForModders");
}
}
@Override
public String getName(){
return "igwmod.wikitab.igwmod.name";
}
@Override
public ItemStack renderTabIcon(GuiWiki gui){
return new ItemStack(Blocks.LOG);
}
@Override
protected String getPageName(String pageEntry){
return I18n.format("igwtab.entry." + pageEntry);
}
@Override
protected String getPageLocation(String pageEntry){
return "igwmod:igwtab/" + pageEntry;
}
}
| 1,040 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
FurnaceRetrievalEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/FurnaceRetrievalEvent.java | package igwmod.api;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.Event;
public class FurnaceRetrievalEvent extends Event{
public ItemStack inputStack;
public ItemStack resultStack;
public final String key;
public FurnaceRetrievalEvent(String key){
this.key = key;
}
}
| 341 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ItemWikiEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/ItemWikiEvent.java | package igwmod.api;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* Event fired on MinecraftForge.EVENT_BUS when the player opens the IGW GUI by looking at an item in another GUI and pressing 'i' or when the player
* navigates between wikipages. This event is also fired when looking
* at item entities. For info about the pageOpened field, look at {@link BlockWikiEvent}
* when you don't alter the pageOpened field, it will default to assets/igwmod/wiki/item/<itemStack.getUnlocalizedName()>
*/
public class ItemWikiEvent extends Event{
public final ItemStack itemStack; //you can change the drawn stack in the top left corner by altering this stack.
public String pageOpened;
public ItemWikiEvent(ItemStack itemStack, String pageOpened){
this.itemStack = itemStack;
this.pageOpened = pageOpened;
}
}
| 894 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
VariableRetrievalEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/VariableRetrievalEvent.java | package igwmod.api;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* This event is fired on MinecraftForge.EVENT_BUS when a wikipage contains a [variable{<variableName>}] block, in which the <variableName is a string that is passed to this event.
* This event can be used to retrieve values that you want to display on a wikipage that are dynamic, for example config options, or parameters that are prone to change.
* You are responsible for a decent variable name. I'd suggest prefixing it with your modid to prevent collisions with other mods' variables.
* If no subscriber has passed a return value for a variable name, it will be replaced by the variable name itself.
*/
public class VariableRetrievalEvent extends Event{
public final String variableName;//The name passed via the wikipage's [variable] command.
public String replacementValue; //The string value you should set with a replacement, like '15%', '1.0 bar'.
public VariableRetrievalEvent(String variableName){
this.variableName = variableName;
}
}
| 1,062 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
PageChangeEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/PageChangeEvent.java | package igwmod.api;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* Fired on MinecraftForge.EVENT_BUS when the page changes. This can be used to intercept any page that is being tried to be looked up from a .txt file, and supply it a custom (language) string instead.
*/
public class PageChangeEvent extends Event{
/**
* The default (partial) resource location of the page opened. examples: block/pistonBase, block/workbench Change to make IGW-Mod look for a different resource location.
*/
public String currentFile;
/**
* Custom page text. When left null, the currentFile resource location will be used to look up the text from a .txt file. If not null, this
* text will be used instead.
*/
public List<String> pageText;
/**
* Will not be null when the page is opened via in-world block looking up, or when the player hovers over an item stack in a GUI and opens the wiki.
*/
public ItemStack associatedStack;
/**
* Will not be null when it's an entity that has been looked up.
*/
public Entity associatedEntity;
public PageChangeEvent(String currentFile, ItemStack associatedStack, Entity associatedEntity){
this.currentFile = currentFile;
this.associatedStack = associatedStack;
this.associatedEntity = associatedEntity;
}
}
| 1,459 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
BlockWikiEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/BlockWikiEvent.java | package igwmod.api;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.client.FMLClientHandler;
/**
* This event will be fired on MinecraftForge.EVENT_BUS when a player opens the wiki GUI while looking at a block in the world. Your job as subscriber is to change the
* pageOpened field when you find the right block. If no subscriber changes the pageOpened field, IGW will try to open a page at
* assets/igwmod/wiki/block/drawnStack.getUnlocalizedName()>.
*/
public class BlockWikiEvent extends WorldEvent{
public final BlockPos pos;
public final IBlockState blockState;
public ItemStack itemStackPicked;
public ItemStack drawnStack; //ItemStack that is drown in the top left corner of the GUI.
public String pageOpened; //current page this gui will go to. It contains the default location, but can be changed.
public BlockWikiEvent(World world, BlockPos pos){
super(world);
this.pos = pos;
blockState = world.getBlockState(pos);
try {
itemStackPicked = blockState.getBlock().getPickBlock(blockState, FMLClientHandler.instance().getClient().objectMouseOver, world, pos, FMLClientHandler.instance().getClientPlayerEntity());
} catch(Throwable e) {}//FMP parts have the habit to throw a ClassCastException.
drawnStack = !itemStackPicked.isEmpty() ? itemStackPicked : new ItemStack(blockState.getBlock(), 1, blockState.getBlock().getMetaFromState(blockState));
}
}
| 1,644 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
WikiRegistry.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/WikiRegistry.java | package igwmod.api;
import igwmod.WikiHooks;
import igwmod.gui.GuiWiki;
import igwmod.gui.tabs.IWikiTab;
import igwmod.gui.tabs.ServerWikiTab;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.oredict.OreDictionary;
public class WikiRegistry{
private static List<Map.Entry<String, ItemStack>> itemAndBlockPageEntries = new ArrayList<Map.Entry<String, ItemStack>>();
private static Map<Class<? extends Entity>, String> entityPageEntries = new HashMap<Class<? extends Entity>, String>();
public static List<IRecipeIntegrator> recipeIntegrators = new ArrayList<IRecipeIntegrator>();
public static List<ITextInterpreter> textInterpreters = new ArrayList<ITextInterpreter>();
private static IWikiHooks wikiHooks = new WikiHooks();
public static void registerWikiTab(IWikiTab tab){
if(tab instanceof ServerWikiTab) {
for(IWikiTab t : GuiWiki.wikiTabs) {
if(t instanceof ServerWikiTab) {
GuiWiki.wikiTabs.remove(t);
break;
}
}
GuiWiki.wikiTabs.add(0, tab);
} else {
GuiWiki.wikiTabs.add(tab);
}
}
public static void registerBlockAndItemPageEntry(ItemStack stack){
if(stack.isEmpty() || stack.getItem() == null) throw new IllegalArgumentException("Can't register null items");
registerBlockAndItemPageEntry(stack, stack.getUnlocalizedName().replace("tile.", "block/").replace("item.", "item/"));
}
public static void registerBlockAndItemPageEntry(Block block, String page){
registerBlockAndItemPageEntry(new ItemStack(block, 1, OreDictionary.WILDCARD_VALUE), page);
}
public static void registerBlockAndItemPageEntry(Item item, String page){
registerBlockAndItemPageEntry(new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE), page);
}
public static void registerBlockAndItemPageEntry(ItemStack stack, String page){
itemAndBlockPageEntries.add(new AbstractMap.SimpleEntry(page, stack));
}
public static void registerEntityPageEntry(Class<? extends Entity> entityClass){
// registerEntityPageEntry(entityClass, "entity/" + EntityList.CLASS_TO_NAME.get(entityClass));
registerEntityPageEntry(entityClass, "entity/" + EntityList.getKey(entityClass).getResourcePath());
}
public static void registerEntityPageEntry(Class<? extends Entity> entityClass, String page){
entityPageEntries.put(entityClass, page);
}
public static void registerRecipeIntegrator(IRecipeIntegrator recipeIntegrator){
recipeIntegrators.add(recipeIntegrator);
}
public static void registerTextInterpreter(ITextInterpreter textInterpreter){
textInterpreters.add(textInterpreter);
}
public static String getPageForItemStack(ItemStack stack){
for(Map.Entry<String, ItemStack> entry : itemAndBlockPageEntries) {
if(entry.getValue().isItemEqual(stack) && ItemStack.areItemStackTagsEqual(entry.getValue(), stack)) return entry.getKey();
}
for(Map.Entry<String, ItemStack> entry : itemAndBlockPageEntries) {
if(OreDictionary.itemMatches(entry.getValue(), stack, false)) return entry.getKey();
}
return null;
}
public static String getPageForEntityClass(Class<? extends Entity> entityClass){
String page = entityPageEntries.get(entityClass);
if(page != null) {
return page;
} else {
ResourceLocation entityName = EntityList.getKey(entityClass);
return entityName == null ? null : "entity/" + entityName.getResourcePath();
}
}
public static List<ItemStack> getItemAndBlockPageEntries(){
// List<ItemStack> entries = new ArrayList<ItemStack>();
NonNullList<ItemStack> entries = NonNullList.create();
for(Map.Entry<String, ItemStack> entry : itemAndBlockPageEntries) {
if(entry.getValue().getItemDamage() == OreDictionary.WILDCARD_VALUE) {
entry.getValue().getItem().getSubItems(CreativeTabs.SEARCH, entries);
} else {
entries.add(entry.getValue());
}
}
return entries;
}
public static List<Class<? extends Entity>> getEntityPageEntries(){
List<Class<? extends Entity>> entries = new ArrayList<Class<? extends Entity>>();
for(Class<? extends Entity> entityClass : entityPageEntries.keySet()) {
entries.add(entityClass);
}
return entries;
}
public static IWikiHooks getWikiHooks(){
return wikiHooks;
}
}
| 5,046 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
CraftingRetrievalEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/CraftingRetrievalEvent.java | package igwmod.api;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* This event is fired on MinecraftForge.EVENT_BUS when a wikipage contains a [crafting{key=recipeName}] block, in which the 'recipeName' is a string that is passed to this event.
* This event is a way to save you the time of writing a manual recipe, like
* [crafting{www,cic,crc,w=block/wood,c=block/stonebrick,i=item/ingotIron,r=block/redstoneDust}block/pistonBase] for a piston.
* With this event, you can write [crafting{piston}]. IGW detects this, and fires this event with the 'piston' key. You see the key, and set
* the 'recipe' field to the ShapelessRecipes of the piston recipe. Instead of searching for the instance of this recipe, you can keep a
* reference to it when you register the recipe (GameRegistry#addShapedRecipe(ItemStack, Object...) returns an IRecipe).
*/
public class CraftingRetrievalEvent extends Event{
public IRecipe recipe; //Only pass ShapedRecipes, ShapedOreRecipe or ShapelessRecipes (or I'll throw an exception, mhoehaha!)
public final String key;
public CraftingRetrievalEvent(String key){
this.key = key;
}
}
| 1,206 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IRecipeIntegrator.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/IRecipeIntegrator.java | package igwmod.api;
import java.util.List;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
/**
* Implement this class and register it to the WikiRegistry to add support for custom recipes, like Pressure Chambers, Carpenters, Assembly Tables, ...
* You could also implement this interface for general commands that might not have to do with recipes at all.
*/
public interface IRecipeIntegrator{
/**
* Return the name of the command here. for normal crafting recipes this is 'crafting', and for furnace recipes 'furnace'
* @return
*/
public String getCommandKey();
/**
* Called as soon as the parsed command started with the command key of this instance.
* @param arguments arguements as strings, seperated by the ',' character. These have been trimmed already. these are the arguments between the '{ }' tags.
* @param reservedSpaces anything added in here will cause the text to wrap around it.
* @param locatedStrings For additional info to display with the recipe.
* @param locatedStacks For recipes you can add stacks to this. These are interfacable, meaning that you can press 'R' and 'U' with NEI, and press 'I' to navigate to the wikipage.
* @param locatedTextures If you add a recipe handler, add a texture here as underlay for the items.
* @throws IllegalArgumentException throw this when the wiki writer tries to give illegal arguments. It won't crash the game, instead it will display the error on the generated page.
*/
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException;
}
| 1,810 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
EntityWikiEvent.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/EntityWikiEvent.java | package igwmod.api;
import net.minecraft.entity.Entity;
import net.minecraftforge.event.entity.EntityEvent;
/**
* Event fired on MinecraftForge.EVENT_BUS when the IGW GUI gets opened by looking at an entity and pressing 'i'. You could change the entity displayed in the
* top left corner by setting the 'entity' field. If you want the default entity, don't change it.
* When you don't change pageOpened, it will default to assets/igwmod/wiki/entity/<Entity.getEntityString(entity)>
* For info about the pageOpened field, look at {@link BlockWikiEvent}.
*/
public class EntityWikiEvent extends EntityEvent{
public String pageOpened; //current page this gui will go to. It contains the default location, but can be changed.
public EntityWikiEvent(Entity entity){
super(entity);
}
}
| 811 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IWikiHooks.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/IWikiHooks.java | package igwmod.api;
public interface IWikiHooks{
/**
* Shows the Wiki gui at the given wiki location.
* @param pageLocation location of the page, for example, 'minecraft:block/grass'
*/
public void showWikiGui(String pageLocation);
}
| 258 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IGWSupportNotifier.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/IGWSupportNotifier.java | package igwmod.api;
import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* This class is meant to be copied to your own mod which implements IGW-Mod. When properly implemented by instantiating a new instance somewhere in your mod
* loading stage, this will notify the player when it doesn't have IGW in the instance. It also needs to have the config option enabled to
* notify the player. This config option will be generated in its own config file.
* @author MineMaarten https:github.com/MineMaarten/IGW-mod
*/
public class IGWSupportNotifier{
private String supportingMod;
private static final String LATEST_DL_URL = "https://minecraft.curseforge.com/projects/in-game-wiki-mod/files/latest";
/**
* Needs to be instantiated somewhere in your mod's loading stage.
*/
public IGWSupportNotifier(){
if(FMLCommonHandler.instance().getSide() == Side.CLIENT && !Loader.isModLoaded("IGWMod")) {
File dir = new File(".", "config");
Configuration config = new Configuration(new File(dir, "IGWMod.cfg"));
config.load();
if(config.get(Configuration.CATEGORY_GENERAL, "enable_missing_notification", true, "When enabled, this will notify players when IGW-Mod is not installed even though mods add support.").getBoolean()) {
ModContainer mc = Loader.instance().activeModContainer();
String modid = mc.getModId();
List<ModContainer> loadedMods = Loader.instance().getActiveModList();
for(ModContainer container : loadedMods) {
if(container.getModId().equals(modid)) {
supportingMod = container.getName();
MinecraftForge.EVENT_BUS.register(this);
ClientCommandHandler.instance.registerCommand(new CommandDownloadIGW());
break;
}
}
}
config.save();
}
}
@SubscribeEvent
public void onPlayerJoin(TickEvent.PlayerTickEvent event){
if(event.player.world.isRemote && event.player == FMLClientHandler.instance().getClientPlayerEntity()) {
event.player.sendMessage(ITextComponent.Serializer.jsonToComponent("[\"" + TextFormatting.GOLD + "The mod " + supportingMod + " is supporting In-Game Wiki mod. " + TextFormatting.GOLD + "However, In-Game Wiki isn't installed! " + "[\"," + "{\"text\":\"Download Latest\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/igwmod_download\"}}," + "\"]\"]"));
FMLCommonHandler.instance().bus().unregister(this);
}
}
private class CommandDownloadIGW extends CommandBase{
@Override
public int getRequiredPermissionLevel(){
return -100;
}
@Override
public String getName(){
return "igwmod_download";
}
@Override
public String getUsage(ICommandSender p_71518_1_){
return getName();
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException{
new ThreadDownloadIGW();
}
}
private class ThreadDownloadIGW extends Thread{
public ThreadDownloadIGW(){
setName("IGW-Mod Download Thread");
start();
}
@Override
public void run(){
try {
if(Minecraft.getMinecraft().player != null) Minecraft.getMinecraft().player.sendMessage(new TextComponentString("Downloading IGW-Mod..."));
URL url = new URL(LATEST_DL_URL);
URLConnection connection = url.openConnection();
connection.connect();
File dir = new File(".", "mods");
File tempFile = File.createTempFile("IGW-Mod.jar", "");
FileUtils.copyURLToFile(url, tempFile);
ZipFile jar = new ZipFile(tempFile.getAbsolutePath());
Enumeration<? extends ZipEntry> entries = jar.entries();
InputStream mcmodInfo = null;
while(entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if(entry.getName().equals("mcmod.info")) {
mcmodInfo = jar.getInputStream(entry);
break;
}
}
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject)((JsonArray)parser.parse(IOUtils.toString(mcmodInfo))).get(0);
jar.close();
String version = obj.get("version").getAsString();
String mcVersion = obj.get("mcversion").getAsString();
File renamedFile = new File(String.format("." + File.separator + "mods" + File.separator + "IGW-Mod-%s-%s-universal.jar", mcVersion, version));
FileUtils.copyFile(tempFile, renamedFile);
if(Minecraft.getMinecraft().player != null) Minecraft.getMinecraft().player.sendMessage(new TextComponentString(TextFormatting.GREEN + "Successfully downloaded. Restart Minecraft to apply."));
Desktop.getDesktop().open(dir);
if(!Loader.MC_VERSION.equals(mcVersion)) {
if(Minecraft.getMinecraft().player != null) Minecraft.getMinecraft().player.sendMessage(new TextComponentString(TextFormatting.RED + "The version of Minecraft you are running doesn't seem to match the version of IGW-Mod that has been downloaded. The mod may not work."));
}
finalize();
} catch(Throwable e) {
e.printStackTrace();
if(Minecraft.getMinecraft().player != null) Minecraft.getMinecraft().player.sendMessage(new TextComponentString(TextFormatting.RED + "Failed to download"));
try {
finalize();
} catch(Throwable e1) {
e1.printStackTrace();
}
}
}
}
}
| 7,349 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ITextInterpreter.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/api/ITextInterpreter.java | package igwmod.api;
import java.util.List;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import net.minecraft.client.gui.FontRenderer;
/**
* When IGWMod's internal markup language doesn't suffice, or does not suit you, you can plugin your own text interpreter with this.
* If you've come up with a nice interpeter, and want to help others with it as well, feel free to create a Pull Request, to put it in natively into IGW-Mod :).
*/
public interface ITextInterpreter{
/**
* Is called when a page is loaded. Giving the raw page contents, and lists you can fill to lay out the page, all the tools are needed to interpret the page how you want to.
* All lists (reservedSpaces, locatedStrings, locatedStacks, locatedTextures) can have elements in upon invoking, these need to be respected with text wrapping.
* @param fontRenderer
* @param rawText
* @param reservedSpaces Rectangles on the screen where text is prohibited to appear (it needs to be wrapped around).
* @param locatedStrings The actual text, plus location. Can be special, such as links/colors.
* @param locatedStacks Item stacks that need to appear on the screen. They have item tooltips and can be interacted with with NEI. They, like reservedSpaces, need to have text wrapped around them, instead of text going through them.
* @param locatedTextures images, basically. They, like reservedSpaces, need to have text wrapped around them, instead of text going through them.
* @return true if you interpreted the text, false if you haven't. When returning true, no other text interpreters will run. If returned false, they will. It's recommended to do like a check at the beginning of the file that contains a marker that allows the interpeter to run, only for your pages.
*/
public boolean interpret(FontRenderer fontRenderer, List<String> rawText, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures);
}
| 2,096 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
TooltipOverlayHandler.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/render/TooltipOverlayHandler.java | package igwmod.render;
import org.lwjgl.input.Keyboard;
import igwmod.ClientProxy;
import igwmod.ConfigHandler;
import igwmod.IGWMod;
import igwmod.TickHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class TooltipOverlayHandler{
@SubscribeEvent
public void tickEnd(TickEvent.RenderTickEvent event){
if(event.phase == TickEvent.Phase.END && TickHandler.showTooltip() && ConfigHandler.shouldShowTooltip && FMLClientHandler.instance().getClient().inGameHasFocus && IGWMod.proxy.getPlayer().world != null) {
Minecraft mc = FMLClientHandler.instance().getClient();
ScaledResolution sr = new ScaledResolution(mc);
FontRenderer fontRenderer = FMLClientHandler.instance().getClient().fontRenderer;
String objectName = TickHandler.getCurrentObjectName();
String moreInfo = "'" + Keyboard.getKeyName(ClientProxy.openInterfaceKey.getKeyCode()) + "' for more info";
fontRenderer.drawString(objectName, sr.getScaledWidth() / 2 - fontRenderer.getStringWidth(objectName) / 2, sr.getScaledHeight() / 2 - 20, 0xFFFFFFFF);
fontRenderer.drawString(moreInfo, sr.getScaledWidth() / 2 - fontRenderer.getStringWidth(moreInfo) / 2, sr.getScaledHeight() / 2 - 10, 0xFFFFFFFF);
}
}
}
| 1,556 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IntegratorImage.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/recipeintegration/IntegratorImage.java | package igwmod.recipeintegration;
import java.util.List;
import igwmod.TextureSupplier;
import igwmod.api.IRecipeIntegrator;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import igwmod.gui.LocatedTexture;
public class IntegratorImage implements IRecipeIntegrator{
@Override
public String getCommandKey(){
return "image";
}
@Override
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
if(arguments.length != 3 && arguments.length != 4) throw new IllegalArgumentException("The code needs to contain 3 or 4 parameters: x, y, [scale,] , texture location. It now contains " + arguments.length + ".");
int[] coords = new int[2];
double scale = 1;
try {
for(int i = 0; i < 2; i++)
coords[i] = Integer.parseInt(arguments[i]);
if(arguments.length == 4) {
scale = Double.parseDouble(arguments[2]);
}
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The code contains an invalid number! Check for spaces or invalid characters.");
}
LocatedTexture texture = new LocatedTexture(TextureSupplier.getTexture(arguments[arguments.length - 1]), coords[0], coords[1]);
texture.width = (int)(texture.width * scale);
texture.height = (int)(texture.height * scale);
locatedTextures.add(texture);
}
}
| 1,646 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IntegratorComment.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/recipeintegration/IntegratorComment.java | package igwmod.recipeintegration;
import java.util.List;
import igwmod.api.IRecipeIntegrator;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
public class IntegratorComment implements IRecipeIntegrator{
@Override
public String getCommandKey(){
return "comment";
}
@Override
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
//Just ignore it, which is what a comment is doing ;).
}
}
| 676 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IntegratorCraftingRecipe.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/recipeintegration/IntegratorCraftingRecipe.java | package igwmod.recipeintegration;
import igwmod.TextureSupplier;
import igwmod.WikiUtils;
import igwmod.api.CraftingRetrievalEvent;
import igwmod.api.IRecipeIntegrator;
import igwmod.gui.GuiWiki;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import igwmod.gui.LocatedTexture;
import igwmod.lib.IGWLog;
import igwmod.lib.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
public class IntegratorCraftingRecipe implements IRecipeIntegrator{
public static Map<String, IRecipe> autoMappedRecipes = new HashMap<String, IRecipe>();
public static final int STACKS_X_OFFSET = 1;
public static final int STACKS_Y_OFFSET = 1;
private static final int RESULT_STACK_X_OFFSET = 95;
private static final int RESULT_STACK_Y_OFFSET = STACKS_Y_OFFSET + 18;
@Override
public String getCommandKey(){
return "crafting";
}
@Override
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
if(arguments.length < 3) throw new IllegalArgumentException("Code needs at least 3 arguments!");
int x;
try {
x = Integer.parseInt(arguments[0]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The first parameter (the x coordinate) contains an invalid number. Check for spaces or invalid characters!");
}
int y;
try {
y = Integer.parseInt(arguments[1]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The second parameter (the y coordinate) contains an invalid number. Check for spaces or invalid characters!");
}
locatedTextures.add(new LocatedTexture(TextureSupplier.getTexture(Paths.MOD_ID_WITH_COLON + "textures/GuiCrafting.png"), x, y, (int)(116 / GuiWiki.TEXT_SCALE), (int)(54 / GuiWiki.TEXT_SCALE)));
if(arguments[2].startsWith("key=")) {
if(arguments.length != 3) throw new IllegalArgumentException("An RecipeRetrievalEvent crafting code can only have 3 parameters: x, y and the key!");
addAutomaticCraftingRecipe(arguments[2], locatedStacks, locatedTextures, locatedStrings, (int)(x * GuiWiki.TEXT_SCALE), (int)(y * GuiWiki.TEXT_SCALE));
} else {
addManualCraftingRecipe(arguments, locatedStacks, locatedTextures, (int)(x * GuiWiki.TEXT_SCALE), (int)(y * GuiWiki.TEXT_SCALE));
}
}
/**
* Check RecipeRetrievalEvent to see what this method does.
* @param y
* @param x
*/
private void addAutomaticCraftingRecipe(String code, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures, List<LocatedString> locatedStrings, int x, int y) throws IllegalArgumentException{
String key = code.substring(4);
CraftingRetrievalEvent recipeEvent = new CraftingRetrievalEvent(key);
IRecipe autoMappedRecipe = autoMappedRecipes.get(key);
if(autoMappedRecipe != null) {
recipeEvent.recipe = autoMappedRecipe;
} else {
MinecraftForge.EVENT_BUS.post(recipeEvent);
}
if(recipeEvent.recipe instanceof ShapedRecipes) {
ShapedRecipes recipe = (ShapedRecipes)recipeEvent.recipe;
for(int i = 0; i < recipe.recipeHeight; i++) {
for(int j = 0; j < recipe.recipeWidth; j++) {
Ingredient ingredientStack = recipe.recipeItems.get(i * recipe.recipeWidth + j);
if(ingredientStack.getMatchingStacks().length > 0) {
locatedStacks.add(new LocatedStack(ingredientStack.getMatchingStacks()[0], x + STACKS_X_OFFSET + j * 18, y + STACKS_Y_OFFSET + i * 18));
}
}
}
locatedStacks.add(new LocatedStack(recipe.getRecipeOutput(), x + RESULT_STACK_X_OFFSET, y + RESULT_STACK_Y_OFFSET));
locatedStrings.add(new LocatedString(I18n.format("igwmod.gui.crafting.shaped"), x * 2 + 120, y * 2 + 10, 0xFF000000, false));
} else if(recipeEvent.recipe instanceof ShapedOreRecipe) {
ShapedOreRecipe recipe = (ShapedOreRecipe)recipeEvent.recipe;
int recipeHeight = 0;
int recipeWidth = 0;
try {
recipeHeight = ReflectionHelper.findField(ShapedOreRecipe.class, "height").getInt(recipe);
recipeWidth = ReflectionHelper.findField(ShapedOreRecipe.class, "width").getInt(recipe);
} catch(Exception e) {
IGWLog.error("Something went wrong while trying to get the width and height fields from ShapedOreRecipe!");
e.printStackTrace();
}
for(int i = 0; i < recipeHeight; i++) {
for(int j = 0; j < recipeWidth; j++) {
Ingredient ingredient = recipe.getIngredients().get(i * recipeWidth + j);
if(ingredient.getMatchingStacks().length > 0) {
ItemStack ingredientStack = ingredient.getMatchingStacks()[0];
//ingredient instanceof ItemStack ? (ItemStack)ingredient : ((List<ItemStack>)ingredient).get(0);
if(!ingredientStack.isEmpty()) {
locatedStacks.add(new LocatedStack(ingredientStack, x + STACKS_X_OFFSET + j * 18, y + STACKS_Y_OFFSET + i * 18));
}
}
}
}
locatedStacks.add(new LocatedStack(recipe.getRecipeOutput(), x + RESULT_STACK_X_OFFSET, y + RESULT_STACK_Y_OFFSET));
locatedStrings.add(new LocatedString(I18n.format("igwmod.gui.crafting.shaped"), x * 2 + 120, y * 2 + 10, 0xFF000000, false));
} else if(recipeEvent.recipe instanceof ShapelessRecipes) {
ShapelessRecipes recipe = (ShapelessRecipes)recipeEvent.recipe;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i * 3 + j < recipe.recipeItems.size()) {
Ingredient ingredient = recipe.recipeItems.get(i * 3 + j);
ItemStack ingredientStack = ingredient.getMatchingStacks()[0];
if(!ingredientStack.isEmpty()) {
locatedStacks.add(new LocatedStack(ingredientStack, x + STACKS_X_OFFSET + j * 18, y + STACKS_Y_OFFSET + i * 18));
}
}
}
}
locatedStacks.add(new LocatedStack(recipe.getRecipeOutput(), x + RESULT_STACK_X_OFFSET, y + RESULT_STACK_Y_OFFSET));
locatedStrings.add(new LocatedString(I18n.format("igwmod.gui.crafting.shapeless"), x * 2 + 120, y * 2 + 10, 0xFF000000, false));
} else if(recipeEvent.recipe instanceof ShapelessOreRecipe) {
ShapelessOreRecipe recipe = (ShapelessOreRecipe)recipeEvent.recipe;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i * 3 + j < recipe.getIngredients().size()) {
Ingredient ingredient = recipe.getIngredients().get(i * 3 + j);
if(ingredient != null) {
ItemStack ingredientStack = ingredient.getMatchingStacks()[0];
//ingredient instanceof ItemStack ? (ItemStack)ingredient : ((List<ItemStack>)ingredient).get(0);
if(!ingredientStack.isEmpty()) {
locatedStacks.add(new LocatedStack(ingredientStack, x + STACKS_X_OFFSET + j * 18, y + STACKS_Y_OFFSET + i * 18));
}
}
}
}
}
locatedStacks.add(new LocatedStack(recipe.getRecipeOutput(), x + RESULT_STACK_X_OFFSET, y + RESULT_STACK_Y_OFFSET));
locatedStrings.add(new LocatedString(I18n.format("igwmod.gui.crafting.shapeless"), x * 2 + 120, y * 2 + 10, 0xFF000000, false));
} else if(recipeEvent.recipe == null) {
throw new IllegalArgumentException("RecipeRetrievalEvent: For the given key, no subscriber returned a recipe! key = " + key);
} else {
throw new IllegalArgumentException("RecipeRetrievalEvent: Don't pass anything other than ShapedRecipes, ShapedOreRecipes, ShapelessRecipes or ShapelessOreRecipe! key = " + key);
}
}
private void addManualCraftingRecipe(String[] codeParts, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures, int x, int y) throws IllegalArgumentException{
String[] ingredients = new String[codeParts.length - 3];
System.arraycopy(codeParts, 3, ingredients, 0, codeParts.length - 3);
// ingredients[codeParts.length - 2] = lastTwoArguments[0];
String result = codeParts[2];
Map<String, ItemStack> ingredientMap = new HashMap<>();
for(int i = 3; i < ingredients.length; i++) {
String[] ingredient = ingredients[i].split("=");
ingredientMap.put(ingredient[0], WikiUtils.getStackFromName(ingredient[1]));
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
ItemStack ingredientStack = ingredientMap.getOrDefault(ingredients[i].substring(j, j + 1), ItemStack.EMPTY);
if(!ingredientStack.isEmpty()) {
locatedStacks.add(new LocatedStack(ingredientStack, x + STACKS_X_OFFSET + j * 18, y + STACKS_Y_OFFSET + i * 18));
}
}
}
ItemStack resultStack = WikiUtils.getStackFromName(result);
if(!resultStack.isEmpty()) {
locatedStacks.add(new LocatedStack(resultStack, x + RESULT_STACK_X_OFFSET, y + RESULT_STACK_Y_OFFSET));
}
}
}
| 10,400 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IntegratorStack.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/recipeintegration/IntegratorStack.java | package igwmod.recipeintegration;
import java.util.List;
import igwmod.WikiUtils;
import igwmod.api.IRecipeIntegrator;
import igwmod.gui.GuiWiki;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import net.minecraft.item.ItemStack;
public class IntegratorStack implements IRecipeIntegrator{
@Override
public String getCommandKey(){
return "stack";
}
@Override
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
if(arguments.length != 3) throw new IllegalArgumentException("stack command takes 3 arguments! Currently it has " + arguments.length);
int x;
try {
x = Integer.parseInt(arguments[0]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The first parameter (the x coordinate) contains an invalid number. Check for invalid characters!");
}
int y;
try {
y = Integer.parseInt(arguments[1]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The second parameter (the y coordinate) contains an invalid number. Check for invalid characters!");
}
ItemStack stack = WikiUtils.getStackFromName(arguments[2]);
if(stack.isEmpty()) throw new IllegalArgumentException("Item not found for the name " + arguments[2]);
locatedStacks.add(new LocatedStack(stack, (int)(x * GuiWiki.TEXT_SCALE), (int)(y * GuiWiki.TEXT_SCALE)));
}
}
| 1,692 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
IntegratorFurnace.java | /FileExtraction/Java_unseen/MineMaarten_IGW-mod/src/igwmod/recipeintegration/IntegratorFurnace.java | package igwmod.recipeintegration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import igwmod.TextureSupplier;
import igwmod.WikiUtils;
import igwmod.api.FurnaceRetrievalEvent;
import igwmod.api.IRecipeIntegrator;
import igwmod.gui.GuiWiki;
import igwmod.gui.IReservedSpace;
import igwmod.gui.IWidget;
import igwmod.gui.LocatedStack;
import igwmod.gui.LocatedString;
import igwmod.gui.LocatedTexture;
import igwmod.lib.Paths;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
public class IntegratorFurnace implements IRecipeIntegrator{
public static Map<String, ItemStack> autoMappedFurnaceRecipes = new HashMap<String, ItemStack>();
@Override
public String getCommandKey(){
return "furnace";
}
@Override
public void onCommandInvoke(String[] arguments, List<IReservedSpace> reservedSpaces, List<LocatedString> locatedStrings, List<LocatedStack> locatedStacks, List<IWidget> locatedTextures) throws IllegalArgumentException{
if(arguments.length != 3 && arguments.length != 4) throw new IllegalArgumentException("Code needs to contain 3 or 4 arguments: x, y, inputstack, outputstack. It now contains " + arguments.length + ".");
int x;
try {
x = Integer.parseInt(arguments[0]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The first parameter (the x coordinate) contains an invalid number. Check for invalid characters!");
}
int y;
try {
y = Integer.parseInt(arguments[1]);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("The second parameter (the y coordinate) contains an invalid number. Check for invalid characters!");
}
locatedTextures.add(new LocatedTexture(TextureSupplier.getTexture(Paths.MOD_ID_WITH_COLON + "textures/GuiFurnace.png"), x, y, (int)(82 / GuiWiki.TEXT_SCALE), (int)(54 / GuiWiki.TEXT_SCALE)));
x = (int)(x * GuiWiki.TEXT_SCALE);
y = (int)(y * GuiWiki.TEXT_SCALE);
ItemStack inputStack = ItemStack.EMPTY;
ItemStack resultStack = ItemStack.EMPTY;
if(arguments[2].startsWith("key=")) {
String resultStackCode = arguments[2].substring(4);
inputStack = autoMappedFurnaceRecipes.get(resultStackCode);
if(!inputStack.isEmpty()) {
resultStack = WikiUtils.getStackFromName(resultStackCode);
} else {
FurnaceRetrievalEvent recipeEvent = new FurnaceRetrievalEvent(resultStackCode);
MinecraftForge.EVENT_BUS.post(recipeEvent);
inputStack = recipeEvent.inputStack;
resultStack = recipeEvent.resultStack;
}
} else {
inputStack = WikiUtils.getStackFromName(arguments[2]);
resultStack = WikiUtils.getStackFromName(arguments[3]);
}
if(!inputStack.isEmpty()) {
locatedStacks.add(new LocatedStack(inputStack, x + IntegratorCraftingRecipe.STACKS_X_OFFSET, y + IntegratorCraftingRecipe.STACKS_Y_OFFSET));
}
if(!resultStack.isEmpty()) {
locatedStacks.add(new LocatedStack(resultStack, x + IntegratorCraftingRecipe.STACKS_X_OFFSET + 60, y + IntegratorCraftingRecipe.STACKS_Y_OFFSET + 18));
}
}
}
| 3,352 | Java | .java | MineMaarten/IGW-mod | 16 | 20 | 10 | 2013-12-10T22:48:16Z | 2018-04-14T15:48:51Z |
ConfirmDialog.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/ConfirmDialog.java | package com.germainz.crappalinks;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class ConfirmDialog extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String uri = getIntent().getStringExtra("uri");
DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.putExtra("crappalinks", "");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_confirm_open) + uri)
.setPositiveButton(R.string.dialog_yes, clickListener)
.setNegativeButton(R.string.dialog_no, clickListener)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
})
.show();
}
}
| 1,737 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
Preferences.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/Preferences.java | package com.germainz.crappalinks;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
public class Preferences extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.prefs);
Preference prefShowAppIcon = findPreference("pref_show_app_icon");
prefShowAppIcon.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
int state = (Boolean) newValue ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
final ComponentName alias = new ComponentName(getActivity(),
"com.germainz.crappalinks.Preferences-Alias");
PackageManager packageManager = getActivity().getPackageManager();
packageManager.setComponentEnabledSetting(alias, state, PackageManager.DONT_KILL_APP);
return true;
}
});
CheckBoxPreference prefUseLongUrl = (CheckBoxPreference) findPreference("pref_use_long_url");
findPreference("pref_resolve_all_when").setEnabled(!prefUseLongUrl.isChecked());
prefUseLongUrl.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
findPreference("pref_resolve_all_when").setEnabled(!(Boolean) newValue);
return true;
}
});
}
}
} | 2,482 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
CrappaLinks.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/CrappaLinks.java | package com.germainz.crappalinks;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XSharedPreferences;
public class CrappaLinks implements IXposedHookZygoteInit {
private final static XSharedPreferences PREFS = new XSharedPreferences("com.germainz.crappalinks");
private final static boolean PREF_UNSHORTEN_URLS = PREFS.getBoolean("pref_unshorten_urls", true);
private static final ArrayList<MaskHost> MASK_HOSTS = new ArrayList<>();
static {
MASK_HOSTS.add(new MaskHost("facebook.com", "/l.php", "u"));
MASK_HOSTS.add(new MaskHost("link.tapatalk.com", null, "out"));
MASK_HOSTS.add(new MaskHost("link2.tapatalk.com", null, "url"));
MASK_HOSTS.add(new MaskHost("pt.tapatalk.com", "/redirect.php", "url"));
MASK_HOSTS.add(new MaskHost("google.com", "/url/", "q"));
MASK_HOSTS.add(new MaskHost("google.com", "/url", "url"));
MASK_HOSTS.add(new MaskHost("vk.com", "/away.php", "to"));
MASK_HOSTS.add(new MaskHost("click.linksynergy.com/", null, "RD_PARM1"));
MASK_HOSTS.add(new MaskHost("youtube.com", "/attribution_link/", "u"));
MASK_HOSTS.add(new MaskHost("youtube.com", "/attribution_link/", "a"));
MASK_HOSTS.add(new MaskHost("m.scope.am", "/api/", "out"));
MASK_HOSTS.add(new MaskHost("redirectingat.com", "/rewrite.php", "url"));
MASK_HOSTS.add(new MaskHost("jdoqocy.com", null, "api"));
MASK_HOSTS.add(new MaskHost("viglink.com", "/api/", "out"));
MASK_HOSTS.add(new MaskHost("redirect.viglink.com", null, "out"));
MASK_HOSTS.add(new MaskHost("getpocket.com", "/redirect/", "url"));
MASK_HOSTS.add(new MaskHost("news.google.com", "/news/", "url"));
MASK_HOSTS.add(new MaskHost("go.theregister.com", "/feed/", null));
MASK_HOSTS.add(new MaskHost("securitylab.ru", "/bitrix/exturl.php", "goto"));
MASK_HOSTS.add(new MaskHost("securitylab.ru", "/bitrix/rk.php", "goto"));
MASK_HOSTS.add(new MaskHost("saviry.co", "/m", "u"));
MASK_HOSTS.add(new MaskHost("ibnads.xl.co.id", "/ads-request", "a"));
MASK_HOSTS.add(new MaskHost("googleadservices.com", "/pagead/aclk", "adurl"));
// Special hosts below.
MASK_HOSTS.add(new MaskHost("redd.it", null, null) {
@Override
public Uri unmaskLink(Uri url) {
return url.buildUpon().authority("reddit.com").build();
}
});
MASK_HOSTS.add(new MaskHost("mandrillapp.com", "track", "p") {
@Override
public Uri unmaskLink(Uri url) {
String b64data = null;
List pathSegments = url.getPathSegments();
if (pathSegments == null) return url;
if (pathSegments.size() > 0 && SEGMENT.equals(pathSegments.get(0)))
b64data = url.getQueryParameter(PARAMETER) + "==";
if (b64data == null) return url;
String unmaskedLink;
try {
String b64Decoded = new String(Base64.decode(b64data, Base64.URL_SAFE), "UTF-8");
JSONObject jsonObject = new JSONObject(b64Decoded);
String p = jsonObject.getString("p");
JSONObject jsonObject2 = new JSONObject(p);
unmaskedLink = jsonObject2.getString("url");
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
return url;
}
return MaskHost.parseUrl(url, unmaskedLink);
}
});
}
public void initZygote(StartupParam startupParam) throws Throwable {
XC_MethodHook hook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
Intent intent = (Intent) param.args[0];
if (intent == null) return;
// We're only interested in ACTION_VIEW intents.
String intentAction = intent.getAction();
if (intentAction == null || !Intent.ACTION_VIEW.equals(intentAction))
return;
// If the data isn't a URL (http/https) do nothing.
Uri intentData = intent.getData();
if (intentData == null || !intentData.toString().startsWith("http"))
return;
// Unmask the URL (nested masked URLs, too.)
Uri unmaskedUrl = intentData;
Uri finalUrl = unmaskedUrl;
MaskHost maskHost = getMaskedUrlMaskHost(unmaskedUrl);
while (maskHost != null) {
unmaskedUrl = maskHost.unmaskLink(unmaskedUrl);
if (unmaskedUrl.equals(finalUrl))
break;
finalUrl = unmaskedUrl;
maskHost = getMaskedUrlMaskHost(unmaskedUrl);
}
// Does the URL need to be unshortened?
// The hasExtra check is to check if the URL is sent from our own app after being
// unshortened, so we,don't start an infinite loop.
if (PREF_UNSHORTEN_URLS && !intent.hasExtra("crappalinks") &&
RedirectHelper.isRedirect(unmaskedUrl.getHost())) {
// Have the shortened URL open with our activity. It'll be handled there.
intent.setComponent(ComponentName.unflattenFromString(
"com.germainz.crappalinks/com.germainz.crappalinks.Resolver"));
}
// We just set the intent's data to the unmasked URL. If this URL needs to be unshortened,
// it'll open with our activity (since we explicitly set the component above) which
// will unshorten it then send a new intent.
intent.setDataAndType(unmaskedUrl, intent.getType());
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
findAndHookMethod("android.app.ContextImpl", null, "startActivity", Intent.class, Bundle.class, hook);
findAndHookMethod(Activity.class, "startActivity", Intent.class, Bundle.class, hook);
} else {
findAndHookMethod("android.app.ContextImpl", null, "startActivity", Intent.class, hook);
findAndHookMethod(Activity.class, "startActivity", Intent.class, hook);
}
}
/**
* Return the appropriate MaskHost or null if the URL's host isn't a known URL masker.
*/
public static MaskHost getMaskedUrlMaskHost(Uri uri) {
String host = uri.getHost();
for (MaskHost maskHost : MASK_HOSTS) {
if (host.endsWith(maskHost.URL)) {
if (maskHost.SEGMENT == null) {
return maskHost;
} else {
String path = uri.getPath();
if (path == null) return null;
if (path.length() > 0 && path.startsWith(maskHost.SEGMENT))
return maskHost;
}
}
}
return null;
}
}
| 7,699 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
Resolver.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/Resolver.java | package com.germainz.crappalinks;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.UnknownHostException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Resolver extends Activity {
private String toastType;
private boolean confirmOpen;
private String resolveAllWhen;
private boolean useUnshortenIt;
private static final String TOAST_NONE = "0";
private static final String TOAST_DETAILED = "2";
private static final String UNSHORTEN_IT_API_KEY = "UcWGkhtMFdM4019XeI8lgfNOk875RL7K";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences("com.germainz.crappalinks_preferences",
Context.MODE_WORLD_READABLE);
toastType = sharedPreferences.getString("pref_toast_type", TOAST_NONE);
confirmOpen = sharedPreferences.getBoolean("pref_confirm_open", false);
resolveAllWhen = sharedPreferences.getString("pref_resolve_all_when", "ALWAYS");
// Still called pref_use_long_url for backwards compatibility, as we used to use longurl.org instead.
useUnshortenIt = sharedPreferences.getBoolean("pref_use_long_url", false);
new ResolveUrl().execute(getIntent().getDataString());
/* Ideally, this would be a service, but we're redirecting intents via Xposed.
* We finish the activity immediately so that the user can still interact with the
* foreground app while we unshorten the URL in the background.
*/
finish();
}
private class ResolveUrl extends AsyncTask<String, Void, String> {
private Context context = null;
// unknown error while connecting
private boolean connectionError = false;
// connection missing/not working
private boolean noConnectionError = false;
private ResolveUrl() {
context = Resolver.this;
}
@Override
protected void onPreExecute() {
if (!toastType.equals(TOAST_NONE))
Toast.makeText(context, getString(R.string.toast_message_started),
Toast.LENGTH_SHORT).show();
}
private String getRedirect(String url) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(url).openConnection();
c.setConnectTimeout(10000);
c.setReadTimeout(15000);
c.connect();
final int responseCode = c.getResponseCode();
// If the response code is 3xx, it's a redirection. Return the real location.
if (responseCode >= 300 && responseCode < 400) {
String location = c.getHeaderField("Location");
return RedirectHelper.getAbsoluteUrl(location, url);
}
// It might also be a redirection using meta tags.
else if (responseCode >= 200 && responseCode < 300 ) {
Document d = Jsoup.parse(c.getInputStream(), "UTF-8", url);
Elements refresh = d.select("*:not(noscript) > meta[http-equiv=Refresh]");
if (!refresh.isEmpty()) {
Element refreshElement = refresh.first();
if (refreshElement.hasAttr("url"))
return RedirectHelper.getAbsoluteUrl(refreshElement.attr("url"), url);
else if (refreshElement.hasAttr("content") && refreshElement.attr("content").contains("url="))
return RedirectHelper.getAbsoluteUrl(refreshElement.attr("content").split("url=")[1].replaceAll("^'|'$", ""), url);
}
}
} catch (ConnectException | UnknownHostException e) {
noConnectionError = true;
e.printStackTrace();
} catch (Exception e) {
connectionError = true;
e.printStackTrace();
} finally {
if (c != null)
c.disconnect();
}
return null;
}
private String getRedirectUsingLongURL(String url) {
HttpURLConnection c = null;
try {
// http://unshorten.it/api/documentation
Uri.Builder builder = new Uri.Builder();
builder.scheme("http").authority("api.unshorten.it").appendQueryParameter("shortURL", url)
.appendQueryParameter("responseFormat", "json").appendQueryParameter("apiKey", UNSHORTEN_IT_API_KEY);
String requestUrl = builder.build().toString();
c = (HttpURLConnection) new URL(requestUrl).openConnection();
c.setRequestProperty("User-Agent", "CrappaLinks");
c.setConnectTimeout(10000);
c.setReadTimeout(15000);
c.connect();
final int responseCode = c.getResponseCode();
if (responseCode == 200) {
// Response format: {"fullurl": "URL"}
JSONObject jsonObject = new JSONObject(new BufferedReader(
new InputStreamReader(c.getInputStream())).readLine());
if (jsonObject.has("error")) {
connectionError = true;
Log.e("CrappaLinks", requestUrl);
Log.e("CrappaLinks", jsonObject.toString());
return url;
} else {
return jsonObject.getString("fullurl");
}
}
} catch (ConnectException | UnknownHostException e) {
noConnectionError = true;
} catch (Exception e) {
connectionError = true;
e.printStackTrace();
} finally {
if (c != null)
c.disconnect();
}
return url;
}
protected String doInBackground(String... urls) {
String redirectUrl = urls[0];
// if there's no connection, fail and return the original URL.
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() == null) {
noConnectionError = true;
return redirectUrl;
}
if (useUnshortenIt) {
return getRedirectUsingLongURL(redirectUrl);
} else {
HttpURLConnection.setFollowRedirects(false);
// Use the cookie manager so that cookies are stored. Useful for some hosts that keep
// redirecting us indefinitely unless the set cookie is detected.
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
// Should we resolve all URLs?
boolean resolveAll = true;
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (resolveAllWhen.equals("NEVER") || (resolveAllWhen.equals("WIFI_ONLY") && !wifiInfo.isConnected()))
resolveAll = false;
// Keep trying to resolve the URL until we get a URL that isn't a redirect.
String finalUrl = redirectUrl;
while (redirectUrl != null && ((resolveAll) || (RedirectHelper.isRedirect(Uri.parse(redirectUrl).getHost())))) {
redirectUrl = getRedirect(redirectUrl);
if (redirectUrl != null) {
// This should avoid infinite loops, just in case.
if (redirectUrl.equals(finalUrl))
return finalUrl;
finalUrl = redirectUrl;
}
}
return finalUrl;
}
}
protected void onPostExecute(final String uri) {
if (noConnectionError)
Toast.makeText(context, getString(R.string.toast_message_network) + uri, Toast.LENGTH_LONG).show();
else if (connectionError)
Toast.makeText(context, getString(R.string.toast_message_error) + uri, Toast.LENGTH_LONG).show();
if (confirmOpen) {
Intent confirmDialogIntent = new Intent(context, ConfirmDialog.class);
confirmDialogIntent.putExtra("uri", uri);
startActivity(confirmDialogIntent);
} else {
if (!noConnectionError && !connectionError && toastType.equals(TOAST_DETAILED))
Toast.makeText(context, getString(R.string.toast_message_done) + uri, Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("crappalinks", "");
startActivity(intent);
}
}
}
} | 9,752 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
RedirectHelper.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/RedirectHelper.java | package com.germainz.crappalinks;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class RedirectHelper {
// Hosts that shorten URLs - we need to follow the redirections to get the real URL for those
private static final String[] REDIRECT_HOSTS = {"t.co", "youtu.be", "bit.ly", "menea.me", "kcy.me", "goo.gl",
"ow.ly", "j.mp", "redes.li", "dlvr.it", "tinyurl.com", "tmblr.co", "reut.rs", "sns.mx", "wp.me", "4sq.com",
"ed.cl", "huff.to", "mun.do", "cos.as", "flip.it", "amzn.to", "cort.as", "on.cnn.com", "fb.me",
"shar.es", "spr.ly", "v.ht", "v0v.in", "bitly.com", "tl.gd", "wh.gov", "hukd.mydealz.de",
"untp.i", "kck.st", "engt.co", "nyti.ms", "cnnmon.ie", "vrge.co", "is.gd", "cnn.it", "spon.de",
"affiliation.appgratuites-network.com", "t.cn", "url.cn", "ht.ly", "po.st", "ohmyyy.gt", "dustn.ws",
"glm.io", "nazr.in", "chip.biz", "ift.tt", "dopice.sk", "phon.es", "buff.ly", "htn.to", "trib.al",
"mhlthm.ag", "nerdi.st", "pulse.me", "y2u.be", "feedproxy.google.com", "mdk.to", "ppt.cc",
"feeds.gawker.com", "tinylinks.co", "vk.cc", "rch.lt", "mynt.to", "brt.st", "kom.ps", "urly.fi",
"qklnk.co", "hec.su", "tr.im", "qr.ae", "full.sc", "smo.sh", "bit.do", "shar.as", "email.ifttt.com"
};
/**
* Return true if the host is a known URL shortener
*/
public static boolean isRedirect(String host) {
for (String redirectHost : REDIRECT_HOSTS) {
if (host.endsWith(redirectHost))
return true;
}
return false;
}
public static String getAbsoluteUrl(String urlString, String baseUrlString) throws URISyntaxException,
MalformedURLException {
if (urlString.startsWith("http")) {
return urlString;
} else {
URL url = new URL(baseUrlString);
URI baseUri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
url.getPath(), url.getQuery(), url.getRef());
return baseUri.resolve(urlString).toString();
}
}
}
| 2,204 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
MaskHost.java | /FileExtraction/Java_unseen/GermainZ_CrappaLinks/src/com/germainz/crappalinks/MaskHost.java | package com.germainz.crappalinks;
import android.net.Uri;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
public class MaskHost {
public String URL;
public String SEGMENT;
public String PARAMETER;
public MaskHost(String URL, String SEGMENT, String PARAMETER) {
this.URL = URL;
this.SEGMENT = SEGMENT;
this.PARAMETER = PARAMETER;
}
/**
* Unmask the URI and return it
*/
public Uri unmaskLink(Uri url) {
String unmaskedLink = null;
String path;
if (SEGMENT == null) {
// The host always masks, no need to determine if it's the right segment
unmaskedLink = url.getQueryParameter(PARAMETER);
} else {
// Only a certain segment is used to mask URLs. Determine if this is it.
path = url.getPath();
if (path == null) return url;
// If it is, unmask the URL.
if (path.length() > 0 && path.startsWith(SEGMENT)) {
if (PARAMETER == null)
unmaskedLink = String.format("%s://%s", url.getScheme(),
url.getPath().substring(SEGMENT.length()));
else
unmaskedLink = url.getQueryParameter(PARAMETER);
}
}
return parseUrl(url, unmaskedLink);
}
/**
* Resolve relative links if necessary and convert the String URL to a Uri URL.
*/
public static Uri parseUrl(Uri originalUrl, String newUrl) {
if (newUrl == null)
return originalUrl;
try {
if (!new URI(newUrl).isAbsolute())
newUrl= new URI(originalUrl.toString()).resolve(newUrl).toString();
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
return Uri.parse(URLDecoder.decode(newUrl, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return originalUrl;
}
}
}
| 2,093 | Java | .java | GermainZ/CrappaLinks | 47 | 8 | 1 | 2014-01-09T15:10:12Z | 2016-07-04T23:36:56Z |
issues-java.txt | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/issues-java.txt |
::::: watch list :::::
2018/01/28 - "VM Thread" causing spikes in CPU usage and stutters in playback.
:::: Java / JavaFX stuff ::::
Scroll speed on lyrics scroll pane when the lyrics almost-but-dont-quite fit one full screen is really slow.
Try to fit all data in current list table by adjusting columns that aren't no-resize on setCurrentList, if not possible, do nothing
I did some work on this. It conflicts with our FormattedAlbumCell because there, to keep it from wrapping
we setminwidth to double.max, causing the fit function to fail.
I used the reflection stuff from this thread, and I think it would've worked if not for this issue:
https://stackoverflow.com/questions/23284437/javafx-tablecolumn-resize-to-fit-cell-content
Of course, I would have to then check table width, fail gracefully and revert, or distribute excess space.
Resize Policy
Windowed mode, shrink window until a scrollbar appears. Maximize window so scrollbar disappears -- Scrollbar width is still accounted for
Scrollbar width is calculated wrong by 4 pixels. I have it hardcoded, but I posted a SE question
https://stackoverflow.com/questions/47852175/get-full-width-of-scrollbar-for-a-tableview
Double clicking on table-column dividers doesn't call resize:
https://stackoverflow.com/questions/47852239/customresizepolicy-not-triggering-when-a-columns-headers-divider-is-double-cli
not fixed in java 11 / javafx11
Tiny drop shadow on transport buttons when in dark theme. It's the line HBox, VBox, #transport { ... -fx-background-color: #222222 ... }
Showing any dialog prevents window drag resize in ubuntu / other linux
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8140491
https://stackoverflow.com/questions/33134791/javafx-stage-cant-be-resized-after-showing-a-dialog
Not fixed in java 11 / javafx11
While loading the library, the table view scrolls a little bit.
https://stackoverflow.com/questions/47950917/stop-tableview-small-scroll-when-adding-content-to-bottom-of-table
1/2/18 - Bug submitted to bugs.java.com
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8194328
11/26/18 - not fixed in java 11 / javafx11
::::
Add file crash, ubuntu 16.04
JNA: Callback uk.co.caprica.vlcj.player.DefaultMediaPlayer$EventCallback@6269409b threw the following exception:
java.lang.IllegalArgumentException: No field of type class uk.co.caprica.vlcj.binding.internal.media_player_chapter_changed in libvlc_event_u(native@0x7f2465abcd00) (16 bytes) {
media_meta_changed media_meta_changed@0=media_meta_changed(native@0x0) (4 bytes) {
int meta_type@0=0
}
media_subitem_added media_subitem_added@0=media_subitem_added(native@0x0) (8 bytes) {
libvlc_media_t new_child@0=NULL
}
media_duration_changed media_duration_changed@0=media_duration_changed(native@0x0) (8 bytes) {
long new_duration@0=0
}
media_parsed_changed media_parsed_changed@0=media_parsed_changed(native@0x0) (4 bytes) {
int new_status@0=0
}
media_freed media_freed@0=media_freed(native@0x0) (8 bytes) {
libvlc_media_t md@0=NULL
}
media_state_changed media_state_changed@0=media_state_changed(native@0x0) (4 bytes) {
int new_state@0=0
}
media_player_buffering media_player_buffering@0=media_player_buffering(native@0x0) (4 bytes) {
float new_cache@0=0.0
}
media_player_position_changed media_player_position_changed@0=media_player_position_changed(native@0x0) (4 bytes) {
float new_position@0=0.0
}
media_player_time_changed media_player_time_changed@0=media_player_time_changed(native@0x0) (8 bytes) {
long new_time@0=0
}
media_player_title_changed media_player_title_changed@0=media_player_title_changed(native@0x0) (4 bytes) {
int new_title@0=0
}
media_player_seekable_changed media_player_seekable_changed@0=media_player_seekable_changed(native@0x0) (4 bytes) {
int new_seekable@0=0
}
media_player_pausable_changed media_player_pausable_changed@0=media_player_pausable_changed(native@0x0) (4 bytes) {
int new_pausable@0=0
}
media_player_vout media_player_vout@0=media_player_vout(native@0x0) (4 bytes) {
int new_count@0=0
}
media_list_item_added media_list_item_added@0=media_list_item_added(native@0x0) (16 bytes) {
libvlc_media_t item@0=NULL
int index@8=0
}
media_list_will_add_item media_list_will_add_item@0=media_list_will_add_item(native@0x0) (16 bytes) {
libvlc_media_t item@0=NULL
int index@8=0
}
media_list_item_deleted media_list_item_deleted@0=media_list_item_deleted(native@0x0) (16 bytes) {
libvlc_media_t item@0=NULL
int index@8=0
}
media_list_will_delete_item media_list_will_delete_item@0=media_list_will_delete_item(native@0x0) (16 bytes) {
libvlc_media_t item@0=NULL
int index@8=0
}
media_list_player_next_item_set media_list_player_next_item_set@0=media_list_player_next_item_set(native@0x0) (8 bytes) {
libvlc_media_t item@0=NULL
}
media_player_snapshot_taken media_player_snapshot_taken@0=media_player_snapshot_taken(native@0x0) (8 bytes) {
String filename@0=null
}
media_player_length_changed media_player_length_changed@0=media_player_length_changed(native@0x0) (8 bytes) {
long new_length@0=0
}
vlm_media_event vlm_media_event@0=vlm_media_event(native@0x0) (16 bytes) {
String psz_media_name@0=null
String psz_instance_name@8=null
}
media_player_media_changed media_player_media_changed@0=media_player_media_changed(native@0x0) (8 bytes) {
libvlc_media_t md@0=NULL
}
media_player_scrambled_changed media_player_scrambled_changed@0=media_player_scrambled_changed(native@0x0) (4 bytes) {
int new_scrambled@0=0
}
media_player_es_changed media_player_es_changed@0=media_player_es_changed(native@0x0) (8 bytes) {
int i_type@0=0
int i_id@4=0
}
media_subitemtree_added media_subitemtree_added@0=media_subitemtree_added(native@0x0) (8 bytes) {
libvlc_media_t item@0=NULL
}
media_player_audio_volume media_player_audio_volume@0=media_player_audio_volume(native@0x0) (4 bytes) {
float volume@0=0.0
}
media_player_audio_device media_player_audio_device@0=media_player_audio_device(native@0x0) (8 bytes) {
String device@0=null
}
}
memory dump
[01000000]
[247f0000]
[709c76d0]
[247f0000]
at com.sun.jna.Union.getTypedValue(Union.java:155)
at uk.co.caprica.vlcj.player.events.MediaPlayerEventFactory.createEvent(MediaPlayerEventFactory.java:263)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer$EventCallback.callback(DefaultMediaPlayer.java:2216)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.jna.CallbackReference$DefaultCallbackProxy.invokeCallback(CallbackReference.java:455)
at com.sun.jna.CallbackReference$DefaultCallbackProxy.callback(CallbackReference.java:485)
Nov 5, 2018 22:56:22 PM net.joshuad.hypnos.Hypnos lambda$start$6
INFO: Hypnos finished loading.
hypnos: ../nptl/pthread_mutex_lock.c:352: __pthread_mutex_lock_full: Assertion `INTERNAL_SYSCALL_ERRNO (e, __err) != ESRCH || !robust' failed. | 7,162 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
HotkeyConflictException.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/HotkeyConflictException.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*/
package jxgrabkey;
/**
* This Exception is thrown when another application already registered a hotkey
* which JXGrabKey tried to register for itself.
* X11 hotkeys can only be registered by one application at a time.
* Because JXGrabKey registers the same hotkey with different combinations of
* offending masks like scrolllock, numlock and capslock,
* any of those registrations can be the cause of the conflict.
* It is best to unregister the hotkey after receiving this exception.
* Otherwise the hotkey may not work at all, or may not work with all mask combinations.
*
* @author subes
*/
public class HotkeyConflictException extends Exception {
private static final long serialVersionUID = 1L;
public HotkeyConflictException() {
super();
}
public HotkeyConflictException(String message) {
super(message);
}
public HotkeyConflictException(String message, Throwable cause) {
super(message, cause);
}
public HotkeyConflictException(Throwable cause) {
super(cause);
}
}
| 1,822 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
HotkeyListenerDebugEnabled.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/HotkeyListenerDebugEnabled.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*/
package jxgrabkey;
/**
* This listener handles debug messages aswell as hotkey events.
* It can be used for custom logging needs.
*
* @author subes
*/
public interface HotkeyListenerDebugEnabled extends HotkeyListener {
/**
* This method is used to handle debug messages from JXGrabKey.
* You need to enable debug to receive those.
*
* @param debugMessage
*/
void debugCallback(String debugMessage);
}
| 1,218 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
JXGrabKey.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/JXGrabKey.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*/
package jxgrabkey;
import java.util.Vector;
/**
* This class implements the API access.
* All public methods are synchronized, hence thread-safe.
*
* @author subes
*/
public class JXGrabKey {
private static final int SLEEP_WHILE_LISTEN_EXITS = 100;
private static boolean debug;
private static JXGrabKey instance;
private static Thread thread;
private static Vector<HotkeyListener> listeners = new Vector<HotkeyListener>();
/**
* This constructor starts a seperate Thread for the main listen loop.
*/
private JXGrabKey() {
thread = new Thread(){
@Override
public void run() {
listen();
debugCallback("-- listen()");
}
};
thread.start();
}
/**
* Retrieves the singleton. Initializes it, if not yet done.
*
* @return
*/
public static synchronized JXGrabKey getInstance(){
if(instance == null){
instance = new JXGrabKey();
}
return instance;
}
/**
* Adds a HotkeyListener.
*
* @param listener
*/
public void addHotkeyListener(HotkeyListener listener){
if(listener == null){
throw new IllegalArgumentException("listener must not be null");
}
JXGrabKey.listeners.add(listener);
}
/**
* Removes a HotkeyListener.
*
* @param listener
*/
public void removeHotkeyListener(HotkeyListener listener){
if(listener == null){
throw new IllegalArgumentException("listener must not be null");
}
JXGrabKey.listeners.remove(listener);
}
/**
* Unregisters all hotkeys, removes all HotkeyListeners,
* stops the main listen loop and deinitializes the singleton.
*/
public void cleanUp(){
clean();
if(thread.isAlive()){
while(thread.isAlive()){
try {
Thread.sleep(SLEEP_WHILE_LISTEN_EXITS);
} catch (InterruptedException e) {
debugCallback("cleanUp() - InterruptedException: "+e.getMessage());
}
}
instance = null; //next time getInstance is called, reinitialize JXGrabKey
}
if(listeners.size() > 0){
listeners.clear();
}
}
/**
* Registers a X11 hotkey.
*
* @param id
* @param x11Mask
* @param x11Keysym
* @throws jxgrabkey.HotkeyConflictException
*/
public void registerX11Hotkey(int id, int x11Mask, int x11Keysym) throws HotkeyConflictException{
registerHotkey(id, x11Mask, x11Keysym);
}
/**
* Enables/Disables printing of debug messages.
*
* @param enabled
*/
public static void setDebugOutput(boolean enabled){
debug = enabled;
setDebug(enabled);
}
/**
* Notifies HotkeyListeners about a received KeyEvent.
*
* This method is used by the C++ code.
* Do not use this method from externally.
*
* @param id
*/
public static void fireKeyEvent(int id){
for(int i = 0; i < listeners.size(); i++){
listeners.get(i).onHotkey(id);
}
}
/**
* Either gives debug messages to a HotkeyListenerDebugEnabled if registered,
* or prints to console otherwise.
* Does only print if debug is enabled.
*
* This method is both used by the C++ and Java code, so it should not be synchronized.
* Don't use this method from externally.
*
* @param debugmessage
*/
public static void debugCallback(String debugmessage){
if(debug){
debugmessage.trim();
if(debugmessage.charAt(debugmessage.length()-1) != '\n'){
debugmessage += "\n";
}else{
while(debugmessage.endsWith("\n\n")){
debugmessage = debugmessage.substring(0, debugmessage.length()-1);
}
}
boolean found = false;
for(HotkeyListener l : listeners){
if(l instanceof HotkeyListenerDebugEnabled){
((HotkeyListenerDebugEnabled)l).debugCallback(debugmessage);
found = true;
}
}
if(found == false){
System.out.print(debugmessage);
}
}
}
/**
* This method unregisters a hotkey.
* If the hotkey is not yet registered, nothing will happen.
*
* @param id
*/
public native void unregisterHotKey(int id);
private native void listen();
private static native void setDebug(boolean debug);
private native void clean();
private native void registerHotkey(int id, int mask, int key) throws HotkeyConflictException;
}
| 5,619 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
HotkeyListener.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/HotkeyListener.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*/
package jxgrabkey;
/**
* This listener is used to handle hotkey events from externally.
*
* @author subes
*/
public interface HotkeyListener {
/**
* This method receives the hotkey events which are received by the main listen loop.
*
* @param id
*/
void onHotkey(int id);
}
| 1,079 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
X11MaskDefinitions.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/X11MaskDefinitions.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*
* Modified by Josh Hartwell to accomodate JavaFX, 2018.
*/
package jxgrabkey;
import net.joshuad.hypnos.hotkeys.HotkeyState;
/**
* This class holds definitions for X11 masks. It can also convert AWT masks into X11 masks.
*
* @author subes
*/
public final class X11MaskDefinitions {
public static final int X11_SHIFT_MASK = 1 << 0;
public static final int X11_LOCK_MASK = 1 << 1;
public static final int X11_CONTROL_MASK = 1 << 2;
public static final int X11_MOD1_MASK = 1 << 3;
public static final int X11_MOD2_MASK = 1 << 4;
public static final int X11_MOD3_MASK = 1 << 5;
public static final int X11_MOD4_MASK = 1 << 6;
public static final int X11_MOD5_MASK = 1 << 7;
//TODO: It'd be nice if this didn't depend on my custom class, since this is kind of a library
public static int fxKeyStateToX11Mask ( HotkeyState e ) {
int mask = 0;
if ( e.isShiftDown() ) {
mask |= X11MaskDefinitions.X11_SHIFT_MASK;
}
if ( e.isControlDown() ) {
mask |= X11MaskDefinitions.X11_CONTROL_MASK;
}
if ( e.isAltDown() ) {
mask |= X11MaskDefinitions.X11_MOD1_MASK;
}
if ( e.isMetaDown() ) {
mask |= X11MaskDefinitions.X11_MOD4_MASK;
}
return mask;
}
}
| 2,005 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
X11KeysymDefinitions.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/jxgrabkey/X11KeysymDefinitions.java | /* Copyright 2008 Edwin Stang (edwinstang@gmail.com),
* Modified by Josh Hartwell to accomodate JavaFX, 2018.
*
* This file is part of JXGrabKey.
*
* JXGrabKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JXGrabKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JXGrabKey. If not, see <http://www.gnu.org/licenses/>.
*/
package jxgrabkey;
import java.awt.event.KeyEvent;
import javafx.scene.input.KeyCode;
/**
* This class holds definitions for X11 keysyms. It can also convert AWT keys into X11 keysyms.
*
* These definitions are taken from the escher project (http://escher.sourceforge.net/).
* They converted them from the original X11 definitions.
*/
public final class X11KeysymDefinitions {
public static final int ERROR = -1;
//Latin1 ******************************************************************
public static final int SPACE = 0x020;
public static final int EXCLAM = 0x021;
public static final int QUOTE_DBL = 0x022;
public static final int NUMBER_SIGN = 0x023;
public static final int DOLLAR = 0x024;
public static final int PERCENT = 0x025;
public static final int AMPERSAND = 0x026;
public static final int APOSTROPHE = 0x027;
public static final int QUOTE_RIGHT = 0x027; /* deprecated */
public static final int PAREN_LEFT = 0x028;
public static final int PAREN_RIGHT = 0x029;
public static final int ASTERISK = 0x02a;
public static final int PLUS = 0x02b;
public static final int COMMA = 0x02c;
public static final int MINUS = 0x02d;
public static final int PERIOD = 0x02e;
public static final int SLASH = 0x02f;
public static final int NUM_0 = 0x030;
public static final int NUM_1 = 0x031;
public static final int NUM_2 = 0x032;
public static final int NUM_3 = 0x033;
public static final int NUM_4 = 0x034;
public static final int NUM_5 = 0x035;
public static final int NUM_6 = 0x036;
public static final int NUM_7 = 0x037;
public static final int NUM_8 = 0x038;
public static final int NUM_9 = 0x039;
public static final int COLON = 0x03a;
public static final int SEMICOLON = 0x03b;
public static final int LESS = 0x03c;
public static final int EQUAL = 0x03d;
public static final int GREATER = 0x03e;
public static final int QUESTION = 0x03f;
public static final int AT = 0x040;
public static final int A = 0x041;
public static final int B = 0x042;
public static final int C = 0x043;
public static final int D = 0x044;
public static final int E = 0x045;
public static final int F = 0x046;
public static final int G = 0x047;
public static final int H = 0x048;
public static final int I = 0x049;
public static final int J = 0x04a;
public static final int K = 0x04b;
public static final int L = 0x04c;
public static final int M = 0x04d;
public static final int N = 0x04e;
public static final int O = 0x04f;
public static final int P = 0x050;
public static final int Q = 0x051;
public static final int R = 0x052;
public static final int S = 0x053;
public static final int T = 0x054;
public static final int U = 0x055;
public static final int V = 0x056;
public static final int W = 0x057;
public static final int X = 0x058;
public static final int Y = 0x059;
public static final int Z = 0x05a;
public static final int BRACKET_LEFT = 0x05b;
public static final int BACKSLASH = 0x05c;
public static final int BRACKET_RIGHT = 0x05d;
public static final int ASCII_CIRCUM = 0x05e;
public static final int UNDERSCORE = 0x05f;
public static final int GRAVE = 0x060;
public static final int QUOTE_LEFT = 0x060; /* deprecated */
public static final int A_SMALL = 0x061;
public static final int B_SMALL = 0x062;
public static final int C_SMALL = 0x063;
public static final int D_SMALL = 0x064;
public static final int E_SMALL = 0x065;
public static final int F_SMALL = 0x066;
public static final int G_SMALL = 0x067;
public static final int H_SMALL = 0x068;
public static final int I_SMALL = 0x069;
public static final int J_SMALL = 0x06a;
public static final int K_SMALL = 0x06b;
public static final int L_SMALL = 0x06c;
public static final int M_SMALL = 0x06d;
public static final int N_SMALL = 0x06e;
public static final int O_SMALL = 0x06f;
public static final int P_SMALL = 0x070;
public static final int Q_SMALL = 0x071;
public static final int R_SMALL = 0x072;
public static final int S_SMALL = 0x073;
public static final int T_SMALL = 0x074;
public static final int U_SMALL = 0x075;
public static final int V_SMALL = 0x076;
public static final int W_SMALL = 0x077;
public static final int X_SMALL = 0x078;
public static final int Y_SMALL = 0x079;
public static final int Z_SMALL = 0x07a;
public static final int BRACE_LEFT = 0x07b;
public static final int BAR = 0x07c;
public static final int BRACE_RIGHT = 0x07d;
public static final int ASCII_TILDE = 0x07e;
public static final int NO_BREAKSPACE = 0x0a0;;
public static final int EXCLAM_DOWN = 0x0a1;
public static final int CENT = 0x0a2;
public static final int STERLING = 0x0a3;
public static final int CURRENCY = 0x0a4;
public static final int YEN = 0x0a5;
public static final int BROKEN_BAR = 0x0a6;
public static final int SECTION = 0x0a7;
public static final int DIAERESIS = 0x0a8;
public static final int COPYRIGHT = 0x0a9;
public static final int ORDFEMININE = 0x0aa;
public static final int GUILLEMOT_LEFT = 0x0ab; /* left angle quotation mark */
public static final int NOT_SIGN = 0x0ac;
public static final int HYPHEN = 0x0ad;
public static final int REGISTERED = 0x0ae;
public static final int MACRON = 0x0af;
public static final int DEGREE = 0x0b0;
public static final int PLUS_MINUS = 0x0b1;
public static final int TWO_SUPERIOR = 0x0b2;
public static final int THREE_SUPERIOR = 0x0b3;
public static final int ACUTE = 0x0b4;
public static final int MU = 0x0b5;
public static final int PARAGRAPH = 0x0b6;
public static final int PERIOD_CENTERED = 0x0b7;
public static final int CEDILLA = 0x0b8;
public static final int ONE_SUPERIOR = 0x0b9;
public static final int MASCULINE = 0x0ba;
public static final int GUILLEMOT_RIGHT = 0x0bb; /* right angle quotation mark */
public static final int ONE_QUARTER = 0x0bc;
public static final int ONE_HALF = 0x0bd;
public static final int THREE_QUARTERS = 0x0be;
public static final int QUESTION_DOWN = 0x0bf;
public static final int A_GRAVE = 0x0c0;
public static final int A_ACUTE = 0x0c1;
public static final int A_CIRCUMFLEX = 0x0c2;
public static final int A_TILDE = 0x0c3;
public static final int A_DIAERESIS = 0x0c4;
public static final int A_RING = 0x0c5;
public static final int AE = 0x0c6;
public static final int C_CEDILLA = 0x0c7;
public static final int E_GRAVE = 0x0c8;
public static final int E_ACUTE = 0x0c9;
public static final int E_CIRCUMFLEX = 0x0ca;
public static final int E_DIAERESIS = 0x0cb;
public static final int I_GRAVE = 0x0cc;
public static final int I_ACUTE = 0x0cd;
public static final int I_CIRCUMFLEX = 0x0ce;
public static final int I_DIAERESIS = 0x0cf;
public static final int E_TH = 0x0d0;
public static final int N_TILDE = 0x0d1;
public static final int O_GRAVE = 0x0d2;
public static final int O_ACUTE = 0x0d3;
public static final int O_CIRCUMFLEX = 0x0d4;
public static final int O_TILDE = 0x0d5;
public static final int O_DIAERESIS = 0x0d6;
public static final int MULTIPLY = 0x0d7;
public static final int O_OBLIQUE = 0x0d8;
public static final int O_SLASH = 0x0d9;
public static final int U_ACUTE = 0x0da;;
public static final int U_CIRCUMFLEX = 0x0db;
public static final int U_DIAERESIS = 0x0dc;
public static final int Y_ACUTE = 0x0dd;
public static final int T_HORN = 0x0de;
public static final int S_SHARP = 0x0df;
public static final int A_GRAVE_SMALL = 0x0e0;
public static final int A_ACUTE_SMALL = 0x0e1;
public static final int A_CIRCUMFLEX_SMALL = 0x0e2;
public static final int A_TILDE_SMALL = 0x0e3;
public static final int A_DIAERESIS_SMALL = 0x0e4;
public static final int A_RING_SMALL = 0x0e5;
public static final int AE_SMALL = 0x0e6;
public static final int C_CEDILLA_SMALL = 0x0e7;
public static final int E_GRAVE_SMALL = 0x0e8;
public static final int E_ACUTE_SMALL = 0x0e9;
public static final int E_CIRCUMFLEX_SMALL = 0x0ea;
public static final int E_DIAERESIS_SMALL = 0x0eb;
public static final int I_GRAVE_SMALL = 0x0ec;
public static final int I_ACUTE_SMALL = 0x0ed;
public static final int I_CIRCUMFLEX_SMALL = 0x0ee;
public static final int I_DIAERESIS_SMALL = 0x0ef;
public static final int E_TH_SMALL = 0x0f0;
public static final int N_TILDE_SMALL = 0x0f1;
public static final int O_GRAVE_SMALL = 0x0f2;
public static final int O_ACUTE_SMALL = 0x0f3;
public static final int O_CIRCUMFLEX_SMALL = 0x0f4;
public static final int O_TILDE_SMALL = 0x0f5;
public static final int O_DIAERESIS_SMALL = 0x0f6;
public static final int DIVISION_SMALL = 0x0f7;
public static final int O_SLASH_SMALL = 0x0f8;
public static final int O_OBLIQUE_SMALL = 0x0f9;
public static final int UA_CUTE_SMALL = 0x0fa;;
public static final int U_CIRCUMFLEX_SMALL = 0x0fb;
public static final int U_DIAERESIS_SMALL = 0x0fc;
public static final int YA_CUTE_SMALL = 0x0fd;
public static final int T_HORN_SMALL = 0x0fe;
public static final int Y_DIAERESIS_SMALL = 0x0ff;
//Misc ********************************************************************
public static final int VOID_SYMBOL = 0xffffff;
/* TTY Functions, cleverly chosen to map to ascii, for convenience of
* programming, but could have been arbitrary (at the cost of lookup
* tables in client code).
*/
public static final int BACKSPACE = 0xff08; /* back space, back char */
public static final int TAB = 0xff09;
public static final int LINEFEED = 0xff0a; /* linefeed, LF */
public static final int CLEAR = 0xff0b;
public static final int RETURN = 0xff0d; /* return, enter */
public static final int PAUSE = 0xff13; /* pause, hold */
public static final int SCROLL_LOCK = 0xff14;
public static final int SYS_REQ = 0xff15;
public static final int ESCAPE = 0xff1b;
public static final int DELETE = 0xffff; /* delete, rubout */
/* International & multi-key character composition. */
public static final int MULTI_KEY = 0xff20; /* multi-key character compose */
public static final int CODEINPUT = 0xff37;
public static final int SINGLE_CANDIDATE = 0xff3c;
public static final int MULTIPLE_CANDIDATE = 0xff3d;
public static final int PREVIOUS_CANDIDATE = 0xff3e;
/* Japanese keyboard support. 0xff31 thru 0xff3f are under XK_KOREAN. */
public static final int KANJI = 0xff21; /* kanji, kanji convert */
public static final int MUHENKAN = 0xff22; /* cancel conversion */
public static final int HENKAN_MODE = 0xff23; /* start/stop conversion */
public static final int HENKAN = 0xff23; /* alias for henkan_mode */
public static final int ROMAJI = 0xff24; /* to romaji */
public static final int HIRAGANA = 0xff25; /* to hiragana */
public static final int KATAKANA = 0xff26; /* to katakana */
public static final int HIRAGANA_KATAKANA = 0xff27; /* hiragana/katakana toggle */
public static final int ZENKAKU = 0xff28; /* to zenkaku */
public static final int HANKAKU = 0xff29; /* to hankaku */
public static final int ZENKAKU_HANKAKU = 0xff2a; /* zenkaku/hankaku toggle */
public static final int TOUROKU = 0xff2b; /* add to dictionary */
public static final int MASSYO = 0xff2c; /* delete from dictionary */
public static final int KANA_LOCK = 0xff2d; /* kana lock */
public static final int KANA_SHIFT = 0xff2e; /* kana shift */
public static final int EISU_SHIFT = 0xff2f; /* alphanumeric shift */
public static final int EISU_TOGGLE = 0xff30; /* alphanumeric toggle */
public static final int KANJI_BANGOU = 0xff37; /* codeinput */
public static final int ZEN_KOHO = 0xff3d; /* multiple/all candidate(s) */
public static final int MAE_KOHO = 0xff3e; /* previous candidate */
/** Cursor control & motion. */
public static final int HOME = 0xff50;
public static final int LEFT = 0xff51; /* move left, left arrow */
public static final int UP = 0xff52; /* move up, up arrow */
public static final int RIGHT = 0xff53; /* move right, right arrow */
public static final int DOWN = 0xff54; /* move down, down arrow */
public static final int PRIOR = 0xff55; /* prior, previous */
public static final int PAGE_UP = 0xff55;
public static final int NEXT = 0xff56; /* next */
public static final int PAGE_DOWN = 0xff56;
public static final int END = 0xff57; /* eol */
public static final int BEGIN = 0xff58; /* bol */
/* Misc Functions. */
public static final int SELECT = 0xff60; /* select, mark */
public static final int PRINT = 0xff61;
public static final int EXECUTE = 0xff62; /* execute, run, do */
public static final int INSERT = 0xff63; /* insert, insert here */
public static final int UNDO = 0xff65; /* undo, oops */
public static final int REDO = 0xff66; /* redo, again */
public static final int MENU = 0xff67;
public static final int FIND = 0xff68; /* find, search */
public static final int CANCEL = 0xff69; /* cancel, stop, abort, exit */
public static final int HELP = 0xff6a; /* help */
public static final int BREAK = 0xff6b;
public static final int MODE_SWITCH = 0xff7e; /* character set switch */
public static final int SCRIPT_SWITCH = 0xff7e; /* alias for mode_switch */
public static final int NUM_LOCK = 0xff7f;
/* Keypad Functions, keypad numbers cleverly chosen to map to ascii. */
public static final int KP_SPACE = 0xff80; /* space */
public static final int KP_TAB = 0xff89;
public static final int KP_ENTER = 0xff8d; /* enter */
public static final int KP_F1 = 0xff91; /* pf1, kp_a, ... */
public static final int KP_F2 = 0xff92;
public static final int KP_F3 = 0xff93;
public static final int KP_F4 = 0xff94;
public static final int KP_HOME = 0xff95;
public static final int KP_LEFT = 0xff96;
public static final int KP_UP = 0xff97;
public static final int KP_RIGHT = 0xff98;
public static final int KP_DOWN = 0xff99;
public static final int KP_PRIOR = 0xff9a;
public static final int KP_PAGE_UP = 0xff9a;
public static final int KP_NEXT = 0xff9b;
public static final int KP_PAGE_DOWN = 0xff9b;
public static final int KP_END = 0xff9c;
public static final int KP_BEGIN = 0xff9d;
public static final int KP_INSERT = 0xff9e;
public static final int KP_DELETE = 0xff9f;
public static final int KP_EQUAL = 0xffbd; /* equals */
public static final int KP_MULTIPLY = 0xffaa;
public static final int KP_ADD = 0xffab;
public static final int KP_SEPARATOR = 0xffac; /* separator, often comma */
public static final int KP_SUBTRACT = 0xffad;
public static final int KP_DECIMAL = 0xffae;
public static final int KP_DIVIDE = 0xffaf;
public static final int KP_0 = 0xffb0;;
public static final int KP_1 = 0xffb1;
public static final int KP_2 = 0xffb2;
public static final int KP_3 = 0xffb3;
public static final int KP_4 = 0xffb4;
public static final int KP_5 = 0xffb5;
public static final int KP_6 = 0xffb6;
public static final int KP_7 = 0xffb7;
public static final int KP_8 = 0xffb8;
public static final int KP_9 = 0xffb9;
/* Auxilliary Functions; note the duplicate definitions for left and
* right function keys; Sun keyboards and a few other manufactures have
* such function key groups on the left and/or right sides of the
* keyboard. We've not found a keyboard with more than 35 function keys
* total.
*/
public static final int F1 = 0xffbe;
public static final int F2 = 0xffbf;
public static final int F3 = 0xffc0;
public static final int F4 = 0xffc1;
public static final int F5 = 0xffc2;
public static final int F6 = 0xffc3;
public static final int F7 = 0xffc4;
public static final int F8 = 0xffc5;
public static final int F9 = 0xffc6;
public static final int F10 = 0xffc7;
public static final int F11 = 0xffc8;
public static final int L1 = 0xffc8;
public static final int F12 = 0xffc9;
public static final int L2 = 0xffc9;
public static final int F13 = 0xffca;
public static final int L3 = 0xffca;
public static final int F14 = 0xffcb;
public static final int L4 = 0xffcb;
public static final int F15 = 0xffcc;
public static final int L5 = 0xffcc;
public static final int F16 = 0xffcd;
public static final int L6 = 0xffcd;
public static final int F17 = 0xffce;
public static final int L7 = 0xffce;
public static final int F18 = 0xffcf;
public static final int L8 = 0xffcf;
public static final int F19 = 0xffd0;
public static final int L9 = 0xffd0;
public static final int F20 = 0xffd1;
public static final int L10 = 0xffd1;
public static final int F21 = 0xffd2;
public static final int R1 = 0xffd2;
public static final int F22 = 0xffd3;
public static final int R2 = 0xffd3;
public static final int F23 = 0xffd4;
public static final int R3 = 0xffd4;
public static final int F24 = 0xffd5;
public static final int R4 = 0xffd5;
public static final int F25 = 0xffd6;
public static final int R5 = 0xffd6;
public static final int F26 = 0xffd7;
public static final int R6 = 0xffd7;
public static final int F27 = 0xffd8;
public static final int R7 = 0xffd8;
public static final int F28 = 0xffd9;
public static final int R8 = 0xffd9;
public static final int F29 = 0xffda;
public static final int R9 = 0xffda;
public static final int F30 = 0xffdb;
public static final int R10 = 0xffdb;
public static final int F31 = 0xffdc;
public static final int R11 = 0xffdc;
public static final int F32 = 0xffdd;
public static final int R12 = 0xffdd;
public static final int F33 = 0xffde;
public static final int R13 = 0xffde;
public static final int F34 = 0xffdf;
public static final int R14 = 0xffdf;
public static final int F35 = 0xffe0;
public static final int R15 = 0xffe0;
/* Modifiers. */
public static final int SHIFT_L = 0xffe1; /* left shift */
public static final int SHIFT_R = 0xffe2; /* right shift */
public static final int CONTROL_L = 0xffe3; /* left control */
public static final int CONTROL_R = 0xffe4; /* right control */
public static final int CAPS_LOCK = 0xffe5; /* caps lock */
public static final int SHIFT_LOCK = 0xffe6; /* shift lock */
public static final int META_L = 0xffe7; /* left meta */
public static final int META_R = 0xffe8; /* right meta */
public static final int ALT_L = 0xffe9; /* left alt */
public static final int ALT_R = 0xffea; /* right alt */
public static final int SUPER_L = 0xffeb; /* left super */
public static final int SUPER_R = 0xffec; /* right super */
public static final int HYPER_L = 0xffed; /* left hyper */
public static final int HYPER_R = 0xffee; /* right hyper */
//XKB *********************************************************************
public static final int LOCK = 0xfe01;
public static final int LEVEL2_LATCH = 0xfe02;
public static final int LEVEL3_SHIFT = 0xfe03;
public static final int LEVEL3_LATCH = 0xfe04;
public static final int LEVEL3_LOCK = 0xfe05;
public static final int GROUP_SHIFT = 0xff7e; /* alias for mode_switch */
public static final int GROUP_LATCH = 0xfe06;
public static final int GROUP_LOCK = 0xfe07;
public static final int NEXT_GROUP = 0xfe08;
public static final int NEXT_GROUP_LOCK = 0xfe09;
public static final int PREV_GROUP = 0xfe0a;
public static final int PREV_GROUP_LOCK = 0xfe0b;
public static final int FIRST_GROUP = 0xfe0c;
public static final int FIRST_GROUP_LOCK = 0xfe0d;
public static final int LAST_GROUP = 0xfe0e;
public static final int LAST_GROUP_LOCK = 0xfe0f;
public static final int LEFT_TAB = 0xfe20;;
public static final int MOVE_LINE_UP = 0xfe21;
public static final int MOVE_LINE_DOWN = 0xfe22;
public static final int PARTIAL_LINE_UP = 0xfe23;
public static final int PARTIAL_LINE_DOWN = 0xfe24;
public static final int PARTIAL_SPACE_LEFT = 0xfe25;
public static final int PARTIAL_SPACE_RIGHT = 0xfe26;
public static final int SET_MARGIN_LEFT = 0xfe27;
public static final int SET_MARGIN_RIGHT = 0xfe28;
public static final int RELEASE_MARGIN_LEFT = 0xfe29;
public static final int RELEASE_MARGIN_RIGHT = 0xfe2a;
public static final int RELEASE_BOTH_MARGINS = 0xfe2b;
public static final int FAST_CURSOR_LEFT = 0xfe2c;
public static final int FAST_CURSOR_RIGHT = 0xfe2d;
public static final int FAST_CURSOR_UP = 0xfe2e;
public static final int FAST_CURSOR_DOWN = 0xfe2f;
public static final int CONTINUOUS_UNDERLINE = 0xfe30;
public static final int DISCONTINUOUS_UNDERLINE = 0xfe31;
public static final int EMPHASIZE = 0xfe32;
public static final int CENTER_OBJECT = 0xfe33;
public static final int ENTER = 0xfe34;
public static final int DEAD_GRAVE = 0xfe50;;
public static final int DEAD_ACUTE = 0xfe51;
public static final int DEAD_CIRCUMFLEX = 0xfe52;
public static final int DEAD_TILDE = 0xfe53;
public static final int DEAD_MACRON = 0xfe54;
public static final int DEAD_BREVE = 0xfe55;
public static final int DEAD_ABOVEDOT = 0xfe56;
public static final int DEAD_DIAERESIS = 0xfe57;
public static final int DEAD_ABOVERING = 0xfe58;
public static final int DEAD_DOUBLEACUTE = 0xfe59;
public static final int DEAD_CARON = 0xfe5a;
public static final int DEAD_CEDILLA = 0xfe5b;
public static final int DEAD_OGONEK = 0xfe5c;
public static final int DEAD_IOTA = 0xfe5d;
public static final int DEAD_VOICED_SOUND = 0xfe5e;
public static final int DEAD_SEMIVOICED_SOUND = 0xfe5f;
public static final int DEAD_BELOWDOT = 0xfe60;
public static final int DEAD_HOOK = 0xfe61;
public static final int DEAD_HORN = 0xfe62;
public static final int FIRST_VIRTUAL_SCREEN = 0xfed0;;
public static final int PREV_VIRTUAL_SCREEN = 0xfed1;
public static final int NEXT_VIRTUAL_SCREEN = 0xfed2;
public static final int LAST_VIRTUAL_SCREEN = 0xfed4;
public static final int TERMINATE_SERVER = 0xfed5;
public static final int ACCESS_X_ENABLE = 0xfe70;;
public static final int ACCESS_X_FEEDBACK_ENABLE = 0xfe71;
public static final int REPEAT_KEYS_ENABLE = 0xfe72;
public static final int SLOW_KEYS_ENABLE = 0xfe73;
public static final int BOUNCE_KEYS_ENABLE = 0xfe74;
public static final int STICKY_KEYS_ENABLE = 0xfe75;
public static final int MOUSE_KEYS_ENABLE = 0xfe76;
public static final int MOUSE_KEYS_ACCEL_ENABLE = 0xfe77;
public static final int OVERLAY1_ENABLE = 0xfe78;
public static final int OVERLAY2_ENABLE = 0xfe79;
public static final int AUDIBLE_BELL_ENABLE = 0xfe7a;
public static final int POINTER_LEFT = 0xfee0;;
public static final int POINTER_RIGHT = 0xfee1;
public static final int POINTER_UP = 0xfee2;
public static final int POINTER_DOWN = 0xfee3;
public static final int POINTER_UP_LEFT = 0xfee4;
public static final int POINTER_UP_RIGHT = 0xfee5;
public static final int POINTER_DOWN_LEFT = 0xfee6;
public static final int POINTER_DOWN_RIGHT = 0xfee7;
public static final int POINTER_BUTTON_DFLT = 0xfee8;
public static final int POINTER_BUTTON1 = 0xfee9;
public static final int POINTER_BUTTON2 = 0xfeea;
public static final int POINTER_BUTTON3 = 0xfeeb;
public static final int POINTER_BUTTON4 = 0xfeec;
public static final int POINTER_BUTTON5 = 0xfeed;
public static final int POINTER_DBL_CLICK_DFLT = 0xfeee;
public static final int POINTER_DBL_CLICK1 = 0xfeef;
public static final int POINTER_DBL_CLICK2 = 0xfef0;
public static final int POINTER_DBL_CLICK3 = 0xfef1;
public static final int POINTER_DBL_CLICK4 = 0xfef2;
public static final int POINTER_DBL_CLICK5 = 0xfef3;
public static final int POINTER_DRAG_DFLT = 0xfef4;
public static final int POINTER_DRAG1 = 0xfef5;
public static final int POINTER_DRAG2 = 0xfef6;
public static final int POINTER_DRAG3 = 0xfef7;
public static final int POINTER_DRAG4 = 0xfef8;
public static final int POINTER_DRAG5 = 0xfefd;
public static final int POINTER_ENABLE_KEYS = 0xfef9;;
public static final int POINTER_ACCELERATE = 0xfefa;
public static final int POINTER_DFLT_BTN_NEXT = 0xfefb;
public static final int POINTER_DFLT_BTN_PREV = 0xfefc;
//XFree86 *****************************************************************
/* ModeLock. This one is old, and not really used any more since XKB
* offers this functionality.
*/
public static final int MODE_LOCK = 0x1008ff01; /* mode switch lock */
/* "Internet" keyboards. */
public static final int STANDBY = 0x1008ff10;
public static final int AUDIO_LOWER_VOLUME = 0x1008ff11;
public static final int AUDIO_MUTE = 0x1008ff12;
public static final int AUDIO_RAISE_VOLUME = 0x1008ff13;
public static final int AUDIO_PLAY = 0x1008ff14;
public static final int AUDIO_STOP = 0x1008ff15;
public static final int AUDIO_PREV = 0x1008ff16;
public static final int AUDIO_NEXT = 0x1008ff17;
public static final int HOME_PAGE = 0x1008ff18;
public static final int MAIL = 0x1008ff19;
public static final int START = 0x1008ff1a;
public static final int SEARCH = 0x1008ff1b;
public static final int AUDIO_RECORD = 0x1008ff1c;
/* PDA's (e.g. Palm, PocketPC or elsewhere). */
public static final int CALCULATOR = 0x1008ff1d;
public static final int MEMO = 0x1008ff1e;
public static final int TO_DO_LIST = 0x1008ff1f;
public static final int CALENDAR = 0x1008ff20;
public static final int POWER_DOWN = 0x1008ff21;
public static final int CONTRASTADJUST = 0x1008ff22;
public static final int ROCKER_UP = 0x1008ff23;
public static final int ROCKER_DOWN = 0x1008ff24;
public static final int ROCKER_ENTER = 0x1008ff25;
public static final int BACK = 0x1008ff26;
public static final int FORWARD = 0x1008ff27;
public static final int STOP = 0x1008ff28;
public static final int REFRESH = 0x1008ff29;
public static final int POWER_OFF = 0x1008ff1a;
public static final int WAKE_UP = 0x1008ff1b;
/* Note, 0x1008ff02 - 0x1008ff0f are free and should be used for misc new
* keysyms that don't fit into any of the groups below.
*/
/* Misc. */
public static final int FAVORITES = 0x1008ff30;
public static final int AUDIO_PAUSE = 0x1008ff31;
public static final int AUDIO_MEDIA = 0x1008ff32;
public static final int MY_COMPUTER = 0x1008ff33;
public static final int VENDOR_HOME = 0x1008ff34;
public static final int LIGHT_BULB = 0x1008ff35;
public static final int SHOP = 0x1008ff36;
//Currency ****************************************************************
public static final int CURR_ECU = 0x20a0;
public static final int CURR_COLON = 0x20a1;
public static final int CURR_CRUZEIRO = 0x20a2;
public static final int CURR_FFRANC = 0x20a3;
public static final int CURR_LIRA = 0x20a4;
public static final int CURR_MILL = 0x20a5;
public static final int CURR_NAIRA = 0x20a6;
public static final int CURR_PESETA = 0x20a7;
public static final int CURR_RUPEE = 0x20a8;
public static final int CURR_WON = 0x20a9;
public static final int CURR_NEW_SHEQEL = 0x20aa;
public static final int CURR_DONG = 0x20ab;
public static final int CURR_EURO = 0x20ac;
private X11KeysymDefinitions(){}
public static int fxKeyToX11Keysym ( KeyCode code ) {
switch ( code ) {
case A:
return A;
case AMPERSAND:
return AMPERSAND;
case ASTERISK:
return ASTERISK;
case AT:
return AT;
case B:
return B;
case BACK_QUOTE:
return QUOTE_LEFT;
case BACK_SLASH:
return BACKSLASH;
case BACK_SPACE:
return BACKSPACE;
case BEGIN:
return BEGIN;
case BRACELEFT:
return BRACE_LEFT;
case BRACERIGHT:
return BRACE_RIGHT;
case C:
return C;
case CANCEL:
return CANCEL;
case CAPS:
return CAPS_LOCK;
case CLOSE_BRACKET:
return BRACKET_RIGHT;
case COLON:
return COLON;
case COMMA:
return COMMA;
case D:
return D;
case DEAD_ABOVEDOT:
return DEAD_ABOVEDOT;
case DEAD_ABOVERING:
return DEAD_ABOVERING;
case DEAD_ACUTE:
return DEAD_ACUTE;
case DEAD_BREVE:
return DEAD_BREVE;
case DEAD_CARON:
return DEAD_CARON;
case DEAD_CEDILLA:
return DEAD_CEDILLA;
case DEAD_CIRCUMFLEX:
return DEAD_CIRCUMFLEX;
case DEAD_DIAERESIS:
return DEAD_DIAERESIS;
case DEAD_DOUBLEACUTE:
return DEAD_DOUBLEACUTE;
case DEAD_GRAVE:
return DEAD_GRAVE;
case DEAD_IOTA:
return DEAD_IOTA;
case DEAD_MACRON:
return DEAD_MACRON;
case DEAD_OGONEK:
return DEAD_OGONEK;
case DEAD_SEMIVOICED_SOUND:
return DEAD_SEMIVOICED_SOUND;
case DEAD_TILDE:
return DEAD_TILDE;
case DEAD_VOICED_SOUND:
return DEAD_VOICED_SOUND;
case DELETE:
return DELETE;
case DIGIT0:
return NUM_0;
case DIGIT1:
return NUM_1;
case DIGIT2:
return NUM_2;
case DIGIT3:
return NUM_3;
case DIGIT4:
return NUM_4;
case DIGIT5:
return NUM_5;
case DIGIT6:
return NUM_6;
case DIGIT7:
return NUM_7;
case DIGIT8:
return NUM_8;
case DIGIT9:
return NUM_9;
case DOLLAR:
return DOLLAR;
case DOWN:
return DOWN;
case E:
return E;
case END:
return END;
case ENTER:
return ENTER;
case EQUALS:
return EQUAL;
case ESCAPE:
return ESCAPE;
case EXCLAMATION_MARK:
return EXCLAM;
case F:
return F;
case F1:
return F1;
case F10:
return F10;
case F11:
return F11;
case F12:
return F12;
case F13:
return F13;
case F14:
return F14;
case F15:
return F15;
case F16:
return F16;
case F17:
return F17;
case F18:
return F18;
case F19:
return F19;
case F2:
return F2;
case F20:
return F20;
case F21:
return F21;
case F22:
return F22;
case F23:
return F23;
case F24:
return F24;
case F3:
return F3;
case F4:
return F4;
case F5:
return F5;
case F6:
return F6;
case F7:
return F7;
case F8:
return F8;
case F9:
return F9;
case FIND:
return FIND;
case G:
return G;
case GREATER:
return GREATER;
case H:
return H;
case HELP:
return HELP;
case HIRAGANA:
return HIRAGANA;
case HOME:
return HOME;
case I:
return I;
case INSERT:
return INSERT;
case J:
return J;
case K:
return K;
case KANA_LOCK:
return KANA_LOCK;
case KANJI:
return KANJI;
case KATAKANA:
return KATAKANA;
case KP_DOWN:
return KP_DOWN;
case KP_LEFT:
return KP_LEFT;
case KP_RIGHT:
return KP_RIGHT;
case KP_UP:
return KP_UP;
case L:
return L;
case LEFT:
return LEFT;
case LEFT_PARENTHESIS:
return PAREN_LEFT;
case LESS:
return LESS;
case M:
return M;
case MINUS:
return MINUS;
case MULTIPLY:
return MULTIPLY;
case MUTE:
return AUDIO_MUTE;
case N:
return N;
case NUMBER_SIGN:
return NUMBER_SIGN;
case NUMPAD0:
return KP_0;
case NUMPAD1:
return KP_1;
case NUMPAD2:
return KP_2;
case NUMPAD3:
return KP_3;
case NUMPAD4:
return KP_4;
case NUMPAD5:
return KP_5;
case NUMPAD6:
return KP_6;
case NUMPAD7:
return KP_7;
case NUMPAD8:
return KP_8;
case NUMPAD9:
return KP_9;
case NUM_LOCK:
return NUM_LOCK;
case O:
return O;
case OPEN_BRACKET:
return BRACKET_LEFT;
case P:
return P;
case PAGE_DOWN:
return PAGE_DOWN;
case PAGE_UP:
return PAGE_UP;
case PAUSE:
return PAUSE;
case PERIOD:
return PERIOD;
case PLAY:
return AUDIO_PLAY;
case PLUS:
return PLUS;
case PREVIOUS_CANDIDATE:
return PREVIOUS_CANDIDATE;
case Q:
return Q;
case R:
return R;
case RIGHT:
return RIGHT;
case RIGHT_PARENTHESIS:
return PAREN_RIGHT;
case S:
return S;
case SCROLL_LOCK:
return SCROLL_LOCK;
case SEMICOLON:
return SEMICOLON;
case SLASH:
return SLASH;
case SPACE:
return SPACE;
case STOP:
return STOP;
case SUBTRACT:
return KP_SUBTRACT;
case T:
return T;
case TAB:
return TAB;
case TRACK_NEXT:
return AUDIO_NEXT;
case TRACK_PREV:
return AUDIO_PREV;
case U:
return U;
case UNDERSCORE:
return UNDERSCORE;
case UNDO:
return UNDO;
case UP:
return UP;
case V:
return V;
case VOLUME_DOWN:
return AUDIO_LOWER_VOLUME;
case VOLUME_UP:
return AUDIO_RAISE_VOLUME;
case W:
return W;
case X:
return X;
case Y:
return Y;
case Z:
return Z;
default:
return ERROR;
}
}
/**
* Converts an AWT key into a X11 keysym.
*
* @param awtKey
* @return
*/
public static int awtKeyToX11Keysym(int awtKey){
switch(awtKey){
case KeyEvent.VK_ENTER:
return RETURN;
case KeyEvent.VK_BACK_SPACE:
return BACKSPACE;
case KeyEvent.VK_TAB:
return TAB;
case KeyEvent.VK_CANCEL:
return CANCEL;
case KeyEvent.VK_CLEAR:
return CLEAR;
case KeyEvent.VK_SHIFT:
return SHIFT_L;
case KeyEvent.VK_CONTROL:
return CONTROL_L;
case KeyEvent.VK_ALT:
return ALT_L;
case KeyEvent.VK_PAUSE:
return PAUSE;
case KeyEvent.VK_CAPS_LOCK:
return CAPS_LOCK;
case KeyEvent.VK_ESCAPE:
return ESCAPE;
case KeyEvent.VK_SPACE:
return SPACE;
case KeyEvent.VK_PAGE_UP:
return PAGE_UP;
case KeyEvent.VK_PAGE_DOWN:
return PAGE_DOWN;
case KeyEvent.VK_END:
return END;
case KeyEvent.VK_HOME:
return HOME;
case KeyEvent.VK_LEFT:
return LEFT;
case KeyEvent.VK_UP:
return UP;
case KeyEvent.VK_RIGHT:
return RIGHT;
case KeyEvent.VK_DOWN:
return DOWN;
case KeyEvent.VK_COMMA:
return COMMA;
case KeyEvent.VK_MINUS:
return MINUS;
case KeyEvent.VK_PERIOD:
return PERIOD;
case KeyEvent.VK_SLASH:
return SLASH;
case KeyEvent.VK_0:
return NUM_0;
case KeyEvent.VK_1:
return NUM_1;
case KeyEvent.VK_2:
return NUM_2;
case KeyEvent.VK_3:
return NUM_3;
case KeyEvent.VK_4:
return NUM_4;
case KeyEvent.VK_5:
return NUM_5;
case KeyEvent.VK_6:
return NUM_6;
case KeyEvent.VK_7:
return NUM_7;
case KeyEvent.VK_8:
return NUM_8;
case KeyEvent.VK_9:
return NUM_9;
case KeyEvent.VK_SEMICOLON:
return SEMICOLON;
case KeyEvent.VK_EQUALS:
return EQUAL;
case KeyEvent.VK_A:
return A;
case KeyEvent.VK_B:
return B;
case KeyEvent.VK_C:
return C;
case KeyEvent.VK_D:
return D;
case KeyEvent.VK_E:
return E;
case KeyEvent.VK_F:
return F;
case KeyEvent.VK_G:
return G;
case KeyEvent.VK_H:
return H;
case KeyEvent.VK_I:
return I;
case KeyEvent.VK_J:
return J;
case KeyEvent.VK_K:
return K;
case KeyEvent.VK_L:
return L;
case KeyEvent.VK_M:
return M;
case KeyEvent.VK_N:
return N;
case KeyEvent.VK_O:
return O;
case KeyEvent.VK_P:
return P;
case KeyEvent.VK_Q:
return Q;
case KeyEvent.VK_R:
return R;
case KeyEvent.VK_S:
return S;
case KeyEvent.VK_T:
return T;
case KeyEvent.VK_U:
return U;
case KeyEvent.VK_V:
return V;
case KeyEvent.VK_W:
return W;
case KeyEvent.VK_X:
return X;
case KeyEvent.VK_Y:
return Y;
case KeyEvent.VK_Z:
return Z;
case KeyEvent.VK_OPEN_BRACKET:
return BRACKET_LEFT;
case KeyEvent.VK_BACK_SLASH:
return BACKSLASH;
case KeyEvent.VK_CLOSE_BRACKET:
return BRACKET_LEFT;
case KeyEvent.VK_NUMPAD0:
return KP_0;
case KeyEvent.VK_NUMPAD1:
return KP_1;
case KeyEvent.VK_NUMPAD2:
return KP_2;
case KeyEvent.VK_NUMPAD3:
return KP_3;
case KeyEvent.VK_NUMPAD4:
return KP_4;
case KeyEvent.VK_NUMPAD5:
return KP_5;
case KeyEvent.VK_NUMPAD6:
return KP_6;
case KeyEvent.VK_NUMPAD7:
return KP_7;
case KeyEvent.VK_NUMPAD8:
return KP_8;
case KeyEvent.VK_NUMPAD9:
return KP_9;
case KeyEvent.VK_MULTIPLY:
return KP_MULTIPLY;
case KeyEvent.VK_ADD:
return KP_ADD;
case KeyEvent.VK_SEPARATER:
return KP_SEPARATOR;
case KeyEvent.VK_SUBTRACT:
return KP_SUBTRACT;
case KeyEvent.VK_DECIMAL:
return KP_DECIMAL;
case KeyEvent.VK_DIVIDE:
return KP_DIVIDE;
case KeyEvent.VK_DELETE:
return DELETE;
case KeyEvent.VK_NUM_LOCK:
return NUM_LOCK;
case KeyEvent.VK_SCROLL_LOCK:
return SCROLL_LOCK;
case KeyEvent.VK_F1:
return F1;
case KeyEvent.VK_F2:
return F2;
case KeyEvent.VK_F3:
return F3;
case KeyEvent.VK_F4:
return F4;
case KeyEvent.VK_F5:
return F5;
case KeyEvent.VK_F6:
return F6;
case KeyEvent.VK_F7:
return F7;
case KeyEvent.VK_F8:
return F8;
case KeyEvent.VK_F9:
return F9;
case KeyEvent.VK_F10:
return F10;
case KeyEvent.VK_F11:
return F11;
case KeyEvent.VK_F12:
return F12;
case KeyEvent.VK_F13:
return F13;
case KeyEvent.VK_F14:
return F14;
case KeyEvent.VK_F15:
return F15;
case KeyEvent.VK_F16:
return F16;
case KeyEvent.VK_F17:
return F17;
case KeyEvent.VK_F18:
return F18;
case KeyEvent.VK_F19:
return F19;
case KeyEvent.VK_F20:
return F20;
case KeyEvent.VK_F21:
return F21;
case KeyEvent.VK_F22:
return F22;
case KeyEvent.VK_F23:
return F23;
case KeyEvent.VK_F24:
return F24;
case KeyEvent.VK_PRINTSCREEN:
return PRINT;
case KeyEvent.VK_INSERT:
return INSERT;
case KeyEvent.VK_HELP:
return HELP;
case KeyEvent.VK_META:
return META_L;
case KeyEvent.VK_BACK_QUOTE:
return QUOTE_LEFT;
case KeyEvent.VK_QUOTE:
return QUOTE_RIGHT;
case KeyEvent.VK_KP_UP:
return KP_UP;
case KeyEvent.VK_KP_DOWN:
return KP_DOWN;
case KeyEvent.VK_KP_LEFT:
return KP_LEFT;
case KeyEvent.VK_KP_RIGHT:
return KP_RIGHT;
case KeyEvent.VK_DEAD_GRAVE:
return DEAD_GRAVE;
case KeyEvent.VK_DEAD_ACUTE:
return DEAD_ACUTE;
case KeyEvent.VK_DEAD_CIRCUMFLEX:
return DEAD_CIRCUMFLEX;
case KeyEvent.VK_DEAD_TILDE:
return DEAD_TILDE;
case KeyEvent.VK_DEAD_MACRON:
return DEAD_MACRON;
case KeyEvent.VK_DEAD_BREVE:
return DEAD_BREVE;
case KeyEvent.VK_DEAD_ABOVEDOT:
return DEAD_ABOVEDOT;
case KeyEvent.VK_DEAD_DIAERESIS:
return DEAD_DIAERESIS;
case KeyEvent.VK_DEAD_ABOVERING:
return DEAD_ABOVERING;
case KeyEvent.VK_DEAD_DOUBLEACUTE:
return DEAD_DOUBLEACUTE;
case KeyEvent.VK_DEAD_CARON:
return DEAD_CARON;
case KeyEvent.VK_DEAD_CEDILLA:
return DEAD_CEDILLA;
case KeyEvent.VK_DEAD_OGONEK:
return DEAD_OGONEK;
case KeyEvent.VK_DEAD_IOTA:
return DEAD_IOTA;
case KeyEvent.VK_DEAD_VOICED_SOUND:
return DEAD_VOICED_SOUND;
case KeyEvent.VK_DEAD_SEMIVOICED_SOUND:
return DEAD_SEMIVOICED_SOUND;
case KeyEvent.VK_AMPERSAND:
return AMPERSAND;
case KeyEvent.VK_ASTERISK:
return ASTERISK;
case KeyEvent.VK_QUOTEDBL:
return QUOTE_DBL;
case KeyEvent.VK_LESS:
return LESS;
case KeyEvent.VK_GREATER:
return GREATER;
case KeyEvent.VK_BRACELEFT:
return BRACE_LEFT;
case KeyEvent.VK_BRACERIGHT:
return BRACE_RIGHT;
case KeyEvent.VK_AT:
return AT;
case KeyEvent.VK_COLON:
return COLON;
case KeyEvent.VK_CIRCUMFLEX:
return ASCII_CIRCUM;
case KeyEvent.VK_DOLLAR:
return DOLLAR;
case KeyEvent.VK_EURO_SIGN:
return CURR_EURO;
case KeyEvent.VK_EXCLAMATION_MARK:
return EXCLAM;
case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
return EXCLAM_DOWN;
case KeyEvent.VK_LEFT_PARENTHESIS:
return PAREN_LEFT;
case KeyEvent.VK_NUMBER_SIGN:
return NUMBER_SIGN;
case KeyEvent.VK_PLUS:
return PLUS;
case KeyEvent.VK_RIGHT_PARENTHESIS:
return PAREN_RIGHT;
case KeyEvent.VK_UNDERSCORE:
return UNDERSCORE;
case KeyEvent.VK_WINDOWS:
return SUPER_L;
case KeyEvent.VK_CONTEXT_MENU:
return MENU;
case KeyEvent.VK_FINAL:
return 0; //????
case KeyEvent.VK_CONVERT:
return 0; //????
case KeyEvent.VK_NONCONVERT:
return 0; //????
case KeyEvent.VK_ACCEPT:
return 0; //????
case KeyEvent.VK_MODECHANGE:
return MODE_SWITCH;
case KeyEvent.VK_KANA:
return KANA_SHIFT;
case KeyEvent.VK_KANJI:
return KANJI;
case KeyEvent.VK_ALPHANUMERIC:
return EISU_SHIFT;
case KeyEvent.VK_KATAKANA:
return KATAKANA;
case KeyEvent.VK_HIRAGANA:
return HIRAGANA;
case KeyEvent.VK_FULL_WIDTH:
return 0; //????
case KeyEvent.VK_HALF_WIDTH:
return 0; //????
case KeyEvent.VK_ROMAN_CHARACTERS:
return 0; //????
case KeyEvent.VK_ALL_CANDIDATES:
return MULTIPLE_CANDIDATE;
case KeyEvent.VK_PREVIOUS_CANDIDATE:
return PREVIOUS_CANDIDATE;
case KeyEvent.VK_CODE_INPUT:
return CODEINPUT;
case KeyEvent.VK_JAPANESE_KATAKANA:
return KATAKANA;
case KeyEvent.VK_JAPANESE_HIRAGANA:
return HIRAGANA;
case KeyEvent.VK_JAPANESE_ROMAN:
return 0; //????
case KeyEvent.VK_KANA_LOCK:
return KANA_LOCK;
case KeyEvent.VK_INPUT_METHOD_ON_OFF:
return 0; //????
case KeyEvent.VK_CUT:
return 0; //????
case KeyEvent.VK_COPY:
return 0; //????
case KeyEvent.VK_PASTE:
return 0; //????
case KeyEvent.VK_UNDO:
return UNDO;
case KeyEvent.VK_AGAIN:
return REDO;
case KeyEvent.VK_FIND:
return FIND;
case KeyEvent.VK_PROPS:
return 0; //????
case KeyEvent.VK_STOP:
return CANCEL;
case KeyEvent.VK_COMPOSE:
return MULTI_KEY;
case KeyEvent.VK_ALT_GRAPH:
return 0; //????
case KeyEvent.VK_BEGIN:
return BEGIN;
case KeyEvent.VK_UNDEFINED:
return 0;
default:
return 0;
}
}
}
| 48,427 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
SingleInstanceController.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/SingleInstanceController.java | package net.joshuad.hypnos;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.joshuad.hypnos.SocketCommand.CommandType;
public class SingleInstanceController {
private static final Logger LOGGER = Logger.getLogger( SingleInstanceController.class.getName() );
int port = 49485;
boolean isFirstInstance = true;
ServerSocket serverSocket;
public SingleInstanceController() {
if ( Hypnos.isDeveloping() ) {
port = 49486;
}
try {
serverSocket = new ServerSocket ( port, 0, InetAddress.getByName(null) );
} catch ( IOException e ) {
isFirstInstance = false;
}
}
public boolean isFirstInstance () {
return isFirstInstance;
}
public boolean startCLICommandListener ( Hypnos hypnos ) {
if ( !isFirstInstance ) {
throw new IllegalStateException( "Cannot start a command line listener if we are not the first instance." );
}
Thread t = new Thread( () -> {
while ( true ) {
try {
Socket clientSocket = serverSocket.accept(); // It blocks here indefinitely while listening
ObjectInputStream in = new ObjectInputStream( clientSocket.getInputStream() );
ObjectOutputStream out = new ObjectOutputStream( clientSocket.getOutputStream() );
Object dataIn = in.readObject();
if ( dataIn instanceof List ) {
List <SocketCommand> items = (List <SocketCommand>) dataIn;
hypnos.applyCLICommands( items );
}
out.writeObject( new SocketCommand ( CommandType.CONTROL, SocketCommand.RECEIPT_ACKNOWLEDGED ) );
} catch ( Exception e ) {
LOGGER.log( Level.INFO, e.getClass() + ": Read error at commandline parser", e );
}
}
} );
t.setName( "CLI Listener" );
t.setDaemon( true );
t.start();
return true;
}
public boolean sendCommandsThroughSocket( List <SocketCommand> commands ) {
try (
Socket clientSocket = new Socket( InetAddress.getByName(null), port );
ObjectOutputStream out = new ObjectOutputStream( clientSocket.getOutputStream() );
ObjectInputStream in = new ObjectInputStream( clientSocket.getInputStream() );
){
//TODO: This timeout isn't working on windows
clientSocket.setSoTimeout( 100 );
out.writeObject( commands );
Object dataIn = in.readObject();
if ( ((SocketCommand)dataIn).getObject().equals( SocketCommand.RECEIPT_ACKNOWLEDGED ) ) {
return true;
}
} catch ( Exception e ) {
//TODO: This log is only called by the second instance of hypnos. Maybe just use printlns instead?
//TODO: Also maybe segregate out code that the second instance uses into its own class
LOGGER.log( Level.INFO, "Error sending commands through socket, UI may not accept commands.", e );
}
return false;
}
}
| 2,931 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
AlphanumComparator.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/AlphanumComparator.java | package net.joshuad.hypnos;
/*
* The Alphanum Algorithm is an improved sorting algorithm for strings
* containing numbers. Instead of sorting numbers in ASCII order like
* a standard sort, this algorithm sorts numbers in numeric order.
*
* The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
*
* Released under the MIT License - https://opensource.org/licenses/MIT
*
* Copyright 2007-2017 David Koelle
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Modified by JDH - 2017/12/19 - To allow case-insensitive handling */
import java.util.Comparator;
/**
* This is an updated version with enhancements made by Daniel Migowski,
* Andre Bogus, and David Koelle. Updated by David Koelle in 2017.
*
* To use this class:
* Use the static "sort" method from the java.util.Collections class:
* Collections.sort(your list, new AlphanumComparator());
*/
public class AlphanumComparator implements Comparator<String>
{
CaseHandling caseHandling = CaseHandling.CASE_SENSITIVE;
public AlphanumComparator() {}
public AlphanumComparator( CaseHandling caseHandling )
{
this.caseHandling = caseHandling;
}
public enum CaseHandling
{
CASE_INSENSITIVE, CASE_SENSITIVE
}
private final boolean isDigit(char ch)
{
return ((ch >= 48) && (ch <= 57));
}
/** Length of string is passed in for improved efficiency (only need to calculate it once) **/
private final String getChunk(String s, int slength, int marker)
{
StringBuilder chunk = new StringBuilder();
char c = s.charAt(marker);
chunk.append(c);
marker++;
if (isDigit(c))
{
while (marker < slength)
{
c = s.charAt(marker);
if (!isDigit(c))
break;
chunk.append(c);
marker++;
}
} else
{
while (marker < slength)
{
c = s.charAt(marker);
if (isDigit(c))
break;
chunk.append(c);
marker++;
}
}
return chunk.toString();
}
public int compare(String s1, String s2)
{
if ((s1 == null) || (s2 == null))
{
return 0;
}
if (caseHandling == CaseHandling.CASE_INSENSITIVE)
{
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
}
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
}
else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
} | 4,943 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
UpdateChecker.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/UpdateChecker.java | package net.joshuad.hypnos;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.joshuad.hypnos.fxui.SettingsWindow;
public class UpdateChecker {
private static final Logger LOGGER = Logger.getLogger( SettingsWindow.class.getName() );
private DateFormat releaseDateFormat = new SimpleDateFormat ( "yyyy-MM-dd" );
public UpdateChecker() {}
public boolean updateAvailable () {
if ( !UpdateChecker.class.getResource( "UpdateChecker.class" ).toString().startsWith( "jar" ) ) {
if ( Hypnos.isDeveloping() ) {
//This is what happens when I am working on the project and I don't want to see extraneous prints.
return false;
} else {
LOGGER.info( "Not running from a jar, so we don't have access to this version's release date. Not checking for updates. "
+ "You may want to download a release binary or build a jar using the provided ant build file to be able to check for updates."
);
return false;
}
}
Date newestVersionDate = getNewestVersionDateFromWeb ();
Date thisVersionDate = null;
try {
thisVersionDate = releaseDateFormat.parse( Hypnos.getBuildDate() );
} catch ( Exception e ) {
LOGGER.log ( Level.WARNING, "Unable to parse this release's date, assuming no update available.", e );
return false;
}
if ( newestVersionDate == null ) return false;
return newestVersionDate.after( thisVersionDate );
}
private Date getNewestVersionDateFromWeb () {
try {
URL url = new URL( "http://hypnosplayer.org/update-info/current-version-date" );
String line;
URLConnection con = url.openConnection();
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
try (
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
) {
line = br.readLine();
return releaseDateFormat.parse ( line );
} catch ( Exception e ) {
LOGGER.log ( Level.WARNING, "Unable to fetch current version date from web. Assuming no update available.", e );
return null;
}
} catch ( Exception e ) {
LOGGER.log ( Level.WARNING, "Unable to fetch current version date from web. Assuming no updates available.", e );
return null;
}
}
}
| 2,566 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
MultiFileTextTagPair.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/MultiFileTextTagPair.java | package net.joshuad.hypnos;
import org.jaudiotagger.tag.FieldKey;
public class MultiFileTextTagPair {
private FieldKey key;
private String value;
private boolean multiValue = false;
public MultiFileTextTagPair ( FieldKey key, String value ) {
this.key = key;
this.value = value;
}
public void setValue ( String value ) {
this.value = value;
multiValue = false;
}
public void anotherFileValue ( String newValue ) {
if ( ! newValue.equals( value ) ) {
multiValue = true;
}
}
public boolean isMultiValue () {
return multiValue;
}
public String getTagName () {
String retMe = key.toString();
if ( key == FieldKey.TRACK ) retMe = "TRACK NUMBER";
else if ( key == FieldKey.DISC_NO ) retMe = "DISC NUMBER";
else if ( key == FieldKey.MUSICBRAINZ_RELEASE_TYPE ) retMe = "RELEASE TYPE";
return retMe.replaceAll( "_", " " );
}
public FieldKey getKey() {
return key;
}
public String getValue () {
if ( multiValue ) {
return "<Multiple Values>";
} else {
return value;
}
}
} | 1,043 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
CLIParser.java | /FileExtraction/Java_unseen/JoshuaD84_HypnosMusicPlayer/src/net/joshuad/hypnos/CLIParser.java | package net.joshuad.hypnos;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLIParser {
private static final Logger LOGGER = Logger.getLogger(CLIParser.class.getName());
// REFACTOR: Combine these into an Enum with the things in SingleInstanceController and the strings in constructor below.
private static final String HELP = "help";
private static final String NEXT = "next";
private static final String PREVIOUS = "previous";
private static final String PAUSE = "pause";
private static final String PLAY = "play";
private static final String TOGGLE_PAUSE = "play-pause";
private static final String STOP = "stop";
private static final String TOGGLE_MINIMIZED = "toggle-window";
private static final String VOLUME_DOWN = "volume-down";
private static final String VOLUME_UP = "volume-up";
private static final String SEEK_BACK = "seek-back";
private static final String SEEK_FORWARD = "seek-forward";
private static final String BASE_DIR = "base-dir";
CommandLineParser parser;
Options options;
Options helpOptions;
public CLIParser() {
options = new Options();
options.addOption(null, HELP, false, "Print this message");
options.addOption(null, NEXT, false, "Jump to next track");
options.addOption(null, PREVIOUS, false, "Jump to previous track");
options.addOption(null, PAUSE, false, "Pause Playback");
options.addOption(null, PLAY, false, "Start Playback");
options.addOption(null, TOGGLE_PAUSE, false, "Toggle play/pause mode");
options.addOption(null, STOP, false, "Stop playback");
options.addOption(null, TOGGLE_MINIMIZED, false, "Toggle the minimized state");
options.addOption(null, VOLUME_DOWN, false, "Turn down the volume");
options.addOption(null, VOLUME_UP, false, "Turn up the volume");
options.addOption(null, SEEK_BACK, false, "Seek back 5 seconds");
options.addOption(null, SEEK_FORWARD, false, "Seek forward 5 seconds");
options.addOption(null, BASE_DIR, true, "Define the base directory from which to interpret relative file arguments");
parser = new DefaultParser();
helpOptions = new Options();
for (Option option : options.getOptions()) {
if (!option.getLongOpt().equals(BASE_DIR)) {
helpOptions.addOption(option);
}
}
}
public ArrayList<SocketCommand> parseCommands(String[] args) {
ArrayList<SocketCommand> retMe = new ArrayList<SocketCommand>();
try {
CommandLine line = parser.parse(options, args);
if (line.hasOption(HELP)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("hypnos <options>", helpOptions);
System.exit(0);
}
if (line.hasOption(PLAY)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.PLAY));
}
if (line.hasOption(NEXT)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.NEXT));
}
if (line.hasOption(PREVIOUS)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.PREVIOUS));
}
if (line.hasOption(TOGGLE_PAUSE)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.TOGGLE_PAUSE));
}
if (line.hasOption(PAUSE)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.PAUSE));
}
if (line.hasOption(STOP)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.STOP));
}
if (line.hasOption(TOGGLE_MINIMIZED)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.TOGGLE_MINIMIZED));
}
if (line.hasOption(VOLUME_DOWN)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.VOLUME_DOWN));
}
if (line.hasOption(VOLUME_UP)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.VOLUME_UP));
}
if (line.hasOption(SEEK_BACK)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.SEEK_BACK));
}
if (line.hasOption(SEEK_FORWARD)) {
retMe.add(new SocketCommand(SocketCommand.CommandType.CONTROL, SocketCommand.SEEK_FORWARD));
}
Path baseDir = Paths.get(System.getProperty("user.dir"));
if (line.hasOption(BASE_DIR)) {
baseDir = Paths.get(line.getOptionValue(BASE_DIR));
}
ArrayList<File> filesToLoad = new ArrayList<File>();
for (String leftOverArgument : line.getArgList()) {
Path argumentPath = Paths.get(leftOverArgument).normalize();
if (!argumentPath.isAbsolute()) {
argumentPath = baseDir.resolve(argumentPath).toAbsolutePath().normalize();
}
filesToLoad.add(argumentPath.toFile());
}
if (filesToLoad.size() > 0) {
retMe.add(new SocketCommand(SocketCommand.CommandType.SET_TRACKS, filesToLoad));
}
} catch (ParseException e) {
LOGGER.log(Level.WARNING, "Unable to parse command line arguments. ", e);
}
return retMe;
}
}
| 5,254 | Java | .java | JoshuaD84/HypnosMusicPlayer | 21 | 2 | 0 | 2017-05-02T07:06:13Z | 2020-08-30T02:20:45Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.