index
int64 0
36.5k
| proj_name
stringclasses 162
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
51
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_func_body
int64 1
5.26k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
|
---|---|---|---|---|---|---|---|---|---|---|
363 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/ZipUtil.java | ZipUtil | clean | class ZipUtil {
private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);
private ZipUtil() {
}
/**
* 创建ZIP文件
* @param sourcePath 文件或文件夹路径
* @param zipPath 生成的zip文件存在路径(包括文件名)
* @param isDrop 是否删除原文件:true删除、false不删除
*/
public static void createZip(String sourcePath, String zipPath,Boolean isDrop) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
//createXmlFile(sourcePath,"293.xml");
writeZip(new File(sourcePath), "", zos,isDrop);
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}
}
}
/**
* 清空文件和文件目录
*
* @param f
*/
public static void clean(File f) throws Exception {<FILL_FUNCTION_BODY>}
private static void writeZip(File file, String parentPath, ZipOutputStream zos,Boolean isDrop) {
if(file.exists()){
if(file.isDirectory()){//处理文件夹
parentPath+=file.getName()+File.separator;
File [] files=file.listFiles();
if(files.length != 0)
{
for(File f:files){
writeZip(f, parentPath, zos,isDrop);
}
}
else
{ //空目录则创建当前目录
try {
zos.putNextEntry(new ZipEntry(parentPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
FileInputStream fis=null;
try {
fis=new FileInputStream(file);
ZipEntry ze = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(ze);
byte [] content=new byte[1024];
int len;
while((len=fis.read(content))!=-1){
zos.write(content,0,len);
}
} catch (FileNotFoundException e) {
log.error("创建ZIP文件失败",e);
} catch (IOException e) {
log.error("创建ZIP文件失败",e);
}finally{
try {
if(fis!=null){
fis.close();
}
if(isDrop){
clean(file);
}
}catch(IOException e){
log.error("创建ZIP文件失败",e);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
// ZipUtil.createZip("/Users/keyuan/Documents/GIT/my-gitlab/dw/dwsurvey_b1/dwsurvey/target/dwsurvey/file/402880e864e15c150164e3917b930000", "/Users/keyuan/Documents/GIT/my-gitlab/dw/dwsurvey_b1/dwsurvey/target/dwsurvey/file/402880e864e15c150164e3917b930000.zip",false);
}
} |
String cs[] = f.list();
if (cs == null || cs.length <= 0) {
boolean isDelete = f.delete();
if (!isDelete) {
throw new Exception(f.getName() + "文件删除失败!");
}
} else {
for (int i = 0; i < cs.length; i++) {
String cn = cs[i];
String cp = f.getPath() + File.separator + cn;
File f2 = new File(cp);
if (f2.exists() && f2.isFile()) {
boolean isDelete = f2.delete();
if (!isDelete) {
throw new Exception(f2.getName() + "文件删除失败!");
}
} else if (f2.exists() && f2.isDirectory()) {
clean(f2);
}
}
boolean isDelete = f.delete();
if (!isDelete) {
throw new Exception(f.getName() + "文件删除失败!");
}
}
| 438 | 984 | 267 | 1,251 |
364 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/excel/ReadExcelUtil.java | ReadExcelUtil | getCellStringValue | class ReadExcelUtil {
public static Workbook getWorkBook(String filePath){
POIFSFileSystem fs;
Workbook wb = null;
try {
wb = new XSSFWorkbook(filePath);
} catch (Exception e) {
try {
fs = new POIFSFileSystem(new FileInputStream(filePath));
wb = new HSSFWorkbook(fs);
} catch (IOException e1) {
e1.printStackTrace();
}
}
return wb;
}
public static HSSFSheet getHSSFSheet(HSSFWorkbook wb, int index) {
HSSFSheet sheet = wb.getSheetAt(0);
return sheet;
}
public static String getValueByRowCol(Row sfrow, int col){
Cell cell = sfrow.getCell((short)col);
if (cell == null)
return "";
String msg = getCellStringValue(cell);
return msg;
}
public static String getValueByCol(Cell sfCell){
String msg = getCellStringValue(sfCell);
return msg;
}
public static void reader(String filePath) {
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(3);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getCellStringValue(Cell cell) {<FILL_FUNCTION_BODY>}
public static int getRowSize(Sheet sheet){
return sheet.getLastRowNum();
}
public static int getCellSize(HSSFRow sfRow){
return sfRow.getLastCellNum();
}
public static void main(String[] args) {
reader("F://terchers.xls");
}
} |
String cellValue = "";
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
if (cellValue.trim().equals("") || cellValue.trim().length() <= 0) {
cellValue = " ";
}
break;
case NUMERIC:
// cellValue = String.valueOf(cell.getNumericCellValue());
DecimalFormat formatter = new DecimalFormat("######");
cellValue = formatter.format(cell.getNumericCellValue());
break;
case FORMULA:
cell.setCellType(CellType.NUMERIC);
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BLANK:
cellValue = " ";
break;
case BOOLEAN:
break;
case ERROR:
break;
default:
break;
}
return cellValue;
| 38 | 584 | 280 | 864 |
365 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/excel/XLSExportUtil.java | XLSExportUtil | exportXLS | class XLSExportUtil {
// 设置cell编码解决中文高位字节截断
// 定制日期格式
private static String DATE_FORMAT = " m/d/yy "; // "m/d/yy h:mm"
// 定制浮点数格式
private static String NUMBER_FORMAT = " #,##0.00 ";
private String xlsFileName;
private String path;
private HSSFWorkbook workbook;
private HSSFSheet sheet;
private HSSFRow row;
/**
* 初始化Excel
*
* @param fileName
* 导出文件名
*/
public XLSExportUtil(String fileName,String path) {
this.xlsFileName = fileName;
this.path=path;
this.workbook = new HSSFWorkbook();
this.sheet = workbook.createSheet();
}
/** */
/**
* 导出Excel文件
*
*/
public void exportXLS() throws Exception {<FILL_FUNCTION_BODY>}
/** */
/**
* 增加一行
*
* @param index
* 行号
*/
public void createRow(int index) {
this.row = this.sheet.createRow(index);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
@SuppressWarnings("deprecation")
public void setCell(int index, String value) {
HSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.STRING);
cell.setCellValue(value);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
@SuppressWarnings("deprecation")
public void setCell(int index, Calendar value) {
HSSFCell cell = this.row.createCell((short) index);
cell.setCellValue(value.getTime());
HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式
cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
public void setCell(int index, int value) {
HSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
public void setCell(int index, double value) {
HSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell样式
HSSFDataFormat format = workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式
cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式
}
} |
try {
File file=new File(path);
if(!file.exists()) {
file.mkdirs();
}
FileOutputStream fOut = new FileOutputStream(path+File.separator+xlsFileName);
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
throw new Exception(" 生成导出Excel文件出错! ", e);
} catch (IOException e) {
throw new Exception(" 写入Excel文件出错! ", e);
}
| 27 | 1,079 | 168 | 1,247 |
366 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/excel/XLSXExportUtil.java | XLSXExportUtil | exportXLS | class XLSXExportUtil {
// 设置cell编码解决中文高位字节截断
// 定制日期格式
private static String DATE_FORMAT = " m/d/yy "; // "m/d/yy h:mm"
// 定制浮点数格式
private static String NUMBER_FORMAT = " #,##0.00 ";
private String xlsFileName;
private String path;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private XSSFRow row;
private XSSFCellStyle cellStyle;
private XSSFDataFormat dataFormat ;
/**
* 初始化Excel
*
* @param fileName
* 导出文件名
*/
public XLSXExportUtil(String fileName, String path) {
this.xlsFileName = fileName;
this.path=path;
this.workbook = new XSSFWorkbook();
this.sheet = workbook.createSheet();
this.cellStyle = workbook.createCellStyle(); // 建立新的cell样式;
this.dataFormat = workbook.createDataFormat();
// SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook1, 100);
}
/** */
/**
* 导出Excel文件
*
*/
public void exportXLS() throws Exception {<FILL_FUNCTION_BODY>}
/** */
/**
* 增加一行
*
* @param index
* 行号
*/
public void createRow(int index) {
this.row = this.sheet.createRow(index);
}
public void setCellBlue(int index, String value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.STRING);
// CellStyle style = workbook.createCellStyle();
// Font font = workbook.createFont();
// font.setColor(IndexedColors.BLUE.getIndex());
// style.setFont(font);
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIME.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
cell.setCellValue(value);
}
public void setCellYellow(int index, String value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.STRING);
// Font font = workbook.createFont();
// font.setColor(IndexedColors.BLUE.getIndex());
// style.setFont(font);
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
cell.setCellValue(value);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
@SuppressWarnings("deprecation")
public void setCell(int index, String value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.STRING);
cell.setCellValue(value);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
@SuppressWarnings("deprecation")
public void setCell(int index, Calendar value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellValue(value.getTime());
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 设置cell样式为定制的日期格式
cell.setCellStyle(cellStyle); // 设置该cell日期的显示格式
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
public void setCell(int index, int value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
}
/** */
/**
* 设置单元格
*
* @param index
* 列号
* @param value
* 单元格填充值
*/
public void setCell(int index, double value) {
XSSFCell cell = this.row.createCell((short) index);
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
cellStyle.setDataFormat(dataFormat.getFormat(NUMBER_FORMAT)); // 设置cell样式为定制的浮点数格式
cell.setCellStyle(cellStyle); // 设置该cell浮点数的显示格式
}
} |
try {
File file=new File(path);
if(!file.exists()) {
file.mkdirs();
}
FileOutputStream fOut = new FileOutputStream(path+File.separator+xlsFileName);
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
throw new Exception(" 生成导出Excel文件出错! ", e);
} catch (IOException e) {
throw new Exception(" 写入Excel文件出错! ", e);
}
| 27 | 1,366 | 152 | 1,518 |
367 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/parsehtml/HtmlUtil.java | HtmlUtil | removeTagFromText | class HtmlUtil {
public static String removeTagFromText(String htmlStr) {<FILL_FUNCTION_BODY>}
} |
if (htmlStr == null || "".equals(htmlStr))
return "";
String textStr = "";
Pattern pattern;
java.util.regex.Matcher matcher;
try {
String regEx_remark = "<!--.+?-->";
// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
// }
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
// }
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String regEx_html1 = "<[^>]+";
htmlStr = htmlStr.replaceAll("\n", "");
htmlStr = htmlStr.replaceAll("\t", "");
htmlStr = htmlStr.replaceAll("\r", "");
pattern = Pattern.compile(regEx_remark);// 过滤注释标签
matcher = pattern.matcher(htmlStr);
htmlStr = matcher.replaceAll("");
pattern = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(htmlStr);
htmlStr = matcher.replaceAll(""); // 过滤script标签
pattern = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(htmlStr);
htmlStr = matcher.replaceAll(""); // 过滤style标签
pattern = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(htmlStr);
htmlStr = matcher.replaceAll(""); // 过滤html标签
pattern = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(htmlStr);
htmlStr = matcher.replaceAll(""); // 过滤html标签
htmlStr = htmlStr.replaceAll("\n[\\s| ]*\r", "");
htmlStr = htmlStr.replaceAll("<(.*)>(.*)<\\/(.*)>|<(.*)\\/>", "");
textStr = htmlStr.trim();
} catch (Exception e) {
e.printStackTrace();
}
return textStr;// dwv402880e666e15b790166e16222000000 返回文本字符串
| 102 | 36 | 846 | 882 |
369 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/security/DigestUtils.java | DigestUtils | digest | class DigestUtils {
private static final String SHA1 = "SHA-1";
private static final String MD5 = "MD5";
//-- String Hash function --//
/**
* 对输入字符串进行sha1散列, 返回Hex编码的结果.
*/
public static String sha1Hex(String input) {
byte[] digestResult = digest(input, SHA1);
return EncodeUtils.encodeHex(digestResult);
}
/**
* 对输入字符串进行sha1散列, 返回Base64编码的结果.
*/
public static String sha1Base64(String input) {
byte[] digestResult = digest(input, SHA1);
return EncodeUtils.encodeBase64(digestResult);
}
/**
* 对输入字符串进行sha1散列, 返回Base64编码的URL安全的结果.
*/
public static String sha1Base64UrlSafe(String input) {
byte[] digestResult = digest(input, SHA1);
return EncodeUtils.encodeUrlSafeBase64(digestResult);
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
*/
private static byte[] digest(String input, String algorithm) {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
return messageDigest.digest(input.getBytes());
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
//-- File Hash function --//
/**
* 对文件进行md5散列, 返回Hex编码结果.
*/
public static String md5Hex(InputStream input) throws IOException {
return digest(input, MD5);
}
/**
* 对文件进行sha1散列, 返回Hex编码结果.
*/
public static String sha1Hex(InputStream input) throws IOException {
return digest(input, SHA1);
}
private static String digest(InputStream input, String algorithm) throws IOException {<FILL_FUNCTION_BODY>}
} |
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return EncodeUtils.encodeHex(messageDigest.digest());
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
| 33 | 601 | 178 | 779 |
370 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/web/InitAppliction.java | InitAppliction | contextInitialized | class InitAppliction implements ServletContextListener {
public static String contextPath = null;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent sce) {<FILL_FUNCTION_BODY>}
} |
// TODO Auto-generated method stub
ServletContext servletContext = sce.getServletContext();
contextPath = servletContext.getContextPath();
| 10 | 90 | 43 | 133 |
371 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/common/utils/web/ServletUtils.java | ServletUtils | getParametersStartingWith | class ServletUtils {
//-- Content Type 定义 --//
public static final String EXCEL_TYPE = "application/vnd.ms-excel";
public static final String HTML_TYPE = "text/html";
public static final String JS_TYPE = "text/javascript";
public static final String JSON_TYPE = "application/json";
public static final String XML_TYPE = "text/xml";
public static final String TEXT_TYPE = "text/plain";
//-- Header 定义 --//
public static final String AUTHENTICATION_HEADER = "Authorization";
//-- 常用数值定义 --//
public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
/**
* 设置客户端缓存过期时间 的Header.
*/
public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
//Http 1.0 header
response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
//Http 1.1 header
response.setHeader("Cache-Control", "private, max-age=" + expiresSeconds);
}
/**
* 设置禁止客户端缓存的Header.
*/
public static void setDisableCacheHeader(HttpServletResponse response) {
//Http 1.0 header
response.setDateHeader("Expires", 1L);
response.addHeader("Pragma", "no-cache");
//Http 1.1 header
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
}
/**
* 设置LastModified Header.
*/
public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
response.setDateHeader("Last-Modified", lastModifiedDate);
}
/**
* 设置Etag Header.
*/
public static void setEtag(HttpServletResponse response, String etag) {
response.setHeader("ETag", etag);
}
/**
* 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
*
* 如果无修改, checkIfModify返回false ,设置304 not modify status.
*
* @param lastModified 内容的最后修改时间.
*/
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
long lastModified) {
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return false;
}
return true;
}
/**
* 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
*
* 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
*
* @param etag 内容的ETag.
*/
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
String headerValue = request.getHeader("If-None-Match");
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!"*".equals(headerValue)) {
StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(etag)) {
conditionSatisfied = true;
}
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader("ETag", etag);
return false;
}
}
return true;
}
/**
* 设置让浏览器弹出下载对话框的Header.
*
* @param fileName 下载后的文件名.
*/
public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
try {
//中文文件名支持
String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
} catch (UnsupportedEncodingException e) {
}
}
/**
* 取得带相同前缀的Request Parameters.
*
* 返回的结果的Parameter名已去除前缀.
*/
public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {<FILL_FUNCTION_BODY>}
/**
* 客户端对Http Basic验证的 Header进行编码.
*/
public static String encodeHttpBasic(String userName, String password) {
String encode = userName + ":" + password;
return "Basic " + EncodeUtils.encodeBase64(encode.getBytes());
}
} |
AssertUtils.notNull(request, "Request must not be null");
Enumeration paramNames = request.getParameterNames();
Map<String, Object> params = new TreeMap<String, Object>();
if (prefix == null) {
prefix = "";
}
while (paramNames != null && paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
if ("".equals(prefix) || paramName.startsWith(prefix)) {
String unprefixed = paramName.substring(prefix.length());
String[] values = request.getParameterValues(paramName);
if (values == null || values.length == 0) {
// Do nothing, no values found at all.
} else if (values.length > 1) {
params.put(unprefixed, values);
} else {
params.put(unprefixed, values[0]);
}
}
}
return params;
| 67 | 1,480 | 269 | 1,749 |
372 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/DwsurveyApplication.java | DwsurveyApplication | tomcatFactory | class DwsurveyApplication {
public static void main(String[] args) {
SpringApplication.run(DwsurveyApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory tomcatFactory(){<FILL_FUNCTION_BODY>}
} |
return new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
((StandardJarScanner) context.getJarScanner()).setScanManifest(false);
}
};
| 80 | 73 | 61 | 134 |
373 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/CorsConfig.java | CorsConfig | corsFilter | class CorsConfig {
// private static String AllowOrigin = "*";
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);//sessionid 多次访问一致
corsConfiguration.setAllowedOriginPatterns(getAllowOrigin());
// corsConfiguration.addAllowedOrigin("*");// 允许任何域名使用
corsConfiguration.addAllowedHeader("*");// 允许任何头
corsConfiguration.addAllowedMethod("*");// 允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public FilterRegistrationBean corsFilter() {<FILL_FUNCTION_BODY>}
/**
* 可以根据需求调整 AllowOrigin ,默认是所有
* @return
*/
public static List<String> getAllowOrigin() {
List<String> list = new ArrayList<>();
list.add("*");//所有域名
return list;
}
} |
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/file/**", buildConfig());
source.registerCorsConfiguration("/**", buildConfig());
CorsFilter corsFilter = new CorsFilter(source);
FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter);
bean.setOrder(0);
return bean;
| 76 | 261 | 101 | 362 |
374 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/HibernateConfig.java | HibernateConfig | hibernateProperties | class HibernateConfig {
@Autowired
private Environment environment;
@Autowired
private DataSource dataSource;
@Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setPhysicalNamingStrategy(new net.diaowen.common.plugs.mapper.SnakeCaseNamingStrategy());
sessionFactoryBean.setPackagesToScan("net.diaowen.common","net.diaowen.dwsurvey");//dao和entity的公共包
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
/* @Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactoryBean().getObject());
return transactionManager;
}*/
//获取hibernate配置
private Properties hibernateProperties() {<FILL_FUNCTION_BODY>}
} |
Properties properties = new Properties();
properties.setProperty("hibernate.current_session_context_class", environment.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));
properties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.setProperty("hibernate.show_sql", environment.getProperty("spring.jpa.properties.hibernate.show_sql"));
properties.setProperty("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql"));
properties.setProperty("hibernate.cache.use_second_level_cache", environment.getProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache"));
properties.setProperty("hibernate.cache.use_query_cache", environment.getProperty("spring.jpa.properties.hibernate.cache.use_query_cache"));
return properties;
| 80 | 276 | 247 | 523 |
375 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/MyCommonsMultipartResolver.java | MyCommonsMultipartResolver | isMultipart | class MyCommonsMultipartResolver extends CommonsMultipartResolver {
@Override
public boolean isMultipart(HttpServletRequest request) {<FILL_FUNCTION_BODY>}
} |
String uri = request.getRequestURI();
if(uri!=null && uri.contains("/config")){
return false;
}else{
return super.isMultipart(request);
}
| 68 | 46 | 54 | 100 |
376 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/ShiroConfig.java | ShiroConfig | shiroFilter | class ShiroConfig {
@Bean
public ShiroDbRealm myShiroRealm() {
ShiroDbRealm customRealm = new ShiroDbRealm();
return customRealm;
}
//权限管理,配置主要是Realm的管理认证 SecurityManager
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
@Bean
public FormAuthenticationWithLockFilter formAuthFilter() {
FormAuthenticationWithLockFilter formAuthFilter = new FormAuthenticationWithLockFilter();
formAuthFilter.setMaxLoginAttempts(100);
formAuthFilter.setSuccessAdminUrl("/design/my-survey/list.do");
formAuthFilter.setSuccessAdminRole("admin");
formAuthFilter.setRememberMeParam("rememberMe");
return formAuthFilter;
}
@Bean
public UserFilter userAuthFilter() {
MyUserFilter formAuthFilter = new MyUserFilter();
return formAuthFilter;
}
@Bean
public MyRolesAuthorizationFilter rolesAuthFilter() {
MyRolesAuthorizationFilter rolesAuthorizationFilter = new MyRolesAuthorizationFilter();
return rolesAuthorizationFilter;
}
@Bean
public AnonymousFilter anonymousFilter() {
AnonymousFilter anonymousFilter = new AnonymousFilter();
return anonymousFilter;
}
//Filter工厂,设置对应的过滤条件和跳转条件
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {<FILL_FUNCTION_BODY>}
@Bean
public SimpleCookie rememberMeCookie() {
SimpleCookie rememberMeCookie = new SimpleCookie("rememberMe");
rememberMeCookie.setHttpOnly(true);
rememberMeCookie.setMaxAge(2592000);
return rememberMeCookie;
}
@Bean
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
rememberMeManager.setCookie(rememberMeCookie());
return rememberMeManager;
}
} |
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> map = new LinkedHashMap<>();
//登出
map.put("/logout", "logout");
//对所有用户认证
map.put("/api/dwsurvey/anon/**", "anon");
map.put("/login", "authc");
map.put("/ic/**", "user");
map.put("/design/**", "user");
map.put("/da/**", "user");
map.put("/api/dwsurvey/app/**", "user");
map.put("/api/dwsurvey/admin/**", "roles["+ RoleCode.DWSURVEY_SUPER_ADMIN +"]");
//登录
// shiroFilterFactoryBean.setLoginUrl("/login.do");
//首页
shiroFilterFactoryBean.setSuccessUrl("/design/my-survey/list.do");
//错误页面,认证不通过跳转
// shiroFilterFactoryBean.setUnauthorizedUrl("/login.do?una=0");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
Map<String, Filter> filters = new HashMap<>();
filters.put("authc", formAuthFilter());
filters.put("user", userAuthFilter());
filters.put("roles", rolesAuthFilter());
// filters.put("anon", anonymousFilter());
shiroFilterFactoryBean.setFilters(filters);
return shiroFilterFactoryBean;
| 250 | 582 | 399 | 981 |
377 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/UrlRewriteConf.java | UrlRewriteConf | loadUrlRewriter | class UrlRewriteConf extends UrlRewriteFilter {
private static final String URL_REWRITE = "classpath:conf/urlrewrite.xml";
//注入urlrewrite配置文件
@Value(URL_REWRITE)
private Resource resource;
//重写配置文件加载方式
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {<FILL_FUNCTION_BODY>}
} |
try {
//将Resource对象转换成Conf对象
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "@@traceability@@");
checkConf(conf);
} catch (IOException ex) {
throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex);
}
| 102 | 113 | 96 | 209 |
378 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/config/WebConfigure.java | WebConfigure | delegatingFilterProxy | class WebConfigure implements WebMvcConfigurer {
/*
@Bean(name="sitemesh3")
SiteMeshFilter siteMeshFilter(){
return new SiteMeshFilter();
}
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login.do");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
*/
@Bean
public FilterRegistrationBean registerOpenEntityManagerInViewFilterBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns("*.do");
return registrationBean;
}
@Bean
public FilterRegistrationBean delegatingFilterProxy(){<FILL_FUNCTION_BODY>}
/*
@Bean
public FilterRegistrationBean filterRegistrationBean(@Qualifier("sitemesh3") SiteMeshFilter siteMeshFilter){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(siteMeshFilter);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("*.do");
return filterRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter();
filterRegistrationBean.setFilter(urlRewriteFilter);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//文件磁盘图片url 映射
//配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
//registry.addResourceHandler("/WEB-INF/**").addResourceLocations("file:/home/IdeaProjects/dwsurvey/src/main/webapp/WEB-INF");
// registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
} |
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
DelegatingFilterProxy proxy = new DelegatingFilterProxy();
proxy.setTargetFilterLifecycle(true);
proxy.setTargetBeanName("shiroFilter");
filterRegistrationBean.setFilter(proxy);
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
| 70 | 590 | 97 | 687 |
379 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/DwWebController.java | DwWebController | footerInfo | class DwWebController {
@Autowired
private AccountManager accountManager;
/**
* 获取问卷详情
* @return
*/
@RequestMapping(value = "/footer-info.do",method = RequestMethod.GET)
@ResponseBody
public HttpResult<SurveyDirectory> footerInfo() {<FILL_FUNCTION_BODY>}
} |
try{
FooterInfo footerInfo = new FooterInfo();
footerInfo.setVersionInfo(DWSurveyConfig.DWSURVEY_VERSION_INFO);
footerInfo.setVersionNumber(DWSurveyConfig.DWSURVEY_VERSION_NUMBER);
footerInfo.setVersionBuilt(DWSurveyConfig.DWSURVEY_VERSION_BUILT);
footerInfo.setSiteName(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_NAME);
footerInfo.setSiteUrl(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_URL);
footerInfo.setSiteIcp(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_ICP);
footerInfo.setSiteMail(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_MAIL);
footerInfo.setSitePhone(DWSurveyConfig.DWSURVEY_WEB_INFO_SITE_PHONE);
footerInfo.setYears("2012-"+new SimpleDateFormat("yyyy").format(new Date()));
User user = accountManager.getCurUser();
if(user!=null){
//登录用户返回带版本号
return HttpResult.SUCCESS(footerInfo);
}else{
//非登录用户返回不带版本号
footerInfo.setVersionNumber("");
return HttpResult.SUCCESS(footerInfo);
}
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
| 311 | 100 | 407 | 507 |
380 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/UEditorController.java | UEditorController | config | class UEditorController {
// 第二种方式
@Autowired // 注入到容器中
private Environment environment;
@Autowired
private AccountManager accountManager;
@RequestMapping(value="/config")
public void config(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
} |
response.setContentType("application/json");
String webFilePath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH;
String rootPath = webFilePath;
try {
User user = accountManager.getCurUser();
if(user!=null){
String exec = new ActionEnter(request, rootPath, user.getId()).exec();
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
| 204 | 92 | 150 | 242 |
383 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuFillblankController.java | QuFillblankController | ajaxBuildSaveOption | class QuFillblankController{
@Autowired
private QuestionManager questionManager;
@Autowired
private AnFillblankManager anFillblankManager;
@RequestMapping("/ajaxSave.do")
public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
Question entity=ajaxBuildSaveOption(request);
questionManager.save(entity);
String resultJson=buildResultJson(entity);
response.getWriter().write(resultJson);
}catch (Exception e) {
e.printStackTrace();
response.getWriter().write("error");
}
return null;
}
private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
public static String buildResultJson(Question entity){
StringBuffer strBuf=new StringBuffer();
strBuf.append("{id:'").append(entity.getId());
strBuf.append("',orderById:");
strBuf.append(entity.getOrderById());
strBuf.append(",quLogics:[");
List<QuestionLogic> questionLogics=entity.getQuestionLogics();
if(questionLogics!=null){
for (QuestionLogic questionLogic : questionLogics) {
strBuf.append("{id:'").append(questionLogic.getId());
strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},");
}
}
int strLen=strBuf.length();
if(strBuf.lastIndexOf(",")==(strLen-1)){
strBuf.replace(strLen-1, strLen, "");
}
strBuf.append("]}");
return strBuf.toString();
}
} |
String quId=request.getParameter("quId");
String belongId=request.getParameter("belongId");
String quTitle=request.getParameter("quTitle");
String orderById=request.getParameter("orderById");
String tag=request.getParameter("tag");
String isRequired=request.getParameter("isRequired");
String answerInputWidth=request.getParameter("answerInputWidth");
String answerInputRow=request.getParameter("answerInputRow");
String contactsAttr=request.getParameter("contactsAttr");
String contactsField=request.getParameter("contactsField");
String checkType=request.getParameter("checkType");
String hv=request.getParameter("hv");
String randOrder=request.getParameter("randOrder");
String cellCount=request.getParameter("cellCount");
String paramInt01=request.getParameter("paramInt01");
//System.out.println("paramInt01:"+paramInt01);
if("".equals(quId)){
quId=null;
}
Question entity=questionManager.getModel(quId);
entity.setBelongId(belongId);
if(quTitle!=null){
quTitle=URLDecoder.decode(quTitle,"utf-8");
entity.setQuTitle(quTitle);
}
entity.setOrderById(Integer.parseInt(orderById));
entity.setTag(Integer.parseInt(tag));
entity.setQuType(QuType.FILLBLANK);
isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired;
hv=(hv==null || "".equals(hv))?"0":hv;
randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder;
cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount;
contactsAttr=(contactsAttr==null || "".equals(contactsAttr))?"0":contactsAttr;
entity.setContactsAttr(Integer.parseInt(contactsAttr));
entity.setContactsField(contactsField);
answerInputWidth=(answerInputWidth==null || "".equals(answerInputWidth))?"300":answerInputWidth;
answerInputRow=(answerInputRow==null || "".equals(answerInputRow))?"1":answerInputRow;
paramInt01=(StringUtils.isEmpty(paramInt01))?"0":paramInt01;
entity.setAnswerInputWidth(Integer.parseInt(answerInputWidth));
entity.setAnswerInputRow(Integer.parseInt(answerInputRow));
entity.setIsRequired(Integer.parseInt(isRequired));
entity.setHv(Integer.parseInt(hv));
entity.setRandOrder(Integer.parseInt(randOrder));
entity.setCellCount(Integer.parseInt(cellCount));
checkType=(checkType==null || "".equals(checkType))?"NO":checkType;
entity.setCheckType(CheckType.valueOf(checkType));
entity.setParamInt01(Integer.parseInt(paramInt01));
Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_");
List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>();
for (String key : quLogicIdMap.keySet()) {
String cgQuItemId=request.getParameter("cgQuItemId_"+key);
String skQuId=request.getParameter("skQuId_"+key);
String visibility=request.getParameter("visibility_"+key);
String logicType=request.getParameter("logicType_"+key);
Object quLogicId=quLogicIdMap.get(key);
String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null;
QuestionLogic quLogic=new QuestionLogic();
quLogic.setId(quLogicIdValue);
quLogic.setCgQuItemId(cgQuItemId);
quLogic.setSkQuId(skQuId);
quLogic.setVisibility(Integer.parseInt(visibility));
quLogic.setTitle(key);
quLogic.setLogicType(logicType);
quLogics.add(quLogic);
}
entity.setQuestionLogics(quLogics);
return entity;
| 52 | 494 | 1,217 | 1,711 |
385 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuOrderquController.java | QuOrderquController | ajaxBuildSaveOption | class QuOrderquController{
@Autowired
private QuestionManager questionManager;
@Autowired
private QuOrderbyManager quOrderbyManager;
@RequestMapping("/ajaxSave.do")
public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
Question entity=ajaxBuildSaveOption(request);
questionManager.save(entity);
String resultJson=buildResultJson(entity);
response.getWriter().write(resultJson);
}catch (Exception e) {
e.printStackTrace();
response.getWriter().write("error");
}
return null;
}
private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
public static String buildResultJson(Question entity){
StringBuffer strBuf=new StringBuffer();
strBuf.append("{id:'").append(entity.getId());
strBuf.append("',orderById:");
strBuf.append(entity.getOrderById());
strBuf.append(",quItems:[");
List<QuOrderby> quOrderbys=entity.getQuOrderbys();
for (QuOrderby quOrderby : quOrderbys) {
strBuf.append("{id:'").append(quOrderby.getId());
strBuf.append("',title:'").append(quOrderby.getOrderById()).append("'},");
}
int strLen=strBuf.length();
if(strBuf.lastIndexOf(",")==(strLen-1)){
strBuf.replace(strLen-1, strLen, "");
}
strBuf.append("]");
strBuf.append(",quLogics:[");
List<QuestionLogic> questionLogics=entity.getQuestionLogics();
if(questionLogics!=null){
for (QuestionLogic questionLogic : questionLogics) {
strBuf.append("{id:'").append(questionLogic.getId());
strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},");
}
}
strLen=strBuf.length();
if(strBuf.lastIndexOf(",")==(strLen-1)){
strBuf.replace(strLen-1, strLen, "");
}
strBuf.append("]}");
return strBuf.toString();
}
/**
* 删除选项
* @return
* @throws Exception
*/
@RequestMapping("/ajaxDelete.do")
public String ajaxDelete(HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
String quItemId=request.getParameter("quItemId");
quOrderbyManager.ajaxDelete(quItemId);
response.getWriter().write("true");
}catch(Exception e){
e.printStackTrace();
response.getWriter().write("error");
}
return null;
}
} |
String quId=request.getParameter("quId");
String belongId=request.getParameter("belongId");
String quTitle=request.getParameter("quTitle");
String orderById=request.getParameter("orderById");
String tag=request.getParameter("tag");
//isRequired 是否必选
String isRequired=request.getParameter("isRequired");
//hv 1水平显示 2垂直显示
String hv=request.getParameter("hv");
//randOrder 选项随机排列
String randOrder=request.getParameter("randOrder");
String cellCount=request.getParameter("cellCount");
if("".equals(quId)){
quId=null;
}
Question entity=questionManager.getModel(quId);
entity.setBelongId(belongId);
if(quTitle!=null){
quTitle=URLDecoder.decode(quTitle,"utf-8");
entity.setQuTitle(quTitle);
}
entity.setOrderById(Integer.parseInt(orderById));
entity.setTag(Integer.parseInt(tag));
entity.setQuType(QuType.ORDERQU);
isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired;
hv=(hv==null || "".equals(hv))?"0":hv;
randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder;
cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount;
entity.setIsRequired(Integer.parseInt(isRequired));
entity.setHv(Integer.parseInt(hv));
entity.setRandOrder(Integer.parseInt(randOrder));
entity.setCellCount(Integer.parseInt(cellCount));
Map<String, Object> optionNameMap=WebUtils.getParametersStartingWith(request, "optionValue_");
List<QuOrderby> quOrderbys=new ArrayList<QuOrderby>();
for (String key : optionNameMap.keySet()) {
String optionId=request.getParameter("optionId_"+key);
Object optionName=optionNameMap.get(key);
String optionNameValue=(optionName!=null)?optionName.toString():"";
QuOrderby quOrderby=new QuOrderby();
if("".equals(optionId)){
optionId=null;
}
quOrderby.setId(optionId);
// quRadio.setOptionTitle(key);
optionNameValue=URLDecoder.decode(optionNameValue,"utf-8");
quOrderby.setOptionName(optionNameValue);
quOrderby.setOrderById(Integer.parseInt(key));
quOrderbys.add(quOrderby);
}
entity.setQuOrderbys(quOrderbys);
//逻辑选项设置
Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_");
List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>();
for (String key : quLogicIdMap.keySet()) {
String cgQuItemId=request.getParameter("cgQuItemId_"+key);
String skQuId=request.getParameter("skQuId_"+key);
String visibility=request.getParameter("visibility_"+key);
String logicType=request.getParameter("logicType_"+key);
Object quLogicId=quLogicIdMap.get(key);
String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null;
QuestionLogic quLogic=new QuestionLogic();
quLogic.setId(quLogicIdValue);
quLogic.setCgQuItemId(cgQuItemId);
quLogic.setSkQuId(skQuId);
quLogic.setVisibility(Integer.parseInt(visibility));
quLogic.setTitle(key);
quLogic.setLogicType(logicType);
quLogics.add(quLogic);
}
entity.setQuestionLogics(quLogics);
return entity;
| 57 | 826 | 1,168 | 1,994 |
386 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuPagetagController.java | QuPagetagController | ajaxBuildSaveOption | class QuPagetagController{
@Autowired
private QuestionManager questionManager;
@RequestMapping("/ajaxSave.do")
public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
Question entity=ajaxBuildSaveOption(request);
questionManager.save(entity);
String resultJson=buildResultJson(entity);
response.getWriter().write(resultJson);
}catch (Exception e) {
e.printStackTrace();
response.getWriter().write("error");
}
return null;
}
private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
public static String buildResultJson(Question entity){
StringBuffer strBuf=new StringBuffer();
strBuf.append("{id:'").append(entity.getId());
strBuf.append("',orderById:");
strBuf.append(entity.getOrderById());
strBuf.append(",quLogics:[");
List<QuestionLogic> questionLogics=entity.getQuestionLogics();
if(questionLogics!=null){
for (QuestionLogic questionLogic : questionLogics) {
strBuf.append("{id:'").append(questionLogic.getId());
strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},");
}
}
int strLen=strBuf.length();
if(strBuf.lastIndexOf(",")==(strLen-1)){
strBuf.replace(strLen-1, strLen, "");
}
strBuf.append("]}");
return strBuf.toString();
}
} |
String quId=request.getParameter("quId");
String belongId=request.getParameter("belongId");
String quTitle=request.getParameter("quTitle");
String orderById=request.getParameter("orderById");
String tag=request.getParameter("tag");
//isRequired 是否必选
String isRequired=request.getParameter("isRequired");
//hv 1水平显示 2垂直显示
String hv=request.getParameter("hv");
//randOrder 选项随机排列
String randOrder=request.getParameter("randOrder");
String cellCount=request.getParameter("cellCount");
if("".equals(quId)){
quId=null;
}
Question entity=questionManager.getModel(quId);
entity.setBelongId(belongId);
if(quTitle!=null){
quTitle=URLDecoder.decode(quTitle,"utf-8");
entity.setQuTitle(quTitle);
}
entity.setOrderById(Integer.parseInt(orderById));
entity.setTag(Integer.parseInt(tag));
entity.setQuType(QuType.PAGETAG);
isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired;
hv=(hv==null || "".equals(hv))?"0":hv;
randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder;
cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount;
entity.setIsRequired(Integer.parseInt(isRequired));
entity.setHv(Integer.parseInt(hv));
entity.setRandOrder(Integer.parseInt(randOrder));
entity.setCellCount(Integer.parseInt(cellCount));
Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_");
List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>();
for (String key : quLogicIdMap.keySet()) {
String cgQuItemId=request.getParameter("cgQuItemId_"+key);
String skQuId=request.getParameter("skQuId_"+key);
String visibility=request.getParameter("visibility_"+key);
String logicType=request.getParameter("logicType_"+key);
Object quLogicId=quLogicIdMap.get(key);
String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null;
QuestionLogic quLogic=new QuestionLogic();
quLogic.setId(quLogicIdValue);
quLogic.setCgQuItemId(cgQuItemId);
quLogic.setSkQuId(skQuId);
quLogic.setVisibility(Integer.parseInt(visibility));
quLogic.setTitle(key);
quLogic.setLogicType(logicType);
quLogics.add(quLogic);
}
entity.setQuestionLogics(quLogics);
return entity;
| 42 | 474 | 879 | 1,353 |
387 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuParagraphController.java | QuParagraphController | ajaxBuildSaveOption | class QuParagraphController{
@Autowired
private QuestionManager questionManager;
@RequestMapping("/ajaxSave.do")
public String ajaxSave(HttpServletRequest request,HttpServletResponse response) throws Exception {
try{
Question entity=ajaxBuildSaveOption(request);
questionManager.save(entity);
String resultJson=buildResultJson(entity);
response.getWriter().write(resultJson);
}catch (Exception e) {
e.printStackTrace();
response.getWriter().write("error");
}
return null;
}
private Question ajaxBuildSaveOption(HttpServletRequest request) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
public static String buildResultJson(Question entity){
StringBuffer strBuf=new StringBuffer();
strBuf.append("{id:'").append(entity.getId());
strBuf.append("',orderById:");
strBuf.append(entity.getOrderById());
strBuf.append(",quLogics:[");
List<QuestionLogic> questionLogics=entity.getQuestionLogics();
if(questionLogics!=null){
for (QuestionLogic questionLogic : questionLogics) {
strBuf.append("{id:'").append(questionLogic.getId());
strBuf.append("',title:'").append(questionLogic.getTitle()).append("'},");
}
}
int strLen=strBuf.length();
if(strBuf.lastIndexOf(",")==(strLen-1)){
strBuf.replace(strLen-1, strLen, "");
}
strBuf.append("]}");
return strBuf.toString();
}
} |
String quId=request.getParameter("quId");
String belongId=request.getParameter("belongId");
String quTitle=request.getParameter("quTitle");
String orderById=request.getParameter("orderById");
String tag=request.getParameter("tag");
String isRequired=request.getParameter("isRequired");
//hv 1水平显示 2垂直显示
String hv=request.getParameter("hv");
//randOrder 选项随机排列
String randOrder=request.getParameter("randOrder");
String cellCount=request.getParameter("cellCount");
if("".equals(quId)){
quId=null;
}
Question entity=questionManager.getModel(quId);
entity.setBelongId(belongId);
if(quTitle!=null){
quTitle=URLDecoder.decode(quTitle,"utf-8");
entity.setQuTitle(quTitle);
}
entity.setOrderById(Integer.parseInt(orderById));
entity.setTag(Integer.parseInt(tag));
entity.setQuType(QuType.PARAGRAPH);
isRequired=(isRequired==null || "".equals(isRequired))?"0":isRequired;
hv=(hv==null || "".equals(hv))?"0":hv;
randOrder=(randOrder==null || "".equals(randOrder))?"0":randOrder;
cellCount=(cellCount==null || "".equals(cellCount))?"0":cellCount;
entity.setIsRequired(Integer.parseInt(isRequired));
entity.setHv(Integer.parseInt(hv));
entity.setRandOrder(Integer.parseInt(randOrder));
entity.setCellCount(Integer.parseInt(cellCount));
Map<String, Object> quLogicIdMap=WebUtils.getParametersStartingWith(request, "quLogicId_");
List<QuestionLogic> quLogics=new ArrayList<QuestionLogic>();
for (String key : quLogicIdMap.keySet()) {
String cgQuItemId=request.getParameter("cgQuItemId_"+key);
String skQuId=request.getParameter("skQuId_"+key);
String visibility=request.getParameter("visibility_"+key);
String logicType=request.getParameter("logicType_"+key);
Object quLogicId=quLogicIdMap.get(key);
String quLogicIdValue=(quLogicId!=null)?quLogicId.toString():null;
QuestionLogic quLogic=new QuestionLogic();
quLogic.setId(quLogicIdValue);
quLogic.setCgQuItemId(cgQuItemId);
quLogic.setSkQuId(skQuId);
quLogic.setVisibility(Integer.parseInt(visibility));
quLogic.setTitle(key);
quLogic.setLogicType(logicType);
quLogics.add(quLogic);
}
entity.setQuestionLogics(quLogics);
return entity;
| 41 | 472 | 864 | 1,336 |
391 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/QuestionController.java | QuestionController | ajaxDelete | class QuestionController{
@Autowired
private QuestionManager questionManager;
/**
* ajax删除
* @return
* @throws Exception
*/
@RequestMapping("/ajaxDelete.do")
public String ajaxDelete(HttpServletRequest request,HttpServletResponse response) throws Exception {<FILL_FUNCTION_BODY>}
} |
String responseStr="";
try{
String delQuId=request.getParameter("quId");
questionManager.delete(delQuId);
responseStr="true";
}catch (Exception e) {
responseStr="false";
}
response.getWriter().write(responseStr);
return null;
| 7 | 96 | 102 | 198 |
393 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/question/SurveyDesignController.java | SurveyDesignController | ajaxSave | class SurveyDesignController {
@Autowired
private QuestionManager questionManager;
@Autowired
private SurveyDirectoryManager surveyDirectoryManager;
@Autowired
private AccountManager accountManager;
@Autowired
private SurveyStyleManager surveyStyleManager;
@RequestMapping("/surveyAll.do")
@ResponseBody
public HttpResult surveyAll(String surveyId,String sid) {
try{
return buildSurvey(surveyId,sid);
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
@RequestMapping("/devSurvey.do")
@ResponseBody
public HttpResult devSurvey(HttpServletRequest request,String surveyId) throws Exception {
User curUser = accountManager.getCurUser();
if(curUser!=null){
SurveyDirectory survey=surveyDirectoryManager.get(surveyId);
try{
surveyDirectoryManager.devSurvey(survey);
// sysLogManager.saveNew("发布问卷",survey.getId(),"DEV-SURVEY",curUser.getId(),1);
return HttpResult.SUCCESS();
}catch (Exception e) {
e.printStackTrace();
}
}else{
HttpResult.NOLOGIN();
}
return HttpResult.FAILURE();
}
@RequestMapping("/ajaxSave.do")
public String ajaxSave(HttpServletRequest request,HttpServletResponse response,String surveyId) throws Exception {<FILL_FUNCTION_BODY>}
private HttpResult buildSurvey(String surveyId,String sid) {
//判断是否拥有权限
SurveyDirectory surveyDirectory = null;
if(StringUtils.isEmpty(surveyId) && StringUtils.isNotEmpty(sid)){
surveyDirectory = surveyDirectoryManager.getSurveyBySid(sid);
}else{
surveyDirectory=surveyDirectoryManager.getSurvey(surveyId);
}
User user= accountManager.getCurUser();
String userId=user.getId();
if(user!=null){
if(!userId.equals(surveyDirectory.getUserId())){
return HttpResult.FAILURE_MSG("未登录或没有相应数据权限");
}
}else{
return HttpResult.FAILURE_MSG("未登录或没有相应数据权限");
}
if(surveyDirectory!=null){
List<Question> questions=questionManager.findDetails(surveyDirectory.getId(), "2");
surveyDirectory.setQuestions(questions);
surveyDirectory.setSurveyQuNum(questions.size());
surveyDirectoryManager.save(surveyDirectory);
return HttpResult.SUCCESS(surveyDirectory);
}else{
return HttpResult.NOLOGIN();
}
}
} |
String svyName=request.getParameter("svyName");
String svyNameText=request.getParameter("svyNameText");
String svyNote=request.getParameter("svyNote");
//属性
String effective=request.getParameter("effective");
String effectiveIp=request.getParameter("effectiveIp");
String rule=request.getParameter("rule");
String ruleCode=request.getParameter("ruleCode");
String refresh=request.getParameter("refresh");
String mailOnly=request.getParameter("mailOnly");
String ynEndNum=request.getParameter("ynEndNum");
String endNum=request.getParameter("endNum");
String ynEndTime=request.getParameter("ynEndTime");
String endTime=request.getParameter("endTime");
String showShareSurvey=request.getParameter("showShareSurvey");
String showAnswerDa=request.getParameter("showAnswerDa");
SurveyDirectory survey=surveyDirectoryManager.getSurvey(surveyId);
SurveyDetail surveyDetail=survey.getSurveyDetail();
User user= accountManager.getCurUser();
if(user!=null && survey!=null){
String userId=user.getId();
if(userId.equals(survey.getUserId())){
if( svyNote!=null){
svyNote=URLDecoder.decode(svyNote,"utf-8");
surveyDetail.setSurveyNote(svyNote);
}
if(svyName!=null && !"".equals(svyName)){
svyName=URLDecoder.decode(svyName,"utf-8");
survey.setSurveyName(svyName);
}
if(StringUtils.isNotEmpty(svyNameText)){
svyNameText=URLDecoder.decode(svyNameText,"utf-8");
survey.setSurveyNameText(svyNameText);
}
//保存属性
if(effective!=null && !"".equals(effective)){
surveyDetail.setEffective(Integer.parseInt(effective));
}
if(effectiveIp!=null && !"".equals(effectiveIp)){
surveyDetail.setEffectiveIp(Integer.parseInt(effectiveIp));
}
if(rule!=null && !"".equals(rule)){
surveyDetail.setRule(Integer.parseInt(rule));
surveyDetail.setRuleCode(ruleCode);
}
if(refresh!=null && !"".equals(refresh)){
surveyDetail.setRefresh(Integer.parseInt(refresh));
}
if(mailOnly!=null && !"".equals(mailOnly)){
surveyDetail.setMailOnly(Integer.parseInt(mailOnly));
}
if(ynEndNum!=null && !"".equals(ynEndNum)){
surveyDetail.setYnEndNum(Integer.parseInt(ynEndNum));
//surveyDetail.setEndNum(Integer.parseInt(endNum));
if(endNum!=null && endNum.matches("\\d*")){
surveyDetail.setEndNum(Integer.parseInt(endNum));
}
}
if(ynEndTime!=null && !"".equals(ynEndTime)){
surveyDetail.setYnEndTime(Integer.parseInt(ynEndTime));
if(org.apache.commons.lang3.StringUtils.isNotEmpty(endTime)){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
surveyDetail.setEndTime(simpleDateFormat.parse(endTime));
}
}
if(showShareSurvey!=null && !"".equals(showShareSurvey)){
surveyDetail.setShowShareSurvey(Integer.parseInt(showShareSurvey));
survey.setIsShare(Integer.parseInt(showShareSurvey));
}
if(showAnswerDa!=null && !"".equals(showAnswerDa)){
surveyDetail.setShowAnswerDa(Integer.parseInt(showAnswerDa));
survey.setViewAnswer(Integer.parseInt(showAnswerDa));
}
surveyDirectoryManager.save(survey);
response.getWriter().write("true");
}
}
return null;
| 52 | 796 | 1,207 | 2,003 |
394 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/survey/MySurveyAnswerController.java | MySurveyAnswerController | exportXLS | class MySurveyAnswerController {
@Autowired
private SurveyDirectoryManager surveyDirectoryManager;
@Autowired
private SurveyAnswerManager surveyAnswerManager;
@Autowired
private AccountManager accountManager;
@Autowired
private AnUploadFileManager anUploadFileManager;
/**
* 获取答卷列表
* @return
*/
@RequestMapping(value = "/list.do",method = RequestMethod.GET)
@ResponseBody
public PageResult survey(HttpServletRequest request,PageResult<SurveyAnswer> pageResult, String surveyId,String ipAddr,String city,Integer isEffective) {
UserAgentUtils.userAgent(request);
User user = accountManager.getCurUser();
if(user!=null){
Page page = ResultUtils.getPageByPageResult(pageResult);
SurveyDirectory survey=surveyDirectoryManager.get(surveyId);
if(survey!=null){
if(!user.getId().equals(survey.getUserId())){
pageResult.setSuccess(false);
return pageResult;
}
page=surveyAnswerManager.answerPage(page, surveyId);
}
pageResult = ResultUtils.getPageResultByPage(page,pageResult);
}
return pageResult;
}
@RequestMapping(value = "/info.do",method = RequestMethod.GET)
@ResponseBody
public HttpResult info(String answerId) throws Exception {
try {
SurveyAnswer answer = null;
if (StringUtils.isNotEmpty(answerId)) {
answer = surveyAnswerManager.findById(answerId);
}
if(answer!=null){
SurveyDirectory survey = surveyDirectoryManager.findUniqueBy(answer.getSurveyId());
User user= accountManager.getCurUser();
if(user!=null && survey!=null) {
if(!user.getId().equals(survey.getUserId())) {
return HttpResult.FAILURE_MSG("没有相应数据权限");
}
List<Question> questions = surveyAnswerManager.findAnswerDetail(answer);
survey.setQuestions(questions);
survey.setSurveyAnswer(answer);
return HttpResult.SUCCESS(survey);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return HttpResult.FAILURE();
}
/**
* @return
* @throws Exception
*/
@RequestMapping(value = "/delete.do",method = RequestMethod.DELETE)
@ResponseBody
public HttpResult delete(@RequestBody Map<String, String[]> map) throws Exception {
// HttpResult httpResultRP = ShiroAuthorizationUtils.isDefaultAdminRoleAndPermissionHttpResult(PermissionCode.HT_CASCADEDB_DELETE);
// if (httpResultRP != null) return httpResultRP;
try{
if(map!=null){
if(map.containsKey("id")){
String[] ids = map.get("id");
if(ids!=null){
surveyAnswerManager.deleteData(ids);
}
}
}
return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
@RequestMapping("/export-xls.do")
@ResponseBody
public String exportXLS(HttpServletRequest request, HttpServletResponse response, String surveyId,String expUpQu) throws Exception{<FILL_FUNCTION_BODY>}
} |
try{
String savePath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH;
User user=accountManager.getCurUser();
if(user!=null){
SurveyDirectory survey = surveyDirectoryManager.get(surveyId);
if(survey!=null){
if(!user.getId().equals(survey.getUserId())){
return "没有相应数据权限";
}
List<AnUplodFile> anUplodFiles = anUploadFileManager.findAnswer(surveyId);
if(anUplodFiles!=null && anUplodFiles.size()>0 && expUpQu!=null && "1".equals(expUpQu)){
//直接导出excel,不存在上传文件的问题
savePath = surveyAnswerManager.exportXLS(surveyId,savePath,true);
//启用压缩导出
String fromPath =DWSurveyConfig.DWSURVEY_WEB_FILE_PATH+"/webin/expfile/"+surveyId;
fromPath = fromPath.replace("/", File.separator);
String zipPath = DWSurveyConfig.DWSURVEY_WEB_FILE_PATH+"/webin/zip/".replace("/", File.separator);
File file = new File(zipPath);
if (!file.exists())
file.mkdirs();
String toPath = zipPath+surveyId + ".zip";
toPath = toPath.replace("/",File.separator);
ZipUtil.createZip(fromPath, toPath, false);
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("dwsurvey_"+survey.getSid()+".zip", "UTF-8"));
request.getRequestDispatcher("/webin/zip/"+ surveyId + ".zip").forward(request,response);
}else{
//直接导出excel,不存在上传文件的问题
savePath=surveyAnswerManager.exportXLS(surveyId,savePath, false);
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("dwsurvey_"+survey.getSid()+".xlsx", "UTF-8"));
request.getRequestDispatcher(savePath).forward(request,response);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
| 785 | 907 | 628 | 1,535 |
395 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/survey/MySurveyController.java | MySurveyController | delete | class MySurveyController {
@Autowired
private AccountManager accountManager;
@Autowired
private SurveyDirectoryManager surveyDirectoryManager;
@Autowired
private SurveyDetailManager surveyDetailManager;
@Autowired
private SurveyAnswerManager surveyAnswerManager;
@Autowired
private SurveyStatsManager surveyStatsManager;
/**
* 拉取问卷列表
* @param pageResult
* @return
*/
@RequestMapping(value = "/list.do",method = RequestMethod.GET)
@ResponseBody
public PageResult<SurveyDirectory> list(PageResult<SurveyDirectory> pageResult, String surveyName, Integer surveyState) {
User user = accountManager.getCurUser();
if(user!=null){
Page page = ResultUtils.getPageByPageResult(pageResult);
page = surveyDirectoryManager.findByUser(page,surveyName, surveyState);
page.setResult(surveyAnswerManager.upAnQuNum(page.getResult()));
pageResult = ResultUtils.getPageResultByPage(page,pageResult);
}
return pageResult;
}
/**
* 获取问卷详情
* @param id
* @return
*/
@RequestMapping(value = "/info.do",method = RequestMethod.GET)
@ResponseBody
public HttpResult<SurveyDirectory> info(String id) {
try{
User user = accountManager.getCurUser();
if(user!=null){
surveyStatsManager.findBySurvey(id);
SurveyDirectory survey = surveyDirectoryManager.findUniqueBy(id);
survey = surveyAnswerManager.upAnQuNum(survey);
return HttpResult.SUCCESS(survey);
}else{
return HttpResult.buildResult(HttpStatus.NOLOGIN);
}
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
/**
* 创建新问卷
* @param surveyDirectory
* @return
*/
@RequestMapping(value = "/add.do",method = RequestMethod.POST)
@ResponseBody
// @RequiresRoles(value = "PROJECT_ADMIN,DEPT_ADMIN,ENT_ADMIN,SUPER_ADMIN,QT_SURVEY_LIST")
public HttpResult add(@RequestBody SurveyDirectory surveyDirectory) {
try{
surveyDirectory.setDirType(2);
surveyDirectory.setSurveyNameText(surveyDirectory.getSurveyName());
surveyDirectoryManager.save(surveyDirectory);
return HttpResult.SUCCESS(surveyDirectory);
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
//引用问卷
@RequestMapping(value = "/copy.do",method = RequestMethod.POST)
@ResponseBody
public HttpResult copy(String fromSurveyId, String surveyName, String tag) throws Exception {
tag="2";
SurveyDirectory directory=surveyDirectoryManager.createBySurvey(fromSurveyId,surveyName,tag);
String surveyId=directory.getId();
return HttpResult.SUCCESS(directory);
}
/**
* 问卷删除
* @param map
* @return
* @throws Exception
*/
@RequestMapping(value = "/delete.do",method = RequestMethod.DELETE)
@ResponseBody
public HttpResult delete(@RequestBody Map<String, String[]> map) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 修改状态
* @return
*/
@RequestMapping(value = "/up-survey-status.do",method = RequestMethod.POST)
@ResponseBody
public HttpResult<SurveyDirectory> upSurveyState(String surveyId, Integer surveyState) {
try{
surveyDirectoryManager.upSurveyState(surveyId,surveyState);
return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
/**
* 保存更新基本属性
* @param surveyDetail
* @return
*/
@RequestMapping(value = "/survey-base-attr.do",method = RequestMethod.PUT)
@ResponseBody
public HttpResult<SurveyDirectory> saveBaseAttr(@RequestBody SurveyDetail surveyDetail) {
try{
surveyDetailManager.saveBaseUp(surveyDetail);
return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
} |
String result = null;
try{
User curUser = accountManager.getCurUser();
if(curUser!=null){
if(map!=null){
if(map.containsKey("id")){
String[] ids = map.get("id");
if(ids!=null){
surveyDirectoryManager.delete(ids);
return HttpResult.SUCCESS();
}
}
}
}
}catch (Exception e) {
result=e.getMessage();
}
return HttpResult.FAILURE(result);
| 307 | 1,195 | 144 | 1,339 |
396 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/survey/MySurveyStatsController.java | MySurveyStatsController | report | class MySurveyStatsController {
@Autowired
private SurveyStatsManager surveyStatsManager;
@Autowired
private SurveyAnswerManager surveyAnswerManager;
@Autowired
private AccountManager accountManager;
@Autowired
private SurveyDirectoryManager surveyDirectoryManager;
@RequestMapping("/report.do")
@ResponseBody
public HttpResult report(String surveyId) {<FILL_FUNCTION_BODY>}
} |
// 得到频数分析数据
User user = accountManager.getCurUser();
if(user!=null){
SurveyDirectory survey = surveyDirectoryManager.findUniqueBy(surveyId);
if(survey!=null){
if(!user.getId().equals(survey.getUserId())){
return HttpResult.FAILURE_MSG("没有相应数据权限");
}
List<Question> questions = surveyStatsManager.findFrequency(survey);
SurveyStats surveyStats = new SurveyStats();
surveyStats.setQuestions(questions);
return HttpResult.SUCCESS(surveyStats);
}
}
return HttpResult.FAILURE();
| 214 | 118 | 174 | 292 |
397 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/user/UserAdminController.java | UserAdminController | delete | class UserAdminController {
@Autowired
private UserManager userManager;
@Autowired
private FormAuthenticationWithLockFilter formAuthFilter;
@RequestMapping(value = "/list.do",method = RequestMethod.GET)
@ResponseBody
public PageResult<User> list(PageResult<User> pageResult,Integer status, String loginName, String name, String email,String cellphone) {
Page page = ResultUtils.getPageByPageResult(pageResult);
page = userManager.findPage(page, status, loginName, name, email, cellphone);
pageResult = ResultUtils.getPageResultByPage(page,pageResult);
return pageResult;
}
/**
* 添加
* @param user
* @return
*/
@RequestMapping(value = "/add.do",method = RequestMethod.POST)
@ResponseBody
public HttpResult add(@RequestBody User user) {
try{
if("demo".equals(DWSurveyConfig.DWSURVEY_SITE)) return HttpResult.FAILURE("DEMO环境不允许操作");
User result = userManager.adminSave(user);
if(result!=null) return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
}
/**
* 修改
* @param user
* @return
*/
@RequestMapping(value = "/edit.do",method = RequestMethod.PUT)
@ResponseBody
public HttpResult up(@RequestBody User user) {
try{
if("demo".equals(DWSurveyConfig.DWSURVEY_SITE)) return HttpResult.FAILURE("DEMO环境不允许操作");
HttpResult httpResult = userManager.upData(user);
return httpResult;
}catch (Exception e){
e.printStackTrace();
return HttpResult.FAILURE(e.getMessage());
}
}
/**
* 修改分组
* @return
*/
@RequestMapping(value = "/delete.do",method = RequestMethod.DELETE)
@ResponseBody
public HttpResult delete(@RequestBody Map<String, String[]> map) {<FILL_FUNCTION_BODY>}
/**
* 修改
* @param user
* @return
*/
@RequestMapping(value = "/reset-login.do",method = RequestMethod.PUT)
@ResponseBody
public HttpResult resetLogin(@RequestBody User user) {
try{
formAuthFilter.resetAccountLock(user.getLoginName());
return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
return HttpResult.FAILURE(e.getMessage());
}
}
} |
try{
if("demo".equals(DWSurveyConfig.DWSURVEY_SITE)) return HttpResult.FAILURE("DEMO环境不允许操作");
if(map!=null){
if(map.containsKey("id")){
String[] ids = map.get("id");
if(ids!=null){
userManager.deleteData(ids);
}
}
}
return HttpResult.SUCCESS();
}catch (Exception e){
e.printStackTrace();
}
return HttpResult.FAILURE();
| 222 | 708 | 146 | 854 |
398 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/controller/user/UserController.java | UserController | save | class UserController {
@Autowired
private AccountManager accountManager;
@RequestMapping("/currentUser.do")
@ResponseBody
public HttpResult currentUser() throws Exception {
User user=accountManager.getCurUser();
return HttpResult.SUCCESS(user);
}
@RequestMapping("/up-info.do")
@ResponseBody
public HttpResult save(HttpServletRequest request,String name,String avatar) throws Exception {<FILL_FUNCTION_BODY>}
@RequestMapping("/up-pwd.do")
@ResponseBody
public HttpResult updatePwd(String curpwd,String pwd) throws Exception {
System.out.println("curpwd:"+curpwd);
boolean isOk = accountManager.updatePwd(curpwd,pwd);
if(isOk){
return HttpResult.SUCCESS();
}
return HttpResult.FAILURE();
}
} |
User user=accountManager.getCurUser();
// user.setEmail(email);
// user.setCellphone(cellphone);
user.setName(name);
user.setAvatar(avatar);
accountManager.saveUp(user);
return HttpResult.SUCCESS();
| 47 | 241 | 79 | 320 |
399 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnAnswerDaoImpl.java | AnAnswerDaoImpl | findGroupStats | class AnAnswerDaoImpl extends BaseDaoImpl<AnAnswer, String> implements AnAnswerDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select count(case when answer='' then answer end) emptyCount, count(case when answer!='' then answer end) blankCount from t_an_answer where visibility=1 and qu_id=?";
Object[] objs=(Object[]) this.getSession().createSQLQuery(sql).setParameter(1, question.getId()).uniqueResult();
question.setRowContent(objs[0].toString());//未回答数
question.setOptionContent(objs[1].toString());//回答的项数
question.setAnCount(Integer.parseInt(objs[1].toString()));
| 25 | 62 | 162 | 224 |
401 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnDFillblankDaoImpl.java | AnDFillblankDaoImpl | findGroupStats | class AnDFillblankDaoImpl extends BaseDaoImpl<AnDFillblank, String> implements AnDFillblankDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select qu_item_id,count(*) from t_an_dfillblank where visibility=1 and qu_id=? group by qu_item_id";
List<Object[]> list=this.getSession().createSQLQuery(sql).setParameter(1,question.getId()).list();
List<QuMultiFillblank> quMultiFillblanks=question.getQuMultiFillblanks();
for (QuMultiFillblank quMultiFillblank : quMultiFillblanks) {
String quMultiFillblankId=quMultiFillblank.getId();
for (Object[] objects : list) {
if(quMultiFillblankId.equals(objects[0].toString())){
quMultiFillblank.setAnCount(Integer.parseInt(objects[1].toString()));
continue;
}
}
}
| 27 | 65 | 224 | 289 |
402 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnEnumquDaoImpl.java | AnEnumquDaoImpl | findGroupStats | class AnEnumquDaoImpl extends BaseDaoImpl<AnEnumqu, String> implements AnEnumquDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select answer,count(answer) from t_an_enumqu where visibility=1 and qu_id=? GROUP BY answer";
List<Object[]> list=this.getSession().createSQLQuery(sql).setParameter(1,question.getId()).list();
//一共有多少对枚举数
if(list!=null && list.size()>0){
question.setAnCount(list.size());
}
| 17 | 62 | 123 | 185 |
403 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnFillblankDaoImpl.java | AnFillblankDaoImpl | findGroupStats | class AnFillblankDaoImpl extends BaseDaoImpl<AnFillblank, String> implements AnFillblankDao{
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select count(case when answer='' then answer end) emptyCount, count(case when answer!='' then answer end) blankCount from t_an_fillblank where visibility=1 and qu_id=?";
Object[] objs=(Object[]) this.getSession().createSQLQuery(sql).setParameter(1, question.getId()).uniqueResult();
question.setRowContent(objs[0].toString());//未回答数
question.setOptionContent(objs[1].toString());//回答的项数
question.setAnCount(Integer.parseInt(objs[1].toString()));
| 27 | 62 | 163 | 225 |
404 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnOrderDaoImpl.java | AnOrderDaoImpl | findGroupStats | class AnOrderDaoImpl extends BaseDaoImpl<AnOrder, String> implements AnOrderDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select qu_row_id,sum(ordery_num) sumOrderNum from t_an_order where visibility=1 and qu_id=? group by qu_row_id order by sumOrderNum";
List<Object[]> list=this.getSession().createSQLQuery(sql).setParameter(1,question.getId()).list();
List<QuOrderby> quOrderbies=question.getQuOrderbys();
/*
int count=0;
for (QuOrderby quOrderby : quOrderbies) {
String quOrderById= quOrderby.getId();
for (Object[] objects : list) {
if(quOrderById.equals(objects[0].toString())){
Float sumOrderyNum=Float.parseFloat(objects[1].toString());
count+=sumOrderyNum;
quOrderby.setAnOrderSum(sumOrderyNum.intValue());
continue;
}
}
}
question.setAnCount(count);
*/
int count=0;
List<QuOrderby> list2 = new ArrayList<QuOrderby>();
for (Object[] objects : list) {
Float sumOrderyNum=Float.parseFloat(objects[1].toString());
String quOrderById= objects[0].toString();
for (QuOrderby quOrderby : quOrderbies) {
if(quOrderById.equals(quOrderby.getId())){
quOrderby.setAnOrderSum(sumOrderyNum.intValue());
list2.add(quOrderby);
}
}
}
// question.setAnCount(count);
question.setQuOrderbys(list2);
| 50 | 59 | 468 | 527 |
406 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnScoreDaoImpl.java | AnScoreDaoImpl | findGroupStats | class AnScoreDaoImpl extends BaseDaoImpl<AnScore, String> implements AnScoreDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select qu_row_id,count(qu_row_id),AVG(answser_score) from t_an_score where visibility=1 and qu_id=? GROUP BY qu_row_id";
List<Object[]> list=this.getSession().createSQLQuery(sql).setParameter(1,question.getId()).list();
List<QuScore> quScores=question.getQuScores();
int count=0;
for (QuScore quScore : quScores) {
String quScoreId=quScore.getId();
for (Object[] objects : list) {
if(quScoreId.equals(objects[0].toString())){
int anCount=Integer.parseInt(objects[1].toString());
count+=anCount;
quScore.setAnCount(anCount);
quScore.setAvgScore(Float.parseFloat(objects[2].toString()));;
continue;
}
}
}
question.setAnCount(count);
| 29 | 59 | 283 | 342 |
407 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/AnUploadFileDaoImpl.java | AnUploadFileDaoImpl | findGroupStats | class AnUploadFileDaoImpl extends BaseDaoImpl<AnUplodFile, String> implements AnUploadFileDao {
@Override
public void findGroupStats(Question question) {<FILL_FUNCTION_BODY>}
} |
String sql="select count(case when file_path='' then file_path end) emptyCount, count(case when file_path!='' then file_path end) blankCount from t_an_uplodfile where visibility=1 and qu_id=?";
Object[] objs=(Object[]) this.getSession().createSQLQuery(sql).setParameter(1, question.getId()).uniqueResult();
question.setRowContent(objs[0].toString());//未回答数
question.setOptionContent(objs[1].toString());//回答的项数
question.setAnCount(Integer.parseInt(objs[1].toString()));
| 27 | 64 | 173 | 237 |
409 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/QuRadioDaoImpl.java | QuRadioDaoImpl | quOrderByIdDel1 | class QuRadioDaoImpl extends BaseDaoImpl<QuRadio, String> implements QuRadioDao {
public void quOrderByIdDel1(String quId,Integer orderById){<FILL_FUNCTION_BODY>}
} |
if(quId!=null && !"".equals(quId)){
String sql="update t_qu_radio set order_by_id=order_by_id-1 where qu_id=? and order_by_id>=?";
//更新排序号
SQLQuery query=this.getSession().createSQLQuery(sql);
query.setParameter(1, quId);
query.setParameter(2, orderById);
query.executeUpdate();
}
| 14 | 64 | 133 | 197 |
412 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/dao/impl/SurveyStatsDaoImpl.java | SurveyStatsDaoImpl | findStatsDataCross | class SurveyStatsDaoImpl extends BaseDaoImpl<SurveyStats, String> implements SurveyStatsDao{
@Override
public void findStatsDataCross(Question rowQuestion, Question colQuestion) {<FILL_FUNCTION_BODY>}
private void checkboxRowDataCross(Question rowQuestion, Question colQuestion) {
// TODO Auto-generated method stub
}
private void radioRowDataCross(Question rowQuestion, Question colQuestion) {
// TODO Auto-generated method stub
}
private String getQuItemName(Question question){
String result=null;
QuType quType=question.getQuType();
if(quType==QuType.YESNO){
result="yesno_answer";
}else if(quType==QuType.RADIO){
result="qu_item_id";
}
return result;
}
} |
String sql="select yesno_answer,qu_item_id,count(*) from t_an_yesno t1, t_an_radio t2"+
"where t1.qu_id='402880e63dd92431013dd9297ecc0000'"+
"and t2.qu_id='402881c83dbff250013dbff6b2d50000'"+
"and t1.belong_answer_id=t2.belong_answer_id GROUP BY yesno_answer,qu_item_id";
getQuItemName(rowQuestion);
getQuItemName(colQuestion);
QuType quType=rowQuestion.getQuType();
if(quType==QuType.RADIO){
radioRowDataCross(rowQuestion,colQuestion);
}else if(quType==QuType.CHECKBOX){
checkboxRowDataCross(rowQuestion,colQuestion);
}
| 19 | 251 | 286 | 537 |
413 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnCheckboxManagerImpl.java | AnCheckboxManagerImpl | findAnswer | class AnCheckboxManagerImpl extends BaseServiceImpl<AnCheckbox, String> implements AnCheckboxManager {
@Autowired
private AnCheckboxDao anCheckboxDao;
@Override
public void setBaseDao() {
this.baseDao=anCheckboxDao;
}
//根据exam_user信息查询答案
public List<AnCheckbox> findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anCheckboxDao.findGroupStats(question);
}
@Override
public List<DataCross> findStatsDataCross(Question rowQuestion,
Question colQuestion) {
return anCheckboxDao.findStatsDataCross(rowQuestion,colQuestion);
}
@Override
public List<DataCross> findStatsDataChart(Question question) {
return anCheckboxDao.findStatsDataChart(question);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anCheckboxDao.find(criterion1,criterion2);
| 7 | 285 | 86 | 371 |
414 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnDFillblankManagerImpl.java | AnDFillblankManagerImpl | findAnswer | class AnDFillblankManagerImpl extends BaseServiceImpl<AnDFillblank, String> implements AnDFillblankManager{
@Autowired
private AnDFillblankDao anDFillblankDao;
@Override
public void setBaseDao() {
this.baseDao=anDFillblankDao;
}
//根据exam_user信息查询答案
public List<AnDFillblank> findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anDFillblankDao.findGroupStats(question);
}
public Page<AnDFillblank> findPage(Page<AnDFillblank> page, String quItemId){
Criterion cri1 = Restrictions.eq("quItemId",quItemId);
Criterion cri2 = Restrictions.eq("visibility",1);
return findPage(page,cri1,cri2);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anDFillblankDao.find(criterion1,criterion2);
| 7 | 275 | 87 | 362 |
415 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnEnumquManagerImpl.java | AnEnumquManagerImpl | findAnswer | class AnEnumquManagerImpl extends BaseServiceImpl<AnEnumqu, String> implements AnEnumquManager {
@Autowired
private AnEnumquDao anEnumquDao;
@Override
public void setBaseDao() {
this.baseDao=anEnumquDao;
}
//根据exam_user信息查询答案
public List<AnEnumqu> findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anEnumquDao.findGroupStats(question);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anEnumquDao.find(criterion1,criterion2);
| 7 | 170 | 86 | 256 |
416 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnFillblankManagerImpl.java | AnFillblankManagerImpl | findAnswer | class AnFillblankManagerImpl extends BaseServiceImpl<AnFillblank, String> implements AnFillblankManager {
@Autowired
private AnFillblankDao anFillblankDao;
@Override
public void setBaseDao() {
this.baseDao=anFillblankDao;
}
//根据exam_user信息查询答案
public AnFillblank findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anFillblankDao.findGroupStats(question);
}
@Override
public Page<AnFillblank> findPage(Page<AnFillblank> page, String quId) {
Criterion cri1 = Restrictions.eq("quId",quId);
Criterion cri2 = Restrictions.eq("visibility",1);
return findPage(page,cri1,cri2);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anFillblankDao.findUnique(criterion1,criterion2);
| 7 | 266 | 88 | 354 |
417 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnOrderManagerImpl.java | AnOrderManagerImpl | findAnswer | class AnOrderManagerImpl extends BaseServiceImpl<AnOrder, String> implements AnOrderManager {
@Autowired
private AnOrderDao anOrderDao;
@Override
public void setBaseDao() {
this.baseDao=anOrderDao;
}
@Override
public List<AnOrder> findAnswer(String belongAnswerId, String quId) {<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anOrderDao.findGroupStats(question);
}
} | //belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anOrderDao.findByOrder("orderyNum",true,criterion1,criterion2);
// return anOrderDao.find(criterion1,criterion2);
| 8 | 158 | 112 | 270 |
418 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnRadioManagerImpl.java | AnRadioManagerImpl | findAnswer | class AnRadioManagerImpl extends BaseServiceImpl<AnRadio, String> implements AnRadioManager {
@Autowired
private AnRadioDao anRadioDao;
@Override
public void setBaseDao() {
this.baseDao=anRadioDao;
}
//根据exam_user信息查询答案
public AnRadio findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anRadioDao.findGroupStats(question);
}
@Override
public List<DataCross> findStatsDataCross(Question rowQuestion,
Question colQuestion) {
return anRadioDao.findStatsDataCross(rowQuestion, colQuestion);
}
@Override
public List<DataCross> findStatsDataChart(Question question) {
return anRadioDao.findStatsDataChart(question);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anRadioDao.findUnique(criterion1,criterion2);
| 7 | 267 | 88 | 355 |
419 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnScoreManagerImpl.java | AnScoreManagerImpl | findAnswer | class AnScoreManagerImpl extends BaseServiceImpl<AnScore, String> implements AnScoreManager {
@Autowired
private AnScoreDao anScoreDao;
@Override
public void setBaseDao() {
this.baseDao=anScoreDao;
}
@Override
public List<AnScore> findAnswer(String belongAnswerId, String quId) {<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anScoreDao.findGroupStats(question);
}
} | //belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anScoreDao.find(criterion1,criterion2);
| 7 | 158 | 82 | 240 |
420 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnUploadFileManagerImpl.java | AnUploadFileManagerImpl | findAnswer | class AnUploadFileManagerImpl extends BaseServiceImpl<AnUplodFile, String> implements AnUploadFileManager {
@Autowired
private AnUploadFileDao anUploadFileDao;
@Override
public void setBaseDao() {
this.baseDao=anUploadFileDao;
}
//根据exam_user信息查询答案
public List<AnUplodFile> findAnswer(String belongAnswerId, String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anUploadFileDao.findGroupStats(question);
}
public List<AnUplodFile> findAnswer(String surveyId){
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongId", surveyId);
return anUploadFileDao.find(criterion1);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anUploadFileDao.find(criterion1,criterion2);
| 7 | 250 | 86 | 336 |
421 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/AnYesnoManagerImpl.java | AnYesnoManagerImpl | findAnswer | class AnYesnoManagerImpl extends BaseServiceImpl<AnYesno, String> implements AnYesnoManager {
@Autowired
private AnYesnoDao anYesnoDao;
@Override
public void setBaseDao() {
this.baseDao=anYesnoDao;
}
//根据exam_user信息查询答案
public AnYesno findAnswer(String belongAnswerId,String quId){<FILL_FUNCTION_BODY>}
@Override
public void findGroupStats(Question question) {
anYesnoDao.findGroupStats(question);
}
@Override
public List<DataCross> findStatsDataCross(Question rowQuestion, Question colQuestion) {
return anYesnoDao.findStatsDataCross(rowQuestion,colQuestion);
}
@Override
public List<DataCross> findStatsDataChart(Question question) {
return anYesnoDao.findStatsDataChart(question);
}
} |
//belongAnswerId quId
Criterion criterion1=Restrictions.eq("belongAnswerId", belongAnswerId);
Criterion criterion2=Restrictions.eq("quId", quId);
return anYesnoDao.findUnique(criterion1,criterion2);
| 7 | 267 | 88 | 355 |
422 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuCheckboxManagerImpl.java | QuCheckboxManagerImpl | findByQuId | class QuCheckboxManagerImpl extends BaseServiceImpl<QuCheckbox, String> implements QuCheckboxManager {
@Autowired
private QuCheckboxDao quCheckboxDao;
@Override
public void setBaseDao() {
this.baseDao=quCheckboxDao;
}
public List<QuCheckbox> findByQuId(String quId){<FILL_FUNCTION_BODY>}
public int getOrderById(String quId){
Criterion criterion=Restrictions.eq("quId", quId);
QuCheckbox quCheckbox=quCheckboxDao.findFirst("orderById", false, criterion);
if(quCheckbox!=null){
return quCheckbox.getOrderById();
}
return 0;
}
/*******************************************************************8
* 更新操作
*/
@Override
@Transactional
public QuCheckbox upOptionName(String quId,String quItemId, String optionName) {
if(quItemId!=null && !"".equals(quItemId)){
QuCheckbox quCheckbox=quCheckboxDao.get(quItemId);
quCheckbox.setOptionName(optionName);
quCheckboxDao.save(quCheckbox);
return quCheckbox;
}else{
//取orderById
int orderById=getOrderById(quId);
//新加选项
QuCheckbox quCheckbox=new QuCheckbox();
quCheckbox.setQuId(quId);
quCheckbox.setOptionName(optionName);
//title
quCheckbox.setOrderById(++orderById);
quCheckbox.setOptionTitle(orderById+"");
quCheckboxDao.save(quCheckbox);
return quCheckbox;
}
}
@Override
@Transactional
public List<QuCheckbox> saveManyOptions(String quId,List<QuCheckbox> quCheckboxs) {
//取orderById
int orderById=getOrderById(quId);
for (QuCheckbox quCheckbox : quCheckboxs) {
//新加选项
quCheckbox.setOrderById(++orderById);
quCheckbox.setOptionTitle(orderById+"");
quCheckboxDao.save(quCheckbox);
}
return quCheckboxs;
}
@Override
@Transactional
public void ajaxDelete(String quItemId) {
QuCheckbox quCheckbox=get(quItemId);
quCheckbox.setVisibility(0);
quCheckboxDao.save(quCheckbox);
}
@Override
@Transactional
public void saveAttr(String quItemId, String isNote) {
QuCheckbox quCheckbox=get(quItemId);
if(isNote!=null && "1".equals(isNote)){
quCheckbox.setIsNote(1);
}else{
quCheckbox.setIsNote(0);
}
quCheckboxDao.save(quCheckbox);
}
} |
/*
Page<QuCheckbox> page=new Page<QuCheckbox>();
page.setOrderBy("orderById");
page.setOrderDir("asc");
List<PropertyFilter> filters=new ArrayList<PropertyFilter>();
filters.add(new PropertyFilter("EQS_quId", quId));
filters.add(new PropertyFilter("EQI_visibility", "1"));
return findAll(page, filters);
*/
CriteriaBuilder criteriaBuilder=quCheckboxDao.getSession().getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuCheckbox.class);
Root root = criteriaQuery.from(QuCheckbox.class);
criteriaQuery.select(root);
Predicate eqQuId = criteriaBuilder.equal(root.get("quId"),quId);
Predicate eqVisibility = criteriaBuilder.equal(root.get("visibility"),1);
criteriaQuery.where(eqQuId,eqVisibility);
criteriaQuery.orderBy(criteriaBuilder.asc(root.get("orderById")));
return quCheckboxDao.findAll(criteriaQuery);
| 25 | 855 | 322 | 1,177 |
423 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuMultiFillblankManagerImpl.java | QuMultiFillblankManagerImpl | findByQuId | class QuMultiFillblankManagerImpl extends BaseServiceImpl<QuMultiFillblank, String> implements QuMultiFillblankManager {
@Autowired
private QuMultiFillblankDao quMultiFillblankDao;
@Override
public void setBaseDao() {
this.baseDao=quMultiFillblankDao;
}
public List<QuMultiFillblank> findByQuId(String quId){<FILL_FUNCTION_BODY>}
public int getOrderById(String quId){
Criterion criterion=Restrictions.eq("quId", quId);
QuMultiFillblank quMultiFillblank=quMultiFillblankDao.findFirst("orderById", false, criterion);
if(quMultiFillblank!=null){
return quMultiFillblank.getOrderById();
}
return 0;
}
/*******************************************************************8
* 更新操作
*/
@Override
@Transactional
public QuMultiFillblank upOptionName(String quId,String quItemId, String optionName) {
if(quItemId!=null && !"".equals(quItemId)){
QuMultiFillblank quMultiFillblank=quMultiFillblankDao.get(quItemId);
quMultiFillblank.setOptionName(optionName);
quMultiFillblankDao.save(quMultiFillblank);
return quMultiFillblank;
}else{
//取orderById
int orderById=getOrderById(quId);
//新加选项
QuMultiFillblank quMultiFillblank=new QuMultiFillblank();
quMultiFillblank.setQuId(quId);
quMultiFillblank.setOptionName(optionName);
//title
quMultiFillblank.setOrderById(++orderById);
quMultiFillblank.setOptionTitle(orderById+"");
quMultiFillblankDao.save(quMultiFillblank);
return quMultiFillblank;
}
}
@Override
@Transactional
public List<QuMultiFillblank> saveManyOptions(String quId,List<QuMultiFillblank> quMultiFillblanks) {
//取orderById
int orderById=getOrderById(quId);
for (QuMultiFillblank quMultiFillblank : quMultiFillblanks) {
//新加选项
quMultiFillblank.setOrderById(++orderById);
quMultiFillblank.setOptionTitle(orderById+"");
quMultiFillblankDao.save(quMultiFillblank);
}
return quMultiFillblanks;
}
@Override
@Transactional
public void ajaxDelete(String quItemId) {
QuMultiFillblank quMultiFillblank=get(quItemId);
quMultiFillblank.setVisibility(0);
quMultiFillblankDao.save(quMultiFillblank);
}
@Override
@Transactional
public void saveAttr(String quItemId) {
QuMultiFillblank quMultiFillblank=get(quItemId);
quMultiFillblankDao.save(quMultiFillblank);
}
} |
/*Page<QuMultiFillblank> page=new Page<QuMultiFillblank>();
page.setOrderBy("orderById");
page.setOrderDir("asc");
List<PropertyFilter> filters=new ArrayList<PropertyFilter>();
filters.add(new PropertyFilter("EQS_quId", quId));
filters.add(new PropertyFilter("EQI_visibility", "1"));
return findAll(page, filters);
*/
CriteriaBuilder criteriaBuilder=quMultiFillblankDao.getSession().getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuMultiFillblank.class);
Root root = criteriaQuery.from(QuMultiFillblank.class);
criteriaQuery.select(root);
Predicate eqQuId = criteriaBuilder.equal(root.get("quId"),quId);
Predicate eqVisibility = criteriaBuilder.equal(root.get("visibility"),1);
criteriaQuery.where(eqQuId,eqVisibility);
criteriaQuery.orderBy(criteriaBuilder.asc(root.get("orderById")));
return quMultiFillblankDao.findAll(criteriaQuery);
| 25 | 842 | 320 | 1,162 |
424 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuOrderbyManagerImpl.java | QuOrderbyManagerImpl | findByQuId | class QuOrderbyManagerImpl extends BaseServiceImpl<QuOrderby, String> implements QuOrderbyManager {
@Autowired
private QuOrderbyDao quOrderbyDao;
@Override
public void setBaseDao() {
this.baseDao=quOrderbyDao;
}
public List<QuOrderby> findByQuId(String quId){<FILL_FUNCTION_BODY>}
public int getOrderById(String quId){
Criterion criterion=Restrictions.eq("quId", quId);
QuOrderby quOrderby=quOrderbyDao.findFirst("orderById", false, criterion);
if(quOrderby!=null){
return quOrderby.getOrderById();
}
return 0;
}
/*******************************************************************8
* 更新操作
*/
@Override
@Transactional
public QuOrderby upOptionName(String quId,String quItemId, String optionName) {
if(quItemId!=null && !"".equals(quItemId)){
QuOrderby quOrderby=quOrderbyDao.get(quItemId);
quOrderby.setOptionName(optionName);
quOrderbyDao.save(quOrderby);
return quOrderby;
}else{
//取orderById
int orderById=getOrderById(quId);
//新加选项
QuOrderby quOrderby=new QuOrderby();
quOrderby.setQuId(quId);
quOrderby.setOptionName(optionName);
//title
quOrderby.setOrderById(++orderById);
quOrderby.setOptionTitle(orderById+"");
quOrderbyDao.save(quOrderby);
return quOrderby;
}
}
@Override
@Transactional
public List<QuOrderby> saveManyOptions(String quId,List<QuOrderby> quOrderbys) {
//取orderById
int orderById=getOrderById(quId);
for (QuOrderby quOrderby : quOrderbys) {
//新加选项
quOrderby.setOrderById(++orderById);
quOrderby.setOptionTitle(orderById+"");
quOrderbyDao.save(quOrderby);
}
return quOrderbys;
}
@Override
@Transactional
public void ajaxDelete(String quItemId) {
QuOrderby quOrderby=get(quItemId);
quOrderby.setVisibility(0);
quOrderbyDao.save(quOrderby);
}
@Override
@Transactional
public void saveAttr(String quItemId) {
QuOrderby quOrderby=get(quItemId);
quOrderbyDao.save(quOrderby);
}
} |
/*Page<QuOrderby> page=new Page<QuOrderby>();
page.setOrderBy("orderById");
page.setOrderDir("asc");
List<PropertyFilter> filters=new ArrayList<PropertyFilter>();
filters.add(new PropertyFilter("EQS_quId", quId));
filters.add(new PropertyFilter("EQI_visibility", "1"));
return findAll(page, filters);
*/
CriteriaBuilder criteriaBuilder=quOrderbyDao.getSession().getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuOrderby.class);
Root root = criteriaQuery.from(QuOrderby.class);
criteriaQuery.select(root);
Predicate eqQuId = criteriaBuilder.equal(root.get("quId"),quId);
Predicate eqVisibility = criteriaBuilder.equal(root.get("visibility"),1);
criteriaQuery.where(eqQuId,eqVisibility);
criteriaQuery.orderBy(criteriaBuilder.asc(root.get("orderById")));
return quOrderbyDao.findAll(criteriaQuery);
| 25 | 794 | 314 | 1,108 |
425 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuRadioManagerImpl.java | QuRadioManagerImpl | findByQuId | class QuRadioManagerImpl extends BaseServiceImpl<QuRadio, String> implements QuRadioManager {
@Autowired
private QuRadioDao quRadioDao;
@Override
public void setBaseDao() {
this.baseDao=quRadioDao;
}
/*******************************************************************8
* 查询操作
*/
/**
* 得到某一题的选项
*/
public List<QuRadio> findByQuId(String quId){<FILL_FUNCTION_BODY>}
public int getOrderById(String quId){
Criterion criterion=Restrictions.eq("quId", quId);
QuRadio quRadio=quRadioDao.findFirst("orderById", false, criterion);
if(quRadio!=null){
return quRadio.getOrderById();
}
return 0;
}
/*******************************************************************8
* 更新操作
*/
@Override
@Transactional
public QuRadio upOptionName(String quId,String quItemId, String optionName) {
if(quItemId!=null && !"".equals(quItemId)){
QuRadio quRadio=quRadioDao.get(quItemId);
quRadio.setOptionName(optionName);
quRadioDao.save(quRadio);
return quRadio;
}else{
//取orderById
int orderById=getOrderById(quId);
//新加选项
QuRadio quRadio=new QuRadio();
quRadio.setQuId(quId);
quRadio.setOptionName(optionName);
//title
quRadio.setOrderById(++orderById);
quRadio.setOptionTitle(orderById+"");
quRadioDao.save(quRadio);
return quRadio;
}
}
@Override
@Transactional
public List<QuRadio> saveManyOptions(String quId,List<QuRadio> quRadios) {
//取orderById
int orderById=getOrderById(quId);
for (QuRadio quRadio : quRadios) {
//新加选项
quRadio.setOrderById(++orderById);
quRadio.setOptionTitle(orderById+"");
quRadioDao.save(quRadio);
}
return quRadios;
}
@Override
@Transactional
public void ajaxDelete(String quItemId) {
/*QuRadio quRadio=get(quItemId);
quRadio.setVisibility(0);
quRadioDao.save(quRadio);*/
QuRadio quRadio=get(quItemId);
String quId=quRadio.getQuId();
int orderById=quRadio.getOrderById();
quRadioDao.delete(quItemId);
//修改排序号
quRadioDao.quOrderByIdDel1(quId, orderById);
}
@Override
@Transactional
public void saveAttr(String quItemId, String isNote) {
QuRadio quRadio=get(quItemId);
if(isNote!=null && "1".equals(isNote)){
quRadio.setIsNote(1);
}else{
quRadio.setIsNote(0);
}
quRadioDao.save(quRadio);
}
} |
/*Page<QuRadio> page=new Page<QuRadio>();
page.setOrderBy("orderById");
page.setOrderDir("asc");
List<PropertyFilter> filters=new ArrayList<PropertyFilter>();
filters.add(new PropertyFilter("EQS_quId", quId));
filters.add(new PropertyFilter("EQI_visibility", "1"));
return findAll(page, filters);
*/
CriteriaBuilder criteriaBuilder=quRadioDao.getSession().getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuRadio.class);
Root root = criteriaQuery.from(QuRadio.class);
criteriaQuery.select(root);
Predicate eqQuId = criteriaBuilder.equal(root.get("quId"),quId);
Predicate eqVisibility = criteriaBuilder.equal(root.get("visibility"),1);
criteriaQuery.where(eqQuId,eqVisibility);
criteriaQuery.orderBy(criteriaBuilder.asc(root.get("orderById")));
return quRadioDao.findAll(criteriaQuery);
| 25 | 985 | 314 | 1,299 |
426 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuScoreManagerImpl.java | QuScoreManagerImpl | findByQuId | class QuScoreManagerImpl extends BaseServiceImpl<QuScore, String> implements QuScoreManager {
@Autowired
private QuScoreDao quScoreDao;
@Override
public void setBaseDao() {
this.baseDao=quScoreDao;
}
public List<QuScore> findByQuId(String quId){<FILL_FUNCTION_BODY>}
public int getOrderById(String quId){
Criterion criterion=Restrictions.eq("quId", quId);
QuScore quRadio=quScoreDao.findFirst("orderById", false, criterion);
if(quRadio!=null){
return quRadio.getOrderById();
}
return 0;
}
/*******************************************************************8
* 更新操作
*/
@Override
@Transactional
public QuScore upOptionName(String quId,String quItemId, String optionName) {
if(quItemId!=null && !"".equals(quItemId)){
QuScore quScore=quScoreDao.get(quItemId);
quScore.setOptionName(optionName);
quScoreDao.save(quScore);
return quScore;
}else{
//取orderById
int orderById=getOrderById(quId);
//新加选项
QuScore quScore=new QuScore();
quScore.setQuId(quId);
quScore.setOptionName(optionName);
//title
quScore.setOrderById(++orderById);
quScore.setOptionTitle(orderById+"");
quScoreDao.save(quScore);
return quScore;
}
}
@Override
@Transactional
public List<QuScore> saveManyOptions(String quId,List<QuScore> quScores) {
//取orderById
int orderById=getOrderById(quId);
for (QuScore quScore : quScores) {
//新加选项
quScore.setOrderById(++orderById);
quScore.setOptionTitle(orderById+"");
quScoreDao.save(quScore);
}
return quScores;
}
@Override
@Transactional
public void ajaxDelete(String quItemId) {
QuScore quScore=get(quItemId);
quScore.setVisibility(0);
quScoreDao.save(quScore);
}
@Override
@Transactional
public void saveAttr(String quItemId) {
QuScore quScore=get(quItemId);
quScoreDao.save(quScore);
}
} |
/*Page<QuScore> page=new Page<QuScore>();
page.setOrderBy("orderById");
page.setOrderDir("asc");
List<PropertyFilter> filters=new ArrayList<PropertyFilter>();
filters.add(new PropertyFilter("EQS_quId", quId));
filters.add(new PropertyFilter("EQI_visibility", "1"));
return findAll(page, filters);*/
CriteriaBuilder criteriaBuilder=quScoreDao.getSession().getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(QuScore.class);
Root root = criteriaQuery.from(QuScore.class);
criteriaQuery.select(root);
Predicate eqQuId = criteriaBuilder.equal(root.get("quId"),quId);
Predicate eqVisibility = criteriaBuilder.equal(root.get("visibility"),1);
criteriaQuery.where(eqQuId,eqVisibility);
criteriaQuery.orderBy(criteriaBuilder.asc(root.get("orderById")));
return quScoreDao.findAll(criteriaQuery);
| 25 | 750 | 304 | 1,054 |
427 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/QuestionBankManagerImpl.java | QuestionBankManagerImpl | findPage | class QuestionBankManagerImpl extends BaseServiceImpl<QuestionBank, String> implements QuestionBankManager {
@Autowired
private QuestionBankDao questionBankDao;
@Autowired
private AccountManager accountManager;
@Autowired
private QuestionManager questionManager;
@Override
public void setBaseDao() {
this.baseDao=questionBankDao;
}
@Override
public void save(QuestionBank t) {
User user = accountManager.getCurUser();
if(user!=null){
t.setUserId(user.getId());
super.save(t);
}
}
/**
* 得到当前目录所在的目录位置
*/
public List<QuestionBank> findPath(QuestionBank questionBank) {
List<QuestionBank> resultList=new ArrayList<QuestionBank>();
if(questionBank!=null){
List<QuestionBank> dirPathList=new ArrayList<QuestionBank>();
dirPathList.add(questionBank);
String parentUuid=questionBank.getParentId();
while(parentUuid!=null && !"".equals(parentUuid)){
QuestionBank questionBank2=get(parentUuid);
parentUuid=questionBank2.getParentId();
dirPathList.add(questionBank2);
}
for (int i = dirPathList.size()-1; i >=0; i--) {
resultList.add(dirPathList.get(i));
}
}
return resultList;
}
@Override
public QuestionBank getBank(String id) {
QuestionBank questionBank=get(id);
return questionBank;
}
@Override
public QuestionBank findByNameUn(String id, String parentId, String bankName) {
List<Criterion> criterions=new ArrayList<Criterion>();
Criterion eqName=Restrictions.eq("bankName", bankName);
Criterion eqParentId=Restrictions.eq("parentId", parentId);
criterions.add(eqName);
criterions.add(eqParentId);
if(id!=null && !"".equals(id)){
Criterion eqId=Restrictions.ne("id", id);
criterions.add(eqId);
}
return questionBankDao.findFirst(criterions);
}
@Override
public Page<QuestionBank> findPage(Page<QuestionBank> page, QuestionBank entity) {<FILL_FUNCTION_BODY>}
@Override
@Transactional
public void delete(String id) {
//设为不可见
QuestionBank questionBank=get(id);
questionBank.setVisibility(0);
questionBankDao.save(questionBank);
Criterion criterion=Restrictions.eq("parentId", questionBank.getId());
List<QuestionBank> banks=findList(criterion);
if(banks!=null){
for (QuestionBank questionBank2 : banks) {
delete(questionBank2);
}
}
}
@Transactional
public void delete(QuestionBank questionBank) {
String id=questionBank.getId();
//目录ID,为1的为系统默认注册用户目录不能删除
if(!"1".equals(id)){
//设为不可见
questionBank.setVisibility(0);
Criterion criterion=Restrictions.eq("parentId", questionBank.getId());
List<QuestionBank> banks=findList(criterion);
if(banks!=null){
for (QuestionBank questionBank2 : banks) {
delete(questionBank2);
}
}
}
}
@Override
@Transactional
public void executeBank(String id) {
QuestionBank questionBank=getBank(id);
questionBank.setBankState(1);
//更新下题目数
List<Question> questions=questionManager.find(id, "1");
if(questions!=null){
questionBank.setQuNum(questions.size());
}
super.save(questionBank);
}
@Override
@Transactional
public void closeBank(String id) {
QuestionBank questionBank=getBank(id);
questionBank.setBankState(0);
super.save(questionBank);
}
public List<QuestionBank> newQuestionBank() {
List<QuestionBank> result=new ArrayList<QuestionBank>();
try{
QuestionBank entity=new QuestionBank();
Page<QuestionBank> page=new Page<QuestionBank>();
page.setPageSize(15);
page=findPage(page,entity);
result=page.getResult();
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
} |
page.setOrderBy("createDate");
page.setOrderDir("desc");
List<Criterion> criterions=new ArrayList<Criterion>();
criterions.add(Restrictions.eq("visibility", 1));
criterions.add(Restrictions.eq("dirType", 2));
criterions.add(Restrictions.eq("bankState", 1));
Integer bankTag = entity.getBankTag();
if(bankTag==null){
bankTag=0;
}
criterions.add(Restrictions.eq("bankTag", bankTag));
String groupId1 = entity.getGroupId1();
String groupId2 = entity.getGroupId2();
if(groupId1!=null && !"".equals(groupId1)){
criterions.add(Restrictions.eq("groupId1", groupId1));
}
if(groupId2!=null && !"".equals(groupId2)){
criterions.add(Restrictions.eq("groupId2", groupId2));
}
return questionBankDao.findPageList(page, criterions);
| 24 | 1,431 | 317 | 1,748 |
430 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/SurveyDetailManagerImpl.java | SurveyDetailManagerImpl | saveBaseUp | class SurveyDetailManagerImpl extends BaseServiceImpl<SurveyDetail, String> implements SurveyDetailManager{
@Autowired
private SurveyDetailDao surveyDetailDao;
@Override
public void setBaseDao() {
this.baseDao=surveyDetailDao;
}
@Transactional
@Override
public void save(SurveyDetail t) {
//判断有无,有则更新
SurveyDetail surveyDetail=findUn(t.getDirId());
if(surveyDetail==null){
surveyDetail=new SurveyDetail();
}
ReflectionUtils.copyAttr(t,surveyDetail);
super.save(surveyDetail);
}
private SurveyDetail findUn(String dirId){
Criterion criterion=Restrictions.eq("dirId", dirId);
List<SurveyDetail> details=surveyDetailDao.find(criterion);
if(details!=null && details.size()>0){
return details.get(0);
}
return null;
}
@Override
public SurveyDetail getBySurveyId(String surveyId) {
return findUn(surveyId);
}
@Transactional
@Override
public void saveBaseUp(SurveyDetail t) {<FILL_FUNCTION_BODY>}
} |
//判断有无,有则更新
SurveyDetail surveyDetail=findUn(t.getDirId());
if(surveyDetail!=null){
surveyDetail.setEffective(t.getEffective());
surveyDetail.setEffectiveIp(t.getEffectiveIp());
surveyDetail.setRefresh(t.getRefresh());
surveyDetail.setRule(t.getRule());
surveyDetail.setRuleCode(t.getRuleCode());
surveyDetail.setYnEndTime(t.getYnEndTime());
surveyDetail.setYnEndNum(t.getYnEndNum());
surveyDetail.setEndNum(t.getEndNum());
surveyDetail.setEndTime(t.getEndTime());
super.save(surveyDetail);
}
| 2 | 362 | 242 | 604 |
433 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/SurveyStyleManagerImpl.java | SurveyStyleManagerImpl | save | class SurveyStyleManagerImpl implements SurveyStyleManager {
@Autowired
private SurveyStyleDao surveyStyleDao;
public SurveyStyle get(String id) {
return surveyStyleDao.findUniqueBy("id", id);
}
public SurveyStyle getBySurveyId(String surveyId) {
Criterion cri1=Restrictions.eq("surveyId", surveyId);
return surveyStyleDao.findFirst(cri1);
}
@Transactional
public void save(SurveyStyle surveyStyle){<FILL_FUNCTION_BODY>}
} |
String surveyId = surveyStyle.getSurveyId();
SurveyStyle upSurveyStyle = getBySurveyId(surveyId);
if(upSurveyStyle!=null){
ReflectionUtils.copyAttr(surveyStyle,upSurveyStyle);
surveyStyleDao.save(upSurveyStyle);
}else{
surveyStyleDao.save(surveyStyle);
}
| 7 | 166 | 117 | 283 |
434 | wkeyuan_DWSurvey | DWSurvey/src/main/java/net/diaowen/dwsurvey/service/impl/UserManagerImpl.java | UserManagerImpl | upData | class UserManagerImpl extends BaseServiceImpl<User, String> implements UserManager {
@Autowired
private UserDao userDao;
@Override
public void setBaseDao() {
this.baseDao=userDao;
}
@Override
public User adminSave(User entity) {
if(entity!=null){
if(StringUtils.isNotEmpty(entity.getId())){
entity.setId(null);
}
String pwd=entity.getPwd();
if(pwd!=null && !"".equals(pwd)){
//加点盐
// String salt=RandomUtils.randomWordNum(5);
String shaPassword = DigestUtils.sha1Hex(pwd);
entity.setShaPassword(shaPassword);
// entity.setSalt(salt);
}
super.save(entity);
return entity;
}
return null;
}
public Page<User> findPage(Page<User> page, User entity) {
List<Criterion> criterions=new ArrayList<Criterion>();
Integer status = entity.getStatus();
String loginName = entity.getLoginName();
if(status!=null && !"".equals(status)){
criterions.add(Restrictions.eq("status", status));
}
if(loginName!=null && !"".equals(loginName)){
criterions.add(Restrictions.like("loginName", "%"+loginName+"%"));
}
criterions.add(Restrictions.disjunction().add(Restrictions.eq("visibility", 1)).add(Restrictions.isNull("visibility")));
page.setOrderBy("createTime");
page.setOrderDir("desc");
return super.findPageByCri(page, criterions);
}
/**
* 禁用账号
*/
@Transactional
@Override
public void disUser(String id) {
User user=get(id);
int status=user.getStatus();
if(status==0){
user.setStatus(1);
}else{
user.setStatus(0);
}
save(user);
}
/**
* 删除账号
*/
@Transactional
@Override
public void delete(String id) {
User user=get(id);
user.setVisibility(0);
save(user);
}
@Override
public User findNameUn(String id, String loginName) {
List<Criterion> criterions=new ArrayList<Criterion>();
criterions.add(Restrictions.eq("loginName", loginName));
if(id!=null && !"".equals(id)){
criterions.add(Restrictions.ne("id", id));
}
return userDao.findFirst(criterions);
}
@Override
public User findEmailUn(String id, String email) {
List<Criterion> criterions=new ArrayList<Criterion>();
criterions.add(Restrictions.eq("email", email));
if(id!=null && !"".equals(id)){
criterions.add(Restrictions.ne("id", id));
}
return userDao.findFirst(criterions);
}
@Override
public User findByCode(String code) {
Criterion criterion=Restrictions.eq("findPwdCode", code);
return userDao.findFirst(criterion);
}
@Override
public User findByActivationCode(String activationCode) {
Criterion criterion=Restrictions.eq("activationCode", activationCode);
return userDao.findFirst(criterion);
}
@Override
public void resetUserGroup(String groupId) {
userDao.resetUserGroup(groupId);
}
@Override
public Page<User> findPageByKeyword(Page<User> page, String keyword) {
Criterion cri1=Restrictions.like("name", "%"+keyword+"%");
// Criterion cri2=Restrictions.like("pinyin", "%"+keyword+"%");
// Criterion cri3 = Restrictions.or(cri1,cri2);
return userDao.findPage(page,cri1);
}
public Page<User> findPage(Page<User> page, Integer status, String loginName, String name, String email,String cellphone) {
List<Criterion> criterions=new ArrayList<Criterion>();
if(status!=null){
criterions.add(Restrictions.eq("status", status));
}
if(StringUtils.isNotEmpty(loginName)){
criterions.add(Restrictions.like("loginName", "%"+loginName+"%"));
}
if(StringUtils.isNotEmpty(name)){
criterions.add(Restrictions.like("name", "%"+name+"%"));
}
if(StringUtils.isNotEmpty(email)){
criterions.add(Restrictions.like("email", "%"+email+"%"));
}
if(StringUtils.isNotEmpty(cellphone)){
criterions.add(Restrictions.like("cellphone", "%"+cellphone+"%"));
}
criterions.add(Restrictions.disjunction().add(Restrictions.eq("visibility", 1)).add(Restrictions.isNull("visibility")));
if(StringUtils.isEmpty(page.getOrderBy())){
page.setOrderBy("createTime");
page.setOrderDir("desc");
}
return super.findPageByCri(page, criterions);
}
@Transactional
@Override
public HttpResult upData(User user) {<FILL_FUNCTION_BODY>}
@Transactional
@Override
public void deleteData(String[] ids) {
for (String id:ids) {
userDao.delete(id);
}
}
} |
if(user!=null){
String id = user.getId();
if(id!=null){
User dbUser = getModel(id);
dbUser.setLoginName(user.getLoginName());
/*
dbUser.setName(user.getName());
dbUser.setEmail(user.getEmail());
dbUser.setCellphone(user.getCellphone());
*/
dbUser.setStatus(user.getStatus());
String pwd = user.getPwd();
if(StringUtils.isNotEmpty(pwd)) {
//加点盐
String shaPassword = DigestUtils.sha1Hex(pwd);
dbUser.setShaPassword(shaPassword);
}
super.save(dbUser);
return HttpResult.SUCCESS();
}
}
return HttpResult.FAILURE("user为null");
| 16 | 1,696 | 253 | 1,949 |
435 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/configuration/ApolloAutoConfiguration.java | ApolloAutoConfiguration | getNamespace | class ApolloAutoConfiguration {
@Autowired
private Environment environment;
@Bean
@ConditionalOnMissingBean
public Config apolloConfig() {
String namespace = getNamespace(environment);
return ConfigService.getConfig(namespace);
}
@Bean
public ApolloOperation apolloOperation() {
return new ApolloOperation();
}
public static String getNamespace(Environment environment) {<FILL_FUNCTION_BODY>}
} |
String namespace = environment.getProperty(ApolloConstant.APOLLO_NAMESPACE);
if (StringUtils.isEmpty(namespace) || namespace.contains(ApolloConstant.SEPARATE)) {
namespace = environment.getProperty(ApolloConstant.APOLLO_BOOTSTRAP_NAMESPACES);
}
if (StringUtils.isEmpty(namespace) || namespace.contains(ApolloConstant.SEPARATE)) {
namespace = ApolloConstant.NAMESPACE_APPLICATION;
}
return namespace;
| 93 | 120 | 135 | 255 |
436 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/operation/ApolloOperation.java | ApolloOperation | subscribeConfig | class ApolloOperation {
@Autowired
private Config apolloConfig;
public String getConfig(String group, String serviceId) {
return apolloConfig.getProperty(group + "-" + serviceId, null);
}
public ConfigChangeListener subscribeConfig(String group, String serviceId, ApolloSubscribeCallback apolloSubscribeCallback) {<FILL_FUNCTION_BODY>}
public void unsubscribeConfig(String group, String serviceId, ConfigChangeListener configChangeListener) {
apolloConfig.removeChangeListener(configChangeListener);
}
} |
ConfigChangeListener configChangeListener = new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
ConfigChange change = changeEvent.getChange(group + "-" + serviceId);
String config = change.getNewValue();
apolloSubscribeCallback.callback(config);
}
};
apolloConfig.addChangeListener(configChangeListener, Sets.newHashSet(group + "-" + serviceId));
return configChangeListener;
| 146 | 143 | 122 | 265 |
437 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-apollo/src/main/java/com/nepxion/discovery/common/apollo/proccessor/ApolloProcessor.java | ApolloProcessor | initialize | class ApolloProcessor extends DiscoveryConfigProcessor {
@Autowired
private ApolloOperation apolloOperation;
private ConfigChangeListener configChangeListener;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (configChangeListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
apolloOperation.unsubscribeConfig(group, dataId, configChangeListener);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.APOLLO;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
configChangeListener = apolloOperation.subscribeConfig(group, dataId, new ApolloSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = apolloOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 426 | 200 | 227 | 427 |
438 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/configuration/ConsulAutoConfiguration.java | ConsulAutoConfiguration | consulClient | class ConsulAutoConfiguration {
@Autowired
private Environment environment;
@Bean
public ConsulOperation consulOperation() {
return new ConsulOperation();
}
@Bean
@ConditionalOnMissingBean
public ConsulClient consulClient() {<FILL_FUNCTION_BODY>}
} |
String consulHost = environment.getProperty(ConsulConstant.CONSUL_HOST);
if (StringUtils.isBlank(consulHost)) {
throw new DiscoveryException(ConsulConstant.CONSUL_HOST + " can't be null or empty");
}
int consulPort = environment.getProperty(ConsulConstant.CONSUL_PORT, Integer.class);
return new ConsulClient(consulHost, consulPort);
| 78 | 84 | 117 | 201 |
439 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulListener.java | ConsulListener | run | class ConsulListener implements Runnable {
private String group;
private String serviceId;
private int timeout;
private String token;
private ConsulClient consulClient;
private ConsulSubscribeCallback consulSubscribeCallback;
private volatile long lastIndex;
private volatile boolean running = true;
public ConsulListener(String group, String serviceId, int timeout, String token, ConsulClient consulClient, ConsulSubscribeCallback consulSubscribeCallback) {
this.group = group;
this.serviceId = serviceId;
this.timeout = timeout;
this.token = token;
this.consulClient = consulClient;
this.consulSubscribeCallback = consulSubscribeCallback;
initialize();
}
private void initialize() {
Response<GetValue> response = consulClient.getKVValue(group + "-" + serviceId, token);
if (response != null) {
lastIndex = response.getConsulIndex();
}
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
public void stop() {
running = false;
}
} |
while (running) {
Response<GetValue> response = consulClient.getKVValue(group + "-" + serviceId, token, new QueryParams(timeout, lastIndex));
if (response == null) {
try {
TimeUnit.MILLISECONDS.sleep(timeout * 1000);
} catch (InterruptedException e) {
}
continue;
}
Long currentIndex = response.getConsulIndex();
if (currentIndex == null || currentIndex <= lastIndex) {
continue;
}
lastIndex = currentIndex;
GetValue getValue = response.getValue();
if (getValue != null) {
String value = getValue.getDecodedValue(StandardCharsets.UTF_8);
consulSubscribeCallback.callback(value);
}
}
| 320 | 296 | 210 | 506 |
440 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/operation/ConsulOperation.java | ConsulOperation | getConfig | class ConsulOperation {
@Autowired
private ConsulClient consulClient;
@Autowired
private Environment environment;
public String getConfig(String group, String serviceId) {<FILL_FUNCTION_BODY>}
public boolean removeConfig(String group, String serviceId) {
String token = getToken();
consulClient.deleteKVValue(group + "-" + serviceId, token);
return true;
}
public boolean publishConfig(String group, String serviceId, String config) {
String token = getToken();
consulClient.setKVValue(group + "-" + serviceId, config, token, null);
return true;
}
public ConsulListener subscribeConfig(String group, String serviceId, ExecutorService executorService, ConsulSubscribeCallback consulSubscribeCallback) throws Exception {
int timeout = getTimeout();
String token = getToken();
ConsulListener consulListener = new ConsulListener(group, serviceId, timeout, token, consulClient, consulSubscribeCallback);
executorService.submit(consulListener);
return consulListener;
}
public void unsubscribeConfig(String group, String serviceId, ConsulListener consulListener) throws Exception {
consulListener.stop();
}
private int getTimeout() {
return environment.getProperty(ConsulConstant.CONSUL_TIMEOUT, Integer.class, ConsulConstant.CONSUL_DEFAULT_TIMEOUT);
}
private String getToken() {
String token = environment.getProperty(ConsulConstant.CONSUL_TOKEN, String.class);
return StringUtils.isNotBlank(token) ? token : null;
}
} |
String token = getToken();
Response<GetValue> response = consulClient.getKVValue(group + "-" + serviceId, token);
if (response == null) {
return null;
}
GetValue getValue = response.getValue();
if (getValue == null) {
return null;
}
return getValue.getDecodedValue(StandardCharsets.UTF_8);
| 118 | 435 | 106 | 541 |
441 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-consul/src/main/java/com/nepxion/discovery/common/consul/proccessor/ConsulProcessor.java | ConsulProcessor | initialize | class ConsulProcessor extends DiscoveryConfigProcessor {
private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("consul-config");
@Autowired
private ConsulOperation consulOperation;
private ConsulListener consulListener;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (consulListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
consulOperation.unsubscribeConfig(group, dataId, consulListener);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
executorService.shutdownNow();
}
@Override
public ConfigType getConfigType() {
return ConfigType.CONSUL;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
consulListener = consulOperation.subscribeConfig(group, dataId, executorService, new ConsulSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = consulOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 427 | 236 | 231 | 467 |
442 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/configuration/EtcdAutoConfiguration.java | EtcdAutoConfiguration | client | class EtcdAutoConfiguration {
@Autowired
private Environment environment;
@Bean
public EtcdOperation etcdOperation() {
return new EtcdOperation();
}
@Bean
@ConditionalOnMissingBean
public Client client() {<FILL_FUNCTION_BODY>}
} |
String serverAddr = environment.getProperty(EtcdConstant.ETCD_SERVER_ADDR);
if (StringUtils.isBlank(serverAddr)) {
throw new DiscoveryException(EtcdConstant.ETCD_SERVER_ADDR + " can't be null or empty");
}
ClientBuilder clientBuilder = Client.builder().endpoints(serverAddr);
String username = environment.getProperty(EtcdConstant.ETCD_USERNAME);
if (StringUtils.isNotBlank(username)) {
clientBuilder.user(ByteSequence.from(username, StandardCharsets.UTF_8));
}
String password = environment.getProperty(EtcdConstant.ETCD_PASSWORD);
if (StringUtils.isNotBlank(password)) {
clientBuilder.password(ByteSequence.from(password, StandardCharsets.UTF_8));
}
clientBuilder.loadBalancerPolicy(EtcdConstant.ETCD_CLIENT_ROUND_ROBIN);
return clientBuilder.build();
| 167 | 80 | 249 | 329 |
443 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/operation/EtcdOperation.java | EtcdOperation | subscribeConfig | class EtcdOperation implements DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(EtcdOperation.class);
@Autowired
private Client client;
public String getConfig(String group, String serviceId) throws ExecutionException, InterruptedException {
ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8);
KV kvClient = client.getKVClient();
GetResponse getResponse = kvClient.get(byteSequence).get();
if (getResponse.getKvs().size() > 0) {
KeyValue keyValue = getResponse.getKvs().get(0);
return keyValue.getValue().toString(StandardCharsets.UTF_8);
}
return null;
}
public boolean removeConfig(String group, String serviceId) throws ExecutionException, InterruptedException {
ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8);
KV kvClient = client.getKVClient();
kvClient.delete(byteSequence);
return true;
}
public boolean publishConfig(String group, String serviceId, String config) throws ExecutionException, InterruptedException {
ByteSequence keyByteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8);
ByteSequence valueByteSequence = ByteSequence.from(config, StandardCharsets.UTF_8);
KV kvClient = client.getKVClient();
kvClient.put(keyByteSequence, valueByteSequence);
return true;
}
public Watch subscribeConfig(String group, String serviceId, EtcdSubscribeCallback etcdSubscribeCallback) throws Exception {<FILL_FUNCTION_BODY>}
public void unsubscribeConfig(String group, String serviceId, Watch watchClient) {
watchClient.close();
}
@Override
public void destroy() throws Exception {
client.close();
LOG.info("Shutting down JEtcd client...");
}
} |
ByteSequence byteSequence = ByteSequence.from(group + "-" + serviceId, StandardCharsets.UTF_8);
Watch watchClient = client.getWatchClient();
Listener listener = new Listener() {
@Override
public void onNext(WatchResponse response) {
for (WatchEvent event : response.getEvents()) {
EventType eventType = event.getEventType();
if (eventType == EventType.PUT) {
KeyValue keyValue = event.getKeyValue();
if (keyValue != null) {
String config = keyValue.getValue().toString(StandardCharsets.UTF_8);
etcdSubscribeCallback.callback(config);
}
} else if (eventType == EventType.DELETE) {
etcdSubscribeCallback.callback(null);
}
}
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
};
watchClient.watch(byteSequence, listener);
return watchClient;
| 482 | 520 | 270 | 790 |
444 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-etcd/src/main/java/com/nepxion/discovery/common/etcd/proccessor/EtcdProcessor.java | EtcdProcessor | initialize | class EtcdProcessor extends DiscoveryConfigProcessor {
@Autowired
private EtcdOperation etcdOperation;
private Watch watchClient;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (watchClient == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
etcdOperation.unsubscribeConfig(group, dataId, watchClient);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.ETCD;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
watchClient = etcdOperation.subscribeConfig(group, dataId, new EtcdSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = etcdOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 426 | 193 | 226 | 419 |
445 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/configuration/NacosAutoConfiguration.java | NacosAutoConfiguration | createNacosProperties | class NacosAutoConfiguration {
@Autowired
private Environment environment;
@Bean
@ConditionalOnMissingBean
public ConfigService nacosConfigService() throws NacosException {
Properties properties = createNacosProperties(environment, true);
return NacosFactory.createConfigService(properties);
}
@Bean
public NacosOperation nacosOperation() {
return new NacosOperation();
}
public static Properties createNacosProperties(Environment environment, boolean enableRemoteSyncConfig) {<FILL_FUNCTION_BODY>}
} |
Properties properties = new Properties();
// 支持从spring.cloud.nacos.config前缀方式获取
PropertiesUtil.enrichProperties(properties, environment, NacosConstant.SPRING_CLOUD_NACOS_CONFIG_PREFIX, true, true);
// 支持从nacos前缀方式获取
PropertiesUtil.enrichProperties(properties, environment, NacosConstant.NACOS_PREFIX, true, true);
properties.put(NacosConstant.ENABLE_REMOTE_SYNC_CONFIG, Boolean.toString(enableRemoteSyncConfig));
return properties;
| 77 | 149 | 154 | 303 |
446 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/operation/NacosOperation.java | NacosOperation | subscribeConfig | class NacosOperation implements DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(NacosOperation.class);
@Autowired
private ConfigService nacosConfigService;
@Autowired
private Environment environment;
public String getConfig(String group, String serviceId) throws NacosException {
String timeout = environment.getProperty(NacosConstant.NACOS_TIMEOUT);
if (StringUtils.isEmpty(timeout)) {
timeout = environment.getProperty(NacosConstant.SPRING_CLOUD_NACOS_CONFIG_TIMEOUT);
}
return nacosConfigService.getConfig(serviceId, group, StringUtils.isNotEmpty(timeout) ? Long.valueOf(timeout) : NacosConstant.NACOS_DEFAULT_TIMEOUT);
}
public boolean removeConfig(String group, String serviceId) throws NacosException {
return nacosConfigService.removeConfig(serviceId, group);
}
public boolean publishConfig(String group, String serviceId, String config) throws NacosException {
return nacosConfigService.publishConfig(serviceId, group, config);
}
public boolean publishConfig(String group, String serviceId, String config, FormatType formatType) throws NacosException {
return nacosConfigService.publishConfig(serviceId, group, config, formatType.toString());
}
public Listener subscribeConfig(String group, String serviceId, Executor executor, NacosSubscribeCallback nacosSubscribeCallback) throws NacosException {<FILL_FUNCTION_BODY>}
public void unsubscribeConfig(String group, String serviceId, Listener listener) {
nacosConfigService.removeListener(serviceId, group, listener);
}
@Override
public void destroy() throws Exception {
nacosConfigService.shutDown();
LOG.info("Shutting down Nacos config service...");
}
} |
Listener listener = new Listener() {
@Override
public void receiveConfigInfo(String config) {
nacosSubscribeCallback.callback(config);
}
@Override
public Executor getExecutor() {
return executor;
}
};
nacosConfigService.addListener(serviceId, group, listener);
return listener;
| 157 | 496 | 97 | 593 |
447 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-nacos/src/main/java/com/nepxion/discovery/common/nacos/proccessor/NacosProcessor.java | NacosProcessor | initialize | class NacosProcessor extends DiscoveryConfigProcessor {
private ExecutorService executorService = DiscoveryThreadPoolFactory.getExecutorService("nacos-config");
@Autowired
private NacosOperation nacosOperation;
private Listener listener;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (listener == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
nacosOperation.unsubscribeConfig(group, dataId, listener);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
executorService.shutdownNow();
}
@Override
public ConfigType getConfigType() {
return ConfigType.NACOS;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
listener = nacosOperation.subscribeConfig(group, dataId, executorService, new NacosSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = nacosOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 427 | 235 | 232 | 467 |
448 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/operation/RedisOperation.java | RedisOperation | subscribeConfig | class RedisOperation implements DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(RedisOperation.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private HashOperations<String, String, String> hashOperations;
@Autowired
private RedisMessageListenerContainer configMessageListenerContainer;
public String getConfig(String group, String serviceId) {
return hashOperations.get(group, serviceId);
}
public boolean removeConfig(String group, String serviceId) {
publishConfig(group, serviceId, StringUtils.EMPTY);
return hashOperations.delete(group, serviceId) == 1;
}
public boolean publishConfig(String group, String serviceId, String config) {
hashOperations.put(group, serviceId, config);
stringRedisTemplate.convertAndSend(group + "-" + serviceId, config);
return true;
}
public MessageListenerAdapter subscribeConfig(String group, String serviceId, Object delegate, String listenerMethod) {<FILL_FUNCTION_BODY>}
public void unsubscribeConfig(String group, String serviceId, MessageListenerAdapter messageListenerAdapter) {
configMessageListenerContainer.removeMessageListener(messageListenerAdapter, new PatternTopic(group + "-" + serviceId));
}
public void subscribeConfig(String config, RedisSubscribeCallback redisSubscribeCallback) {
redisSubscribeCallback.callback(config);
}
@Override
public void destroy() throws Exception {
configMessageListenerContainer.destroy();
LOG.info("Shutting down Redis message listener...");
}
} |
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(delegate, listenerMethod);
messageListenerAdapter.afterPropertiesSet();
configMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic(group + "-" + serviceId));
return messageListenerAdapter;
| 49 | 423 | 72 | 495 |
449 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-redis/src/main/java/com/nepxion/discovery/common/redis/proccessor/RedisProcessor.java | RedisProcessor | initialize | class RedisProcessor extends DiscoveryConfigProcessor {
@Autowired
private RedisOperation redisOperation;
private MessageListenerAdapter messageListenerAdapter;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
public void subscribeConfig(String config) {
redisOperation.subscribeConfig(config, new RedisSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
}
@Override
public void destroy() {
if (messageListenerAdapter == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
redisOperation.unsubscribeConfig(group, dataId, messageListenerAdapter);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.REDIS;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
messageListenerAdapter = redisOperation.subscribeConfig(group, dataId, this, "subscribeConfig");
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = redisOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 248 | 283 | 174 | 457 |
450 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/configuration/ZookeeperAutoConfiguration.java | ZookeeperAutoConfiguration | curatorFramework | class ZookeeperAutoConfiguration {
@Autowired
private Environment environment;
@Bean
public ZookeeperOperation zookeeperOperation() {
return new ZookeeperOperation();
}
@Bean
@ConditionalOnMissingBean
public CuratorFramework curatorFramework() {<FILL_FUNCTION_BODY>}
} |
String connectString = environment.getProperty(ZookeeperConstant.ZOOKEEPER_CONNECT_STRING);
if (StringUtils.isEmpty(connectString)) {
throw new DiscoveryException(ZookeeperConstant.ZOOKEEPER_CONNECT_STRING + " can't be null or empty");
}
int retryCount = environment.getProperty(ZookeeperConstant.ZOOKEEPER_RETRY_COUNT, Integer.class, ZookeeperConstant.ZOOKEEPER_DEFAULT_RETRY_COUNT_VALUE);
int sleepTime = environment.getProperty(ZookeeperConstant.ZOOKEEPER_SLEEP_TIME, Integer.class, ZookeeperConstant.ZOOKEEPER_DEFAULT_SLEEP_TIME_VALUE);
CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(connectString).retryPolicy(new ExponentialBackoffRetry(sleepTime, retryCount)).build();
curatorFramework.start();
return curatorFramework;
| 111 | 92 | 253 | 345 |
451 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/operation/ZookeeperOperation.java | ZookeeperOperation | subscribeConfig | class ZookeeperOperation implements DisposableBean {
private static final Logger LOG = LoggerFactory.getLogger(ZookeeperOperation.class);
@Autowired
private CuratorFramework curatorFramework;
public String getConfig(String group, String serviceId) throws Exception {
String path = getPath(group, serviceId);
boolean hasPath = hasPath(path);
if (!hasPath) {
return null;
}
return convertConfig(path);
}
public boolean removeConfig(String group, String serviceId) throws Exception {
String path = getPath(group, serviceId);
boolean hasPath = hasPath(path);
if (!hasPath) {
return false;
}
curatorFramework.delete().forPath(path);
return true;
}
public boolean publishConfig(String group, String serviceId, String config) throws Exception {
byte[] bytes = config.getBytes();
if (bytes == null) {
return false;
}
String path = getPath(group, serviceId);
Stat stat = curatorFramework.checkExists().forPath(path);
if (stat == null) {
curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, bytes);
} else {
curatorFramework.setData().forPath(path, bytes);
}
return true;
}
public ZookeeperListener subscribeConfig(String group, String serviceId, ZookeeperSubscribeCallback zookeeperSubscribeCallback) throws Exception {<FILL_FUNCTION_BODY>}
public void unsubscribeConfig(String group, String serviceId, ZookeeperListener zookeeperListener) throws Exception {
zookeeperListener.removeListener();
}
public String getPath(String group, String serviceId) {
return String.format("/%s/%s", group, serviceId);
}
public boolean hasPath(String path) throws Exception {
return curatorFramework.checkExists().forPath(path) != null;
}
public boolean hasPath(String group, String serviceId) throws Exception {
String path = getPath(group, serviceId);
return hasPath(path);
}
public String convertConfig(String path) throws Exception {
return convertConfig(curatorFramework, path);
}
public String convertConfig(CuratorFramework curatorFramework, String path) throws Exception {
byte[] bytes = curatorFramework.getData().forPath(path);
if (bytes == null) {
return null;
}
return new String(bytes);
}
public String convertConfig(NodeCache nodeCache) throws Exception {
ChildData childData = nodeCache.getCurrentData();
if (childData == null) {
return null;
}
byte[] bytes = childData.getData();
if (bytes == null) {
return null;
}
return new String(bytes);
}
@Override
public void destroy() throws Exception {
curatorFramework.close();
LOG.info("Shutting down Zookeeper CuratorFramework...");
}
} |
String path = getPath(group, serviceId);
NodeCache nodeCache = new NodeCache(curatorFramework, path);
nodeCache.start(true);
NodeCacheListener nodeCacheListener = new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
String config = convertConfig(nodeCache);
zookeeperSubscribeCallback.callback(config);
}
};
ZookeeperListener zookeeperListener = new ZookeeperListener(nodeCache, nodeCacheListener);
zookeeperListener.addListener();
return zookeeperListener;
| 165 | 808 | 154 | 962 |
452 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common-zookeeper/src/main/java/com/nepxion/discovery/common/zookeeper/proccessor/ZookeeperProcessor.java | ZookeeperProcessor | initialize | class ZookeeperProcessor extends DiscoveryConfigProcessor {
@Autowired
private ZookeeperOperation zookeeperOperation;
private ZookeeperListener zookeeperListener;
@PostConstruct
public void initialize() {<FILL_FUNCTION_BODY>}
@Override
public void destroy() {
if (zookeeperListener == null) {
return;
}
String group = getGroup();
String dataId = getDataId();
logUnsubscribeStarted();
try {
zookeeperOperation.unsubscribeConfig(group, dataId, zookeeperListener);
} catch (Exception e) {
logUnsubscribeFailed(e);
}
}
@Override
public ConfigType getConfigType() {
return ConfigType.ZOOKEEPER;
}
} |
beforeInitialization();
String group = getGroup();
String dataId = getDataId();
logSubscribeStarted();
try {
zookeeperListener = zookeeperOperation.subscribeConfig(group, dataId, new ZookeeperSubscribeCallback() {
@Override
public void callback(String config) {
try {
callbackConfig(config);
} catch (Exception e) {
logCallbackFailed(e);
}
}
});
} catch (Exception e) {
logSubscribeFailed(e);
}
logGetStarted();
try {
String config = zookeeperOperation.getConfig(group, dataId);
if (config != null) {
callbackConfig(config);
} else {
logNotFound();
}
} catch (Exception e) {
logGetFailed(e);
}
afterInitialization();
| 426 | 216 | 235 | 451 |
453 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JParser.java | Dom4JParser | parse | class Dom4JParser {
public void parse(String text) throws DocumentException {
if (StringUtils.isEmpty(text)) {
throw new IllegalArgumentException("The text is empty");
}
Document document = Dom4JReader.getDocument(text);
parse(document);
}
public void parseFormat(String text) throws DocumentException, UnsupportedEncodingException {
if (StringUtils.isEmpty(text)) {
throw new IllegalArgumentException("The text is empty");
}
Document document = Dom4JReader.getFormatDocument(text);
parse(document);
}
public void parse(File file) throws DocumentException, IOException, UnsupportedEncodingException {
if (file == null) {
throw new IllegalArgumentException("The file is null");
}
Document document = Dom4JReader.getDocument(file);
parse(document);
}
public void parseFormat(File file) throws DocumentException, IOException, UnsupportedEncodingException {
if (file == null) {
throw new IllegalArgumentException("The file is null");
}
Document document = Dom4JReader.getFormatDocument(file);
parse(document);
}
public void parse(InputStream inputStream) throws DocumentException, IOException {<FILL_FUNCTION_BODY>}
public void parseFormat(InputStream inputStream) throws DocumentException, IOException, UnsupportedEncodingException {
if (inputStream == null) {
throw new IllegalArgumentException("The input stream is null");
}
Document document = Dom4JReader.getFormatDocument(inputStream);
parse(document);
}
public void parse(Document document) {
Element rootElement = document.getRootElement();
parseRoot(rootElement);
}
protected abstract void parseRoot(Element element);
} |
if (inputStream == null) {
throw new IllegalArgumentException("The input stream is null");
}
Document document = Dom4JReader.getDocument(inputStream);
parse(document);
| 62 | 446 | 53 | 499 |
454 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JReader.java | Dom4JReader | getDocument | class Dom4JReader {
public static Document getDocument(String text) throws DocumentException {
return DocumentHelper.parseText(text);
}
public static Document getFormatDocument(String text) throws DocumentException, UnsupportedEncodingException {
return getFormatDocument(text, Dom4JConstant.ENCODING_UTF_8);
}
public static Document getFormatDocument(String text, String charset) throws DocumentException, UnsupportedEncodingException {
String formatText = new String(text.getBytes(Dom4JConstant.ENCODING_ISO_8859_1), Dom4JConstant.ENCODING_UTF_8);
return getDocument(formatText);
}
public static Document getDocument(File file) throws DocumentException, IOException {
InputStream inputStream = new FileInputStream(file);
return getDocument(inputStream);
}
public static Document getFormatDocument(File file) throws DocumentException, IOException, UnsupportedEncodingException {
return getFormatDocument(file, Dom4JConstant.ENCODING_UTF_8);
}
public static Document getFormatDocument(File file, String charset) throws DocumentException, IOException, UnsupportedEncodingException {
InputStream inputStream = new FileInputStream(file);
return getFormatDocument(inputStream, charset);
}
public static Document getDocument(InputSource inputSource) throws DocumentException {
SAXReader saxReader = new SAXReader();
return saxReader.read(inputSource);
}
public static Document getFormatDocument(InputSource inputSource) throws DocumentException {
return getFormatDocument(inputSource, Dom4JConstant.ENCODING_UTF_8);
}
public static Document getFormatDocument(InputSource inputSource, String charset) throws DocumentException {
inputSource.setEncoding(charset);
return getDocument(inputSource);
}
public static Document getDocument(InputStream inputStream) throws DocumentException, IOException {<FILL_FUNCTION_BODY>}
public static Document getFormatDocument(InputStream inputStream) throws DocumentException, IOException, UnsupportedEncodingException {
return getFormatDocument(inputStream, Dom4JConstant.ENCODING_UTF_8);
}
public static Document getFormatDocument(InputStream inputStream, String charset) throws DocumentException, IOException, UnsupportedEncodingException {
Reader inputStreamReader = new InputStreamReader(inputStream, charset);
return getDocument(inputStreamReader);
}
public static Document getDocument(Reader reader) throws DocumentException, IOException {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(reader);
} catch (DocumentException e) {
throw e;
} finally {
if (reader != null) {
reader.close();
}
}
return document;
}
public static Document getDocument(URL url) throws DocumentException {
SAXReader saxReader = new SAXReader();
return saxReader.read(url);
}
} |
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(inputStream);
} catch (DocumentException e) {
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return document;
| 147 | 755 | 92 | 847 |
455 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/dom4j/Dom4JWriter.java | Dom4JWriter | getText | class Dom4JWriter {
public static Document createDocument() {
return DocumentHelper.createDocument();
}
public static String getText(Document document) throws IOException, UnsupportedEncodingException {
return getText(document, Dom4JConstant.ENCODING_UTF_8);
}
public static String getText(Document document, String charset) throws IOException, UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
} |
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputFormat outputFormat = new OutputFormat(" ", true, charset);
try {
XMLWriter writer = new XMLWriter(baos, outputFormat);
writer.write(document);
baos.flush();
} catch (UnsupportedEncodingException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
if (baos != null) {
baos.close();
}
}
return baos.toString(charset);
| 204 | 110 | 142 | 252 |
456 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/GatewayStrategyRouteEntity.java | Clause | toClausesJson | class Clause implements Serializable {
private static final long serialVersionUID = -6284675851623689077L;
private String name;
private Map<String, String> args = new LinkedHashMap<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getArgs() {
return args;
}
public void setArgs(Map<String, String> args) {
this.args = args;
}
public void addArg(String key, String value) {
this.args.put(key, value);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
public static <T extends Clause> String toClausesJson(List<T> clauses) {<FILL_FUNCTION_BODY> |
StringBuilder stringBuilder = new StringBuilder();
for (Clause clause : clauses) {
stringBuilder.append(String.format("%s=%s, ", clause.getName(), JsonUtil.toJson(clause.getArgs())));
}
if (stringBuilder.length() > 0) {
stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length());
}
return stringBuilder.toString();
| 97 | 328 | 110 | 438 |
457 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/InstanceEntityWrapper.java | InstanceEntityWrapper | getGroup | class InstanceEntityWrapper {
public static String getPlugin(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getPlugin(metadata);
}
public static String getGroup(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getGroup(metadata);
}
public static String getServiceType(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getServiceType(metadata);
}
public static String getGatewayType(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getGatewayType(metadata);
}
public static String getServiceAppId(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getServiceAppId(metadata);
}
public static String getServiceUUId(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getServiceUUId(metadata);
}
public static String getVersion(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getVersion(metadata);
}
public static String getRegion(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getRegion(metadata);
}
public static String getEnvironment(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getEnvironment(metadata);
}
public static String getZone(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getZone(metadata);
}
public static boolean isActive(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return isActive(metadata);
}
public static String getProtocol(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getProtocol(metadata);
}
public static String getContextPath(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getContextPath(metadata);
}
public static String getFormatContextPath(InstanceEntity instanceEntity) {
Map<String, String> metadata = instanceEntity.getMetadata();
return getFormatContextPath(metadata);
}
public static String getPlugin(Map<String, String> metadata) {
String plugin = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN);
if (StringUtils.isEmpty(plugin)) {
return StringUtils.EMPTY;
}
return plugin;
}
public static String getGroup(Map<String, String> metadata) {<FILL_FUNCTION_BODY>}
public static String getServiceType(Map<String, String> metadata) {
return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE);
}
public static String getGatewayType(Map<String, String> metadata) {
return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE);
}
public static String getServiceAppId(Map<String, String> metadata) {
return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID);
}
public static String getServiceUUId(Map<String, String> metadata) {
return metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID);
}
public static String getVersion(Map<String, String> metadata) {
String version = metadata.get(DiscoveryConstant.VERSION);
if (StringUtils.isEmpty(version)) {
version = DiscoveryConstant.DEFAULT;
}
return version;
}
public static String getRegion(Map<String, String> metadata) {
String region = metadata.get(DiscoveryConstant.REGION);
if (StringUtils.isEmpty(region)) {
region = DiscoveryConstant.DEFAULT;
}
return region;
}
public static String getEnvironment(Map<String, String> metadata) {
String environment = metadata.get(DiscoveryConstant.ENVIRONMENT);
if (StringUtils.isEmpty(environment)) {
environment = DiscoveryConstant.DEFAULT;
}
return environment;
}
public static String getZone(Map<String, String> metadata) {
String zone = metadata.get(DiscoveryConstant.ZONE);
if (StringUtils.isEmpty(zone)) {
zone = DiscoveryConstant.DEFAULT;
}
return zone;
}
public static boolean isActive(Map<String, String> metadata) {
String active = metadata.get(DiscoveryConstant.ACTIVE);
if (StringUtils.isEmpty(active)) {
return false;
}
return Boolean.valueOf(active);
}
public static String getProtocol(Map<String, String> metadata) {
String protocol = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL);
if (StringUtils.isEmpty(protocol)) {
return "http";
}
return protocol;
}
public static String getContextPath(Map<String, String> metadata) {
String contextPath = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH);
if (StringUtils.isEmpty(contextPath)) {
return "/";
}
return contextPath;
}
public static String getFormatContextPath(Map<String, String> metadata) {
String contextPath = getContextPath(metadata);
return UrlUtil.formatContextPath(contextPath);
}
} |
String groupKey = metadata.get(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY);
if (StringUtils.isEmpty(groupKey)) {
groupKey = DiscoveryConstant.GROUP;
}
String group = metadata.get(groupKey);
if (StringUtils.isEmpty(group)) {
return StringUtils.EMPTY;
}
return group;
| 99 | 1,485 | 102 | 1,587 |
458 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/RuleEntityWrapper.java | RuleEntityWrapper | assemble | class RuleEntityWrapper {
// 以局部规则为准,如果局部规则规则里某些属性没有,而全局规则有,则从全局规则把那些属性复制到局部规则,并合并创建最终的复合规则
public static RuleEntity assemble(RuleEntity partialRuleEntity, RuleEntity globalRuleEntity) {<FILL_FUNCTION_BODY>}
} |
RuleEntity ruleEntity = new RuleEntity();
RegisterEntity registerEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getRegisterEntity() != null) {
registerEntity = partialRuleEntity.getRegisterEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getRegisterEntity() != null) {
registerEntity = globalRuleEntity.getRegisterEntity();
}
ruleEntity.setRegisterEntity(registerEntity);
DiscoveryEntity discoveryEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getDiscoveryEntity() != null) {
discoveryEntity = partialRuleEntity.getDiscoveryEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getDiscoveryEntity() != null) {
discoveryEntity = globalRuleEntity.getDiscoveryEntity();
}
ruleEntity.setDiscoveryEntity(discoveryEntity);
StrategyEntity strategyEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getStrategyEntity() != null) {
strategyEntity = partialRuleEntity.getStrategyEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getStrategyEntity() != null) {
strategyEntity = globalRuleEntity.getStrategyEntity();
}
ruleEntity.setStrategyEntity(strategyEntity);
StrategyReleaseEntity strategyReleaseEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getStrategyReleaseEntity() != null) {
strategyReleaseEntity = partialRuleEntity.getStrategyReleaseEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getStrategyReleaseEntity() != null) {
strategyReleaseEntity = globalRuleEntity.getStrategyReleaseEntity();
}
ruleEntity.setStrategyReleaseEntity(strategyReleaseEntity);
StrategyFailoverEntity strategyFailoverEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getStrategyFailoverEntity() != null) {
strategyFailoverEntity = partialRuleEntity.getStrategyFailoverEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getStrategyFailoverEntity() != null) {
strategyFailoverEntity = globalRuleEntity.getStrategyFailoverEntity();
}
ruleEntity.setStrategyFailoverEntity(strategyFailoverEntity);
StrategyBlacklistEntity strategyBlacklistEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getStrategyBlacklistEntity() != null) {
strategyBlacklistEntity = partialRuleEntity.getStrategyBlacklistEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getStrategyBlacklistEntity() != null) {
strategyBlacklistEntity = globalRuleEntity.getStrategyBlacklistEntity();
}
ruleEntity.setStrategyBlacklistEntity(strategyBlacklistEntity);
ParameterEntity parameterEntity = null;
if (partialRuleEntity != null && partialRuleEntity.getParameterEntity() != null) {
parameterEntity = partialRuleEntity.getParameterEntity();
} else if (globalRuleEntity != null && globalRuleEntity.getParameterEntity() != null) {
parameterEntity = globalRuleEntity.getParameterEntity();
}
ruleEntity.setParameterEntity(parameterEntity);
String content = null;
if (partialRuleEntity != null && partialRuleEntity.getContent() != null) {
content = partialRuleEntity.getContent();
} else if (globalRuleEntity != null && globalRuleEntity.getContent() != null) {
content = globalRuleEntity.getContent();
}
ruleEntity.setContent(content);
return ruleEntity;
| 738 | 95 | 885 | 980 |
459 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/StrategyReleaseEntity.java | StrategyReleaseEntity | setStrategyRouteEntityList | class StrategyReleaseEntity implements Serializable {
private static final long serialVersionUID = 4903833660194433964L;
private List<StrategyConditionBlueGreenEntity> strategyConditionBlueGreenEntityList;
private List<StrategyConditionGrayEntity> strategyConditionGrayEntityList;
private List<StrategyRouteEntity> strategyRouteEntityList;
private StrategyHeaderEntity strategyHeaderEntity;
public List<StrategyConditionBlueGreenEntity> getStrategyConditionBlueGreenEntityList() {
return strategyConditionBlueGreenEntityList;
}
public void setStrategyConditionBlueGreenEntityList(List<StrategyConditionBlueGreenEntity> strategyConditionBlueGreenEntityList) {
this.strategyConditionBlueGreenEntityList = strategyConditionBlueGreenEntityList;
}
public List<StrategyConditionGrayEntity> getStrategyConditionGrayEntityList() {
return strategyConditionGrayEntityList;
}
public void setStrategyConditionGrayEntityList(List<StrategyConditionGrayEntity> strategyConditionGrayEntityList) {
this.strategyConditionGrayEntityList = strategyConditionGrayEntityList;
}
public List<StrategyRouteEntity> getStrategyRouteEntityList() {
return strategyRouteEntityList;
}
public void setStrategyRouteEntityList(List<StrategyRouteEntity> strategyRouteEntityList) {<FILL_FUNCTION_BODY>}
public StrategyHeaderEntity getStrategyHeaderEntity() {
return strategyHeaderEntity;
}
public void setStrategyHeaderEntity(StrategyHeaderEntity strategyHeaderEntity) {
this.strategyHeaderEntity = strategyHeaderEntity;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
} |
this.strategyRouteEntityList = strategyRouteEntityList;
// Header参数越多,越排在前面
if (CollectionUtils.isNotEmpty(strategyConditionBlueGreenEntityList)) {
Collections.sort(strategyConditionBlueGreenEntityList, new Comparator<StrategyConditionBlueGreenEntity>() {
public int compare(StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity1, StrategyConditionBlueGreenEntity strategyConditionBlueGreenEntity2) {
Integer count1 = StringUtil.count(strategyConditionBlueGreenEntity1.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX);
Integer count2 = StringUtil.count(strategyConditionBlueGreenEntity2.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX);
return count2.compareTo(count1);
}
});
}
// Header参数越多,越排在前面
if (CollectionUtils.isNotEmpty(strategyConditionGrayEntityList)) {
Collections.sort(strategyConditionGrayEntityList, new Comparator<StrategyConditionGrayEntity>() {
public int compare(StrategyConditionGrayEntity strategyConditionGrayEntity1, StrategyConditionGrayEntity strategyConditionGrayEntity2) {
Integer count1 = StringUtil.count(strategyConditionGrayEntity1.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX);
Integer count2 = StringUtil.count(strategyConditionGrayEntity2.getExpression(), DiscoveryConstant.EXPRESSION_SUB_PREFIX);
return count2.compareTo(count1);
}
});
}
| 337 | 502 | 390 | 892 |
460 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightEntityWrapper.java | WeightEntityWrapper | getWeight | class WeightEntityWrapper {
@SuppressWarnings("unchecked")
public static List<WeightEntity> parseWeightEntityList(String weightValue) {
List<WeightEntity> weightEntityList = new ArrayList<WeightEntity>();
Map<String, String> jsonWeightMap = JsonUtil.fromJson(weightValue, Map.class);
for (Map.Entry<String, String> entry : jsonWeightMap.entrySet()) {
String providerServiceName = entry.getKey();
String providerWeightValue = entry.getValue();
WeightEntity weightEntity = new WeightEntity();
weightEntity.setProviderServiceName(providerServiceName);
parseWeightEntity(weightEntity, providerWeightValue);
weightEntityList.add(weightEntity);
}
return weightEntityList;
}
public static void parseWeightEntity(MapWeightEntity weightEntity, String weightValue) {
Map<String, Integer> weightMap = weightEntity.getWeightMap();
List<String> providerWeightValueList = StringUtil.splitToList(weightValue);
if (CollectionUtils.isNotEmpty(providerWeightValueList)) {
for (String value : providerWeightValueList) {
String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS);
String key = valueArray[0].trim();
int weight = 0;
try {
weight = Integer.valueOf(valueArray[1].trim());
if (weight < 0) {
weight = 0;
}
} catch (Exception e) {
}
weightMap.put(key, weight);
}
}
}
public static int getWeight(String consumerServiceId, String providerServiceId, String providerKey, Map<String, List<WeightEntity>> weightEntityMap) {
if (MapUtils.isEmpty(weightEntityMap)) {
return -1;
}
List<WeightEntity> weightEntityList = weightEntityMap.get(consumerServiceId);
return getWeight(providerServiceId, providerKey, weightEntityList);
}
public static int getWeight(String providerServiceId, String providerKey, List<WeightEntity> weightEntityList) {
if (CollectionUtils.isEmpty(weightEntityList)) {
return -1;
}
for (WeightEntity weightEntity : weightEntityList) {
String providerServiceName = weightEntity.getProviderServiceName();
if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) {
return getWeight(providerKey, weightEntity);
}
}
return -1;
}
public static int getWeight(String providerKey, MapWeightEntity weightEntity) {
if (weightEntity == null) {
return -1;
}
Map<String, Integer> weightMap = weightEntity.getWeightMap();
if (MapUtils.isEmpty(weightMap)) {
return -1;
}
Integer weight = weightMap.get(providerKey);
if (weight != null) {
return weight;
} else {
return -1;
}
}
public static int getWeight(WeightFilterEntity weightFilterEntity, String providerServiceId, String providerVersion, String providerRegion, String serviceId) {<FILL_FUNCTION_BODY>}
} |
int weight = -1;
if (StringUtils.isNotEmpty(serviceId) && weight < 0) {
Map<String, List<WeightEntity>> versionWeightEntityMap = weightFilterEntity.getVersionWeightEntityMap();
weight = getWeight(serviceId, providerServiceId, providerVersion, versionWeightEntityMap);
}
if (weight < 0) {
List<WeightEntity> versionWeightEntityList = weightFilterEntity.getVersionWeightEntityList();
weight = getWeight(providerServiceId, providerVersion, versionWeightEntityList);
}
if (weight < 0) {
VersionWeightEntity versionWeightEntity = weightFilterEntity.getVersionWeightEntity();
weight = getWeight(providerVersion, versionWeightEntity);
}
if (StringUtils.isNotEmpty(serviceId) && weight < 0) {
Map<String, List<WeightEntity>> regionWeightEntityMap = weightFilterEntity.getRegionWeightEntityMap();
weight = getWeight(serviceId, providerServiceId, providerRegion, regionWeightEntityMap);
}
if (weight < 0) {
List<WeightEntity> regionWeightEntityList = weightFilterEntity.getRegionWeightEntityList();
weight = getWeight(providerServiceId, providerRegion, regionWeightEntityList);
}
if (weight < 0) {
RegionWeightEntity regionWeightEntity = weightFilterEntity.getRegionWeightEntity();
weight = getWeight(providerRegion, regionWeightEntity);
}
return weight;
| 337 | 803 | 354 | 1,157 |
461 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/entity/WeightFilterEntity.java | WeightFilterEntity | hasWeight | class WeightFilterEntity implements Serializable {
private static final long serialVersionUID = 7313443273653189837L;
// Consumer-service-name非空,作为Key,以Map方式存储
private Map<String, List<WeightEntity>> versionWeightEntityMap;
// Consumer-service-name为空,以List方式存储
private List<WeightEntity> versionWeightEntityList;
private VersionWeightEntity versionWeightEntity;
// Consumer-service-name非空,作为Key,以Map方式存储
private Map<String, List<WeightEntity>> regionWeightEntityMap;
// Consumer-service-name为空,以List方式存储
private List<WeightEntity> regionWeightEntityList;
private RegionWeightEntity regionWeightEntity;
public Map<String, List<WeightEntity>> getVersionWeightEntityMap() {
return versionWeightEntityMap;
}
public void setVersionWeightEntityMap(Map<String, List<WeightEntity>> versionWeightEntityMap) {
this.versionWeightEntityMap = versionWeightEntityMap;
}
public List<WeightEntity> getVersionWeightEntityList() {
return versionWeightEntityList;
}
public void setVersionWeightEntityList(List<WeightEntity> versionWeightEntityList) {
this.versionWeightEntityList = versionWeightEntityList;
}
public VersionWeightEntity getVersionWeightEntity() {
return versionWeightEntity;
}
public void setVersionWeightEntity(VersionWeightEntity versionWeightEntity) {
this.versionWeightEntity = versionWeightEntity;
}
public Map<String, List<WeightEntity>> getRegionWeightEntityMap() {
return regionWeightEntityMap;
}
public void setRegionWeightEntityMap(Map<String, List<WeightEntity>> regionWeightEntityMap) {
this.regionWeightEntityMap = regionWeightEntityMap;
}
public List<WeightEntity> getRegionWeightEntityList() {
return regionWeightEntityList;
}
public void setRegionWeightEntityList(List<WeightEntity> regionWeightEntityList) {
this.regionWeightEntityList = regionWeightEntityList;
}
public RegionWeightEntity getRegionWeightEntity() {
return regionWeightEntity;
}
public void setRegionWeightEntity(RegionWeightEntity regionWeightEntity) {
this.regionWeightEntity = regionWeightEntity;
}
public boolean hasWeight() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
} |
return MapUtils.isNotEmpty(versionWeightEntityMap) || CollectionUtils.isNotEmpty(versionWeightEntityList) || versionWeightEntity != null ||
MapUtils.isNotEmpty(regionWeightEntityMap) || CollectionUtils.isNotEmpty(regionWeightEntityList) || regionWeightEntity != null;
| 43 | 717 | 74 | 791 |
462 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryExpressionResolver.java | DiscoveryExpressionResolver | extractMap | class DiscoveryExpressionResolver {
public static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
public static boolean eval(String expression, String key, Map<String, String> map, TypeComparator typeComparator) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setTypeComparator(typeComparator);
if (map != null) {
context.setVariable(key, map);
} else {
context.setVariable(key, new HashMap<String, String>());
}
return eval(expression, context);
}
public static boolean eval(String expression, StandardEvaluationContext context) {
try {
Boolean result = EXPRESSION_PARSER.parseExpression(expression).getValue(context, Boolean.class);
return result != null ? result.booleanValue() : false;
} catch (Exception e) {
return false;
}
}
public static final Pattern EXPRESSION_PATTERN = Pattern.compile(DiscoveryConstant.EXPRESSION_REGEX);
public static List<String> extractList(String expression) {
List<String> list = new ArrayList<String>();
Matcher matcher = EXPRESSION_PATTERN.matcher(expression);
while (matcher.find()) {
String group = matcher.group();
String name = StringUtils.substringBetween(group, DiscoveryConstant.EXPRESSION_SUB_PREFIX, DiscoveryConstant.EXPRESSION_SUB_SUFFIX).trim();
list.add(name);
}
return list;
}
public static final Pattern EXPRESSION_SINGLE_QUOTES_PATTERN = Pattern.compile(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES_REGEX);
public static Map<String, String> extractMap(String expression) {<FILL_FUNCTION_BODY>}
} |
Map<String, String> map = new LinkedHashMap<String, String>();
Matcher matcher = EXPRESSION_SINGLE_QUOTES_PATTERN.matcher(expression);
int index = 0;
String key = null;
while (matcher.find()) {
String group = matcher.group();
if (group.startsWith(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES) && group.endsWith(DiscoveryConstant.EXPRESSION_SINGLE_QUOTES)) {
String name = StringUtils.substringBetween(group, DiscoveryConstant.EXPRESSION_SINGLE_QUOTES, DiscoveryConstant.EXPRESSION_SINGLE_QUOTES).trim();
if (index % 2 == 0) {
// 偶数个元素为Key
key = name;
} else if (index % 2 == 1) {
// 奇数个元素为Value
map.put(key, name);
}
index++;
}
}
return map;
| 306 | 484 | 267 | 751 |
463 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/expression/DiscoveryTypeComparator.java | DiscoveryTypeComparator | compare | class DiscoveryTypeComparator extends StandardTypeComparator {
@Override
public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException {<FILL_FUNCTION_BODY>}
} |
if (left == null) {
return right == null ? 0 : -1;
} else if (right == null) {
return 1;
}
try {
BigDecimal leftValue = new BigDecimal(left.toString());
BigDecimal rightValue = new BigDecimal(right.toString());
return super.compare(leftValue, rightValue);
} catch (Exception e) {
}
return super.compare(left, right);
| 156 | 55 | 123 | 178 |
464 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/future/DiscoveryFutureResolver.java | DiscoveryFutureResolver | call | class DiscoveryFutureResolver {
public static <T> T call(ExecutorService executorService, DiscoveryFutureCallback<T> discoveryFutureCallback) throws InterruptedException, ExecutionException {<FILL_FUNCTION_BODY>}
} |
Future<T> future = executorService.submit(new Callable<T>() {
@Override
public T call() throws Exception {
return discoveryFutureCallback.callback();
}
});
return future.get();
| 93 | 57 | 61 | 118 |
465 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/handler/DiscoveryResponseErrorHandler.java | DiscoveryResponseErrorHandler | handleError | class DiscoveryResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {<FILL_FUNCTION_BODY>}
public String getError() {
String error = DiscoveryResponseErrorContext.getCurrentContext().getError();
DiscoveryResponseErrorContext.clearCurrentContext();
return error;
}
} |
InputStream inputStream = response.getBody();
String error = IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8);
DiscoveryResponseErrorContext.getCurrentContext().setError(error);
| 36 | 95 | 59 | 154 |
466 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/json/DiscoveryPrettyPrinter.java | DiscoveryPrettyPrinter | createInstance | class DiscoveryPrettyPrinter extends DefaultPrettyPrinter {
private static final long serialVersionUID = 7557042630980590487L;
public DiscoveryPrettyPrinter() {
_arrayIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
_objectIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE;
}
public DiscoveryPrettyPrinter(DefaultPrettyPrinter base) {
super(base);
}
@Override
public DiscoveryPrettyPrinter createInstance() {<FILL_FUNCTION_BODY>}
@Override
public DiscoveryPrettyPrinter withSeparators(Separators separators) {
this._separators = separators;
this._objectFieldValueSeparatorWithSpaces = separators.getObjectFieldValueSeparator() + " ";
return this;
}
@Override
public void writeEndArray(JsonGenerator g, int nrOfValues) throws IOException {
if (!_arrayIndenter.isInline()) {
--_nesting;
}
if (nrOfValues > 0) {
_arrayIndenter.writeIndentation(g, _nesting);
}
g.writeRaw(']');
}
@Override
public void writeEndObject(JsonGenerator g, int nrOfEntries) throws IOException {
if (!_objectIndenter.isInline()) {
--_nesting;
}
if (nrOfEntries > 0) {
_objectIndenter.writeIndentation(g, _nesting);
}
g.writeRaw('}');
}
} |
if (getClass() != DiscoveryPrettyPrinter.class) {
throw new IllegalStateException("Failed `createInstance()`: " + getClass().getName()
+ " does not override method; it has to");
}
return new DiscoveryPrettyPrinter(this);
| 81 | 423 | 73 | 496 |
467 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/logback/LevelColorConverter.java | LevelColorConverter | getForegroundColorCode | class LevelColorConverter extends ForegroundCompositeConverterBase<ILoggingEvent> {
@Override
protected String getForegroundColorCode(ILoggingEvent event) {<FILL_FUNCTION_BODY>}
} |
Level level = event.getLevel();
switch (level.toInt()) {
// ERROR等级为红色
case Level.ERROR_INT:
return LogbackConstant.RED_FG;
// WARN等级为黄色
case Level.WARN_INT:
return LogbackConstant.YELLOW_FG;
// INFO等级为蓝色
case Level.INFO_INT:
return LogbackConstant.GREEN_FG;
// DEBUG等级为绿色
case Level.DEBUG_INT:
return LogbackConstant.BLUE_FG;
// 其他为默认颜色
default:
return LogbackConstant.DEFAULT_FG;
}
| 248 | 54 | 178 | 232 |
468 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessor.java | DiscoveryConfigProcessor | logGetFailed | class DiscoveryConfigProcessor implements DisposableBean {
public void logGetStarted() {
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logGetStarted(group, dataId, description, configType, isConfigSingleKey);
}
public void logGetFailed(Exception e) {<FILL_FUNCTION_BODY>}
public void logNotFound() {
String description = getDescription();
ConfigType configType = getConfigType();
DiscoveryConfigProcessorLogger.logNotFound(description, configType);
}
public void logSubscribeStarted() {
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logSubscribeStarted(group, dataId, description, configType, isConfigSingleKey);
}
public void logSubscribeFailed(Exception e) {
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logSubscribeFailed(group, dataId, description, configType, isConfigSingleKey, e);
}
public void logUnsubscribeStarted() {
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logUnsubscribeStarted(group, dataId, description, configType, isConfigSingleKey);
}
public void logUnsubscribeFailed(Exception e) {
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logUnsubscribeFailed(group, dataId, description, configType, isConfigSingleKey, e);
}
public void logCallbackFailed(Exception e) {
String description = getDescription();
DiscoveryConfigProcessorLogger.logCallbackFailed(description, e);
}
public boolean isConfigSingleKey() {
ConfigType configType = getConfigType();
return ConfigType.isSingleKey(configType);
}
public void beforeInitialization() {
}
public void afterInitialization() {
}
public abstract ConfigType getConfigType();
public abstract String getGroup();
public abstract String getDataId();
public abstract String getDescription();
public abstract void callbackConfig(String config);
} |
String group = getGroup();
String dataId = getDataId();
String description = getDescription();
ConfigType configType = getConfigType();
boolean isConfigSingleKey = isConfigSingleKey();
DiscoveryConfigProcessorLogger.logGetFailed(group, dataId, description, configType, isConfigSingleKey, e);
| 73 | 724 | 83 | 807 |
469 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/processor/DiscoveryConfigProcessorLogger.java | DiscoveryConfigProcessorLogger | logGetFailed | class DiscoveryConfigProcessorLogger {
private static final Logger LOG = LoggerFactory.getLogger(DiscoveryConfigProcessorLogger.class);
public static void logGetStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) {
LOG.info("Get {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId);
}
public static void logGetFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) {<FILL_FUNCTION_BODY>}
public static void logNotFound(String description, ConfigType configType) {
LOG.info("Not found {} config from {} server", description, configType);
}
public static void logSubscribeStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) {
LOG.info("Subscribe {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId);
}
public static void logSubscribeFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) {
LOG.error("Subscribe {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e);
}
public static void logUnsubscribeStarted(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey) {
LOG.info("Unsubscribe {} config from {} server, " + getLogKey(isConfigSingleKey), description, configType, group, dataId);
}
public static void logUnsubscribeFailed(String group, String dataId, String description, ConfigType configType, boolean isConfigSingleKey, Exception e) {
LOG.error("Unsubscribe {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e);
}
public static void logCallbackFailed(String description, Exception e) {
LOG.error("Callback {} config failed", description, e);
}
private static String getLogKey(boolean isConfigSingleKey) {
return isConfigSingleKey ? "key={}-{}" : "group={}, dataId={}";
}
} |
LOG.error("Get {} config from {} server failed, " + getLogKey(isConfigSingleKey), description, configType, group, dataId, e);
| 27 | 570 | 40 | 610 |
471 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/thread/DiscoveryNamedThreadFactory.java | DiscoveryNamedThreadFactory | newThread | class DiscoveryNamedThreadFactory implements ThreadFactory {
private AtomicInteger count = new AtomicInteger(1);
private ThreadGroup group;
private String namePrefix;
private boolean daemon;
public DiscoveryNamedThreadFactory(String namePrefix) {
this(namePrefix, false);
}
public DiscoveryNamedThreadFactory(String namePrefix, boolean daemon) {
SecurityManager securityManager = System.getSecurityManager();
this.group = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix;
this.daemon = daemon;
}
@Override
public Thread newThread(Runnable runnable) {<FILL_FUNCTION_BODY>}
} |
Thread thread = new Thread(group, runnable, namePrefix + "-thread-" + count.getAndIncrement(), 0);
thread.setDaemon(daemon);
return thread;
| 41 | 191 | 51 | 242 |
472 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/BeanRegisterUtil.java | BeanRegisterUtil | registerBean | class BeanRegisterUtil {
public static BeanDefinitionRegistry getRegistry(ConfigurableApplicationContext applicationContext) {
return (BeanDefinitionRegistry) applicationContext.getBeanFactory();
}
public static void registerBean(BeanDefinitionRegistry beanDefinitionRegistry, String beanName, String beanClassName) {<FILL_FUNCTION_BODY>}
public static void registerBean(BeanDefinitionRegistry beanDefinitionRegistry, String beanName, Class<?> beanClass) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
}
} |
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClassName);
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
| 44 | 194 | 83 | 277 |
473 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/ClassUtil.java | ClassUtil | getParameterMap | class ClassUtil {
public static Map<String, Object> getParameterMap(String[] methodParameterNames, Object[] arguments) {<FILL_FUNCTION_BODY>}
} |
Map<String, Object> parameterMap = new LinkedHashMap<String, Object>();
if (ArrayUtils.isNotEmpty(arguments)) {
for (int i = 0; i < arguments.length; i++) {
String parameterName = null;
if (ArrayUtils.isNotEmpty(methodParameterNames)) {
parameterName = methodParameterNames[i];
} else {
parameterName = String.valueOf(i);
}
Object argument = arguments[i];
parameterMap.put(parameterName, argument);
}
}
return parameterMap;
| 230 | 44 | 147 | 191 |
474 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FileUtil.java | FileUtil | toFile | class FileUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileUtil.class);
public static File getFile(ApplicationContext applicationContext, String path) {
if (StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("File path doesn't set");
}
try {
String filePath = applicationContext.getEnvironment().resolvePlaceholders(path);
File file = applicationContext.getResource(filePath).getFile();
LOG.info("File [{}] is found", path);
return file;
} catch (Exception e) {
LOG.warn("File [{}] isn't found or valid, ignore to load...", path);
}
return null;
}
public static InputStream getInputStream(ApplicationContext applicationContext, String path) {
if (StringUtils.isEmpty(path)) {
throw new IllegalArgumentException("File path doesn't set");
}
try {
String filePath = applicationContext.getEnvironment().resolvePlaceholders(path);
InputStream inputStream = applicationContext.getResource(filePath).getInputStream();
LOG.info("File [{}] is found", path);
return inputStream;
} catch (Exception e) {
LOG.warn("File [{}] isn't found or valid, ignore to load...", path);
}
return null;
}
public static String getText(ApplicationContext applicationContext, String path) {
InputStream inputStream = null;
try {
inputStream = getInputStream(applicationContext, path);
if (inputStream != null) {
try {
return IOUtils.toString(inputStream, DiscoveryConstant.ENCODING_UTF_8);
} catch (IOException e) {
LOG.warn("InputStream to String failed, ignore to load...");
}
}
} finally {
if (inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
}
return null;
}
public static void toFile(String text, String directoryPath, String fileName, String encoding) throws IOException {
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
directory.mkdirs();
}
File file = new File(directoryPath + File.separator + fileName);
FileUtils.writeStringToFile(file, text, encoding);
}
public static void toFile(byte[] bytes, String directoryPath, String fileName) throws IOException {<FILL_FUNCTION_BODY>}
public static byte[] fromFile(String directoryPath, String fileName) throws IOException {
File file = new File(directoryPath + File.separator + fileName);
return FileUtils.readFileToByteArray(file);
}
public static void forceDeleteDirectory(File directory, int forceTimes) {
if (directory.isDirectory() && directory.exists()) {
try {
FileUtils.deleteDirectory(directory);
forceTimes--;
if (forceTimes > 0) {
forceDeleteDirectory(directory, forceTimes);
} else {
throw new IOException("Force delete directory=" + directory + " failed");
}
} catch (IOException e) {
}
}
}
public static void forceDeleteFile(File file, int forceTimes) {
if (file.isFile() && file.exists()) {
try {
FileUtils.deleteQuietly(file);
forceTimes--;
if (forceTimes > 0) {
forceDeleteFile(file, forceTimes);
} else {
throw new IOException("Force delete file=" + file + " failed");
}
} catch (IOException e) {
}
}
}
public static byte[] getBytes(File file) throws FileNotFoundException, IOException {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
return IOUtils.toByteArray(inputStream);
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
}
}
} |
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
directory.mkdirs();
}
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
File file = new File(directoryPath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} finally {
if (bos != null) {
IOUtils.closeQuietly(bos);
}
if (fos != null) {
IOUtils.closeQuietly(fos);
}
}
| 248 | 1,061 | 174 | 1,235 |
475 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/FormatUtil.java | FormatUtil | getFormatType | class FormatUtil {
public static FormatType getFormatType(String content) {<FILL_FUNCTION_BODY>}
} |
if (XmlUtil.isXmlFormat(content)) {
return FormatType.XML_FORMAT;
} else if (JsonUtil.isJsonFormat(content)) {
return FormatType.JSON_FORMAT;
/*} else if (YamlUtil.isYamlFormat(content)) {
return FormatType.YAML_FORMAT;
} else if (PropertiesUtil.isPropertiesFormat(content)) {
return FormatType.PROPERTIES_FORMAT;*/
} else {
return FormatType.TEXT_FORMAT;
}
| 134 | 33 | 131 | 164 |
476 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/IOUtil.java | IOUtil | getInputStream | class IOUtil {
public static InputStream getInputStream(String path) throws IOException {<FILL_FUNCTION_BODY>}
} |
// 从Resource路径获取
InputStream inputStream = IOUtil.class.getClassLoader().getResourceAsStream(path);
if (inputStream == null) {
// 从文件路径获取
inputStream = new FileInputStream(path);
}
return inputStream;
| 82 | 34 | 75 | 109 |
477 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/JsonUtil.java | NullKeySerializer | fromJsonMap | class NullKeySerializer extends StdSerializer<Object> {
private static final long serialVersionUID = -9176767187240330396L;
public NullKeySerializer() {
this(null);
}
public NullKeySerializer(Class<Object> object) {
super(object);
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeFieldName(StringUtils.EMPTY);
}
}
public static <T> String toJson(T object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static <T> String toPrettyJson(T object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
try {
return objectMapper.writer(discoveryPrettyPrinter).writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static <T> T fromJson(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("Json is null or empty");
}
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static <T> T fromJson(String json, TypeReference<T> typeReference) {
if (StringUtils.isEmpty(json)) {
throw new IllegalArgumentException("Json is null or empty");
}
try {
return objectMapper.readValue(json, typeReference);
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
public static boolean isJsonFormat(String json) {
if (StringUtils.isBlank(json)) {
return false;
}
try {
objectMapper.readTree(json);
return true;
} catch (Exception e) {
return false;
}
}
@SuppressWarnings("unchecked")
public static String fromJsonMap(String json, String key) {<FILL_FUNCTION_BODY> |
if (StringUtils.isEmpty(json)) {
return null;
}
String value = null;
try {
Map<String, String> map = fromJson(json, Map.class);
value = map.get(key);
} catch (Exception e) {
value = json;
}
return value;
| 130 | 636 | 88 | 724 |
478 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/MathsUtil.java | MathsUtil | calculate | class MathsUtil {
private static final char ASTERISK = '*';
public static Long calculate(String value) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isEmpty(value)) {
return null;
}
long result = 1;
try {
String[] array = StringUtils.split(value, ASTERISK);
for (String data : array) {
result *= Long.parseLong(data.trim());
}
} catch (Exception e) {
return null;
}
return result;
| 161 | 46 | 103 | 149 |
479 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PluginInfoUtil.java | PluginInfoUtil | extractAll | class PluginInfoUtil {
private static Pattern pattern = Pattern.compile("\\[\\S+\\]");
public static List<Map<String, String>> assembleAll(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return assembleAll(text, filterList);
}
public static List<Map<String, String>> assembleAll(String text, List<String> filterList) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
List<String> singleList = StringUtil.splitToList(text, " -> ");
for (String value : singleList) {
Map<String, String> map = assembleSingle(value, filterList);
list.add(map);
}
return list;
}
public static Map<String, String> assembleSingle(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return assembleSingle(text, filterList);
}
public static Map<String, String> assembleSingle(String text, List<String> filterList) {
text = StringUtils.replace(text, "][", "] [");
Matcher matcher = pattern.matcher(text);
Map<String, String> map = new LinkedHashMap<String, String>();
while (matcher.find()) {
String group = matcher.group();
String value = StringUtils.substringBetween(group, "[", "]");
String[] array = StringUtils.split(value, "=");
if (CollectionUtils.isEmpty(filterList) || filterList.contains(array[0])) {
map.put(array[0], array[1]);
}
}
return map;
}
public static String extractAll(String text, String filters) {
List<String> filterList = StringUtil.splitToList(filters, ",");
return extractAll(text, filterList);
}
public static String extractAll(String text, List<String> filterList) {<FILL_FUNCTION_BODY>}
public static String substringSingle(String text, String keyword) {
if (text.contains("[" + keyword + "=")) {
String value = text.substring(text.indexOf("[" + keyword + "=") + keyword.length() + 2);
return value.substring(0, value.indexOf("]"));
}
return null;
}
} |
if (CollectionUtils.isEmpty(filterList)) {
return text;
}
StringBuilder stringBuilder = new StringBuilder();
List<Map<String, String>> list = assembleAll(text, filterList);
for (Map<String, String> map : list) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
stringBuilder.append("[").append(key).append("=").append(value).append("]");
}
stringBuilder.append(" -> ");
}
stringBuilder.delete(stringBuilder.length() - 4, stringBuilder.length());
return stringBuilder.toString();
| 201 | 639 | 184 | 823 |
480 | Nepxion_Discovery | Discovery/discovery-commons/discovery-common/src/main/java/com/nepxion/discovery/common/util/PropertiesUtil.java | PropertiesUtil | isPropertiesFormat | class PropertiesUtil {
public static final Pattern PATTERN = Pattern.compile("-(\\w)");
public static void enrichProperties(Properties properties, Environment environment, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) {
enrichProperties(properties, environment, PATTERN, prefix, replaceExistedKey, ignoreEmptyValue);
}
public static void enrichProperties(Properties properties, Environment environment, Pattern pattern, String prefix, boolean replaceExistedKey, boolean ignoreEmptyValue) {
Map<String, Object> map = PropertySourcesUtils.getSubProperties((ConfigurableEnvironment) environment, prefix);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = resolveKey(pattern, entry.getKey());
String value = String.valueOf(entry.getValue());
addProperty(properties, key, value, replaceExistedKey, ignoreEmptyValue);
}
}
public static void addProperty(Properties properties, String key, String value, boolean replaceExistedKey, boolean ignoreEmptyValue) {
if (properties.containsKey(key)) {
if (replaceExistedKey) {
addProperty(properties, key, value, ignoreEmptyValue);
}
} else {
addProperty(properties, key, value, ignoreEmptyValue);
}
}
public static void addProperty(Properties properties, String key, String value, boolean ignoreEmptyValue) {
if (StringUtils.isBlank(value)) {
if (!ignoreEmptyValue) {
properties.put(key, value);
}
} else {
properties.put(key, value);
}
}
public static String resolveKey(String key) {
return resolveKey(PATTERN, key);
}
public static String resolveKey(Pattern pattern, String key) {
Matcher matcher = pattern.matcher(key);
StringBuffer stringBuffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(stringBuffer, matcher.group(1).toUpperCase());
}
matcher.appendTail(stringBuffer);
return stringBuffer.toString();
}
public static boolean isPropertiesFormat(String properties) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isBlank(properties)) {
return false;
}
InputStream inputStream = null;
Reader reader = null;
try {
inputStream = IOUtils.toInputStream(properties, DiscoveryConstant.ENCODING_UTF_8);
reader = new InputStreamReader(inputStream, DiscoveryConstant.ENCODING_UTF_8);
new Properties().load(reader);
return true;
} catch (Exception e) {
return false;
} finally {
if (reader != null) {
IOUtils.closeQuietly(reader);
}
if (inputStream != null) {
IOUtils.closeQuietly(inputStream);
}
}
| 255 | 559 | 188 | 747 |