input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public void put(String cacheName, Object key, Object value, int liveSeconds) {
try {
ehcache.put(cacheName, key, value, liveSeconds);
redisCache.put(cacheName, key, value, liveSeconds);
} finally {
Jboot.me().getMq().publish(new JbootEhredisMessage(clientId, JbootEhredisMessage.ACTION_PUT, cacheName, key), channel);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void put(String cacheName, Object key, Object value, int liveSeconds) {
try {
ehcache.put(cacheName, key, value, liveSeconds);
redisCache.put(cacheName, key, value, liveSeconds);
} finally {
publishMessage(JbootEhredisMessage.ACTION_PUT, cacheName, key);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean save() {
if (hasColumn(COLUMN_CREATED) && get(COLUMN_CREATED) == null) {
set(COLUMN_CREATED, new Date());
}
if (null == get(getPrimaryKey()) && String.class == getPrimaryType()) {
set(getPrimaryKey(), StringUtils.uuid());
}
Boolean autoCopyModel = get(AUTO_COPY_MODEL);
boolean saveSuccess = autoCopyModel == true ? copyModel().saveNormal() : saveNormal();
if (saveSuccess) {
Jboot.sendEvent(addAction(), this);
}
return saveSuccess;
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean save() {
if (hasColumn(COLUMN_CREATED) && get(COLUMN_CREATED) == null) {
set(COLUMN_CREATED, new Date());
}
if (null == get(getPrimaryKey()) && String.class == getPrimaryType()) {
set(getPrimaryKey(), StringUtils.uuid());
}
Boolean autoCopyModel = get(AUTO_COPY_MODEL);
boolean saveSuccess = (autoCopyModel != null && autoCopyModel) ? copyModel().saveNormal() : saveNormal();
if (saveSuccess) {
Jboot.sendEvent(addAction(), this);
}
return saveSuccess;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequiresPermissions("adminSystemVariable")
@RequestMapping(value="variableSave${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public BaseVO variableSave(System sys, Model model, HttpServletRequest request){
System system;
if(Global.system.get(sys.getName()) == null){
system = new System();
system.setName(sys.getName());
}else{
//有,编辑即可
system = sqlService.findAloneByProperty(System.class, "name", sys.getName());
}
system.setDescription(sys.getDescription());
system.setLasttime(DateUtil.timeForUnix10());
system.setValue(sys.getValue());
sqlService.save(system);
/***更新内存数据****/
systemService.refreshSystemCache();
ActionLogCache.insert(request, system.getId(), "保存系统变量", system.getName()+"="+system.getValue());
return success();
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequiresPermissions("adminSystemVariable")
@RequestMapping(value="variableSave${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public BaseVO variableSave(System sys, Model model, HttpServletRequest request){
System system = sqlService.findAloneByProperty(System.class, "name", sys.getName());
if(system == null){
//新增
system = new System();
system.setName(sys.getName());
}else{
//编辑
}
system.setDescription(sys.getDescription());
system.setLasttime(DateUtil.timeForUnix10());
system.setValue(sys.getValue());
sqlService.save(system);
/***更新内存数据****/
systemService.refreshSystemCache();
ActionLogCache.insert(request, system.getId(), "保存系统变量", system.getName()+"="+system.getValue());
return success();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping(value="saveTemplateName${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public BaseVO saveTemplateName(HttpServletRequest request,
@RequestParam(value = "templateName", required = false, defaultValue="") String templateName){
if(!haveSiteAuth()){
return error("无权操作");
}
if(!clientCheck(request)){
return error( "模版开发仅限本地运行使用!");
}
Site site = getSite();
if(site.getTemplateName() != null && site.getTemplateName().length() > 0){
return error("当前已有模版编码,不可再次设置!");
}
templateName = StringUtil.filterXss(templateName);
if(templateName.length() == 0){
return error("您还没填写模版编码呢");
}
//在 template 数据表中判断是否存在这个模版,若不存在,则创建
Template template = sqlService.findAloneByProperty(Template.class, "name", templateName);
if(template != null){
return error("模版已存在!请重新起个名吧");
}
template = new Template();
template.setAddtime(DateUtil.timeForUnix10());
template.setName(templateName);
template.setUserid(getUserId());
sqlService.save(template); //保存模版
//将当前站点使用模版设置为此模版
site = sqlService.findById(Site.class, site.getId());
site.setTemplateName(templateName);
sqlService.save(site);
setSite(site);
//将当前站点使用的模版变量、模版页面全部设置为绑定这个模版
sqlService.updateByHql(TemplatePage.class, "templateName", templateName, "siteid", site.getId());
sqlService.updateByHql(TemplateVar.class, "templateName", templateName, "siteid", site.getId());
//创建模版编码的文件夹
File file = new File(Global.getProjectPath()+getExportPath()+templateName);
file.mkdir(); //创建这个文件夹
//创建 css 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/css").mkdir();
//创建 js 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/js").mkdir();
//创建 images 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/images").mkdir();
AliyunLog.addActionLog(site.getId(), "模版开发-保存模版编码");
return success();
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequestMapping(value="saveTemplateName${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public BaseVO saveTemplateName(HttpServletRequest request,
@RequestParam(value = "templateName", required = false, defaultValue="") String templateName){
if(!haveSiteAuth()){
return error("无权操作");
}
if(!clientCheck(request)){
return error( "模版开发仅限本地运行使用!");
}
templateName = StringUtil.filterXss(templateName);
if(templateName.length() == 0){
return error("您还没填写模版编码呢");
}
Site site = getSite();
//在 template 数据表中判断是否存在这个模版,若不存在,则创建
Template template = sqlService.findAloneByProperty(Template.class, "name", templateName);
if(template != null){
return error("模版已存在!请重新起个名吧");
}
//资源文件设置,创建或者转移
if(site.getTemplateName() != null && site.getTemplateName().length() > 0){
//return error("当前已有模版编码,不可再次设置!");
//当前已有模版编码,判断是否是这个人的,也就是判断一下是否有原本模版编码的模版资源文件
System.out.println(Global.getProjectPath()+getExportPath()+site.getTemplateName());
if(!FileUtil.exists(Global.getProjectPath()+getExportPath()+site.getTemplateName())){
return error("没有发现模版资源文件!模版是你做的吗?");
}
System.out.println("old----- "+Global.getProjectPath()+getExportPath()+site.getTemplateName());
File file = new File(Global.getProjectPath()+getExportPath()+site.getTemplateName());
file.renameTo(new File(Global.getProjectPath()+getExportPath()+templateName));
System.out.println("new------ "+Global.getProjectPath()+getExportPath()+templateName);
}else{
//当前还没有模版编码
//创建模版编码的文件夹
File file = new File(Global.getProjectPath()+getExportPath()+templateName);
file.mkdir(); //创建这个文件夹
//创建 css 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/css").mkdir();
//创建 js 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/js").mkdir();
//创建 images 文件夹
new File(Global.getProjectPath()+getExportPath()+templateName+"/images").mkdir();
}
template = new Template();
template.setAddtime(DateUtil.timeForUnix10());
template.setName(templateName);
template.setUserid(getUserId());
sqlService.save(template); //保存模版
//将当前站点使用模版设置为此模版
site = sqlService.findById(Site.class, site.getId());
site.setTemplateName(templateName);
sqlService.save(site);
//更新当前站点的缓存
setSite(site);
//将当前站点使用的模版变量、模版页面全部设置为绑定这个模版
sqlService.updateByHql(TemplatePage.class, "templateName", templateName, "siteid", site.getId());
sqlService.updateByHql(TemplateVar.class, "templateName", templateName, "siteid", site.getId());
AliyunLog.addActionLog(site.getId(), "模版开发-保存模版编码");
return success();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public TemplatePageVO saveTemplatePageText(String fileName, String html, HttpServletRequest request) {
TemplatePageVO vo = new TemplatePageVO();
fileName = Safety.filter(fileName);
if(fileName == null || fileName.length() == 0){
vo.setBaseVO(BaseVO.FAILURE, "出错,你要修改的是哪个模版呢?");
return vo;
}
Site site = Func.getCurrentSite();
//判断其是否是进行了自由编辑,替换掉其中htmledit加入的js跟css文件,也就是替换掉<!--XNX3HTMLEDIT-->跟</head>中间的所有字符,网页源码本身<!--XNX3HTMLEDIT-->跟</head>是挨着的
int htmledit_start = html.indexOf("<!--XNX3HTMLEDIT-->");
if(htmledit_start > 0){
int htmledit_head = html.indexOf("</head>");
if(htmledit_head == -1){
//出错了,忽略
}else{
//成功,进行过滤中间的htmledit加入的js跟css
html = html.substring(0, htmledit_start)+html.substring(htmledit_head, html.length());
}
//contenteditable=true去掉
if(html.indexOf("<body contenteditable=\"true\">") > -1){
html = html.replace("<body contenteditable=\"true\">", "<body>");
}else{
html = html.replaceAll(" contenteditable=\"true\"", "");
}
}
//如果这个页面中使用了模版变量,保存时,将模版变量去掉,变回模版调用形式{includeid=},卸载变量模版
if(html.indexOf("<!--templateVarStart-->") > -1){
Template temp = new Template(site);
Pattern p = Pattern.compile("<!--templateVarStart-->([\\s|\\S]*?)<!--templateVarEnd-->");
Matcher m = p.matcher(html);
while (m.find()) {
String templateVarText = m.group(1); //<!--templateVarName=-->+模版变量的内容
String templateVarName = temp.getConfigValue(templateVarText, "templateVarName"); //模版变量的名字
templateVarName = Sql.filter(templateVarName);
//替换出当前模版变量的内容,即去掉templateVarText注释
templateVarText = templateVarText.replace("<!--templateVarName="+templateVarName+"-->", "");
//判断模版变量是否有过变动,当前用户是否修改过模版变量,如果修改过,将修改过的模版变量保存
//从内存中取模版变量内容
String content = null;
BaseVO tvVO = getTemplateVarByCache(templateVarName);
if(tvVO.getResult() - BaseVO.SUCCESS == 0){
content = tvVO.getInfo();
}else{
vo.setBaseVO(BaseVO.FAILURE, "其中使用的模版变量“"+templateVarName+"”不存在!保存失败,请检查修改后再尝试保存");
return vo;
}
// String content = G.templateVarMap.get(site.getTemplateName()).get(templateVarName);
//讲用户保存的跟内存中的模版变量内容比较,是否一样,若不一样,要将当前的保存
if(!(content.replaceAll("\r|\n|\t", "").equals(templateVarText.replaceAll("\r|\n|\t", "")))){
//不一样,进行保存
//模版名字检索,是否是使用的导入的模版,若是使用的导入的模版,则只列出导入的模版变量
String templateNameWhere = "";
if(site.getTemplateName() != null && site.getTemplateName().length() > 0){
templateNameWhere = " AND template_var.template_name = '"+ site.getTemplateName() +"'";
}
com.xnx3.wangmarket.admin.entity.TemplateVar tv = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_var WHERE siteid = " + site.getId() + templateNameWhere + " AND var_name = '"+templateVarName+"'", com.xnx3.wangmarket.admin.entity.TemplateVar.class);
if(tv != null){
tv.setUpdatetime(DateUtil.timeForUnix10());
sqlDAO.save(tv);
TemplateVarData templateVarData = sqlDAO.findById(TemplateVarData.class, tv.getId());
templateVarData.setText(templateVarText);
sqlDAO.save(templateVarData);
//保存完后,要将其更新到全局缓存中
updateTemplateVarForCache(tv, templateVarData);
}
}
// 将用户保存的当前的模版页面,模版变量摘除出来,还原为模版调用的模式
html = html.replaceAll("<!--templateVarStart--><!--templateVarName="+templateVarName+"-->([\\s|\\S]*?)<!--templateVarEnd-->", "{include="+templateVarName+"}");
}
}
TemplatePage templatePage = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_page WHERE siteid = "+site.getId()+" AND name = '"+fileName+"'", TemplatePage.class);
if(templatePage == null){
vo.setBaseVO(BaseVO.FAILURE, "要保存的模版页不存在!请手动复制保存好您当前所编辑的模版页内容!");
return vo;
}
TemplatePageData templatePageData = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_page_data WHERE id = "+templatePage.getId(), TemplatePageData.class);
if(templatePageData == null){
//没有发现内容,则是添加
templatePageData = new TemplatePageData();
templatePageData.setId(templatePage.getId());
}
templatePageData.setText(html);
sqlDAO.save(templatePageData);
//刷新Session缓存
updateTemplatePageForCache(templatePage, templatePageData, request);
vo.setTemplatePage(templatePage);
vo.setTemplatePageData(templatePageData);
return vo;
}
#location 33
#vulnerability type NULL_DEREFERENCE | #fixed code
public TemplatePageVO saveTemplatePageText(String fileName, String html, HttpServletRequest request) {
TemplatePageVO vo = new TemplatePageVO();
fileName = Safety.filter(fileName);
if(fileName == null || fileName.length() == 0){
vo.setBaseVO(BaseVO.FAILURE, "出错,你要修改的是哪个模版呢?");
return vo;
}
Site site = Func.getCurrentSite();
TemplatePage templatePage = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_page WHERE siteid = "+site.getId()+" AND name = '"+fileName+"'", TemplatePage.class);
if(templatePage == null){
vo.setBaseVO(BaseVO.FAILURE, "要保存的模版页不存在!请手动复制保存好您当前所编辑的模版页内容!");
return vo;
}
TemplatePageData templatePageData = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_page_data WHERE id = "+templatePage.getId(), TemplatePageData.class);
if(templatePageData == null){
//没有发现内容,则是添加
templatePageData = new TemplatePageData();
templatePageData.setId(templatePage.getId());
}
//判断是代码模式,还是智能模式
if(templatePage.getEditMode() != null && templatePage.getEditMode() - TemplatePage.EDIT_MODE_CODE == 0){
//代码模式编辑,那么直接保存即可,不需要卸载模版变量等
}else{
//可视化编辑,需要提取模版变量、过滤 htmledit 等
//判断其是否是进行了自由编辑,替换掉其中htmledit加入的js跟css文件,也就是替换掉<!--XNX3HTMLEDIT-->跟</head>中间的所有字符,网页源码本身<!--XNX3HTMLEDIT-->跟</head>是挨着的
int htmledit_start = html.indexOf("<!--XNX3HTMLEDIT-->");
if(htmledit_start > 0){
int htmledit_head = html.indexOf("</head>");
if(htmledit_head == -1){
//出错了,忽略
}else{
//成功,进行过滤中间的htmledit加入的js跟css
html = html.substring(0, htmledit_start)+html.substring(htmledit_head, html.length());
}
//contenteditable=true去掉
if(html.indexOf("<body contenteditable=\"true\">") > -1){
html = html.replace("<body contenteditable=\"true\">", "<body>");
}else{
html = html.replaceAll(" contenteditable=\"true\"", "");
}
}
//如果这个页面中使用了模版变量,保存时,将模版变量去掉,变回模版调用形式{includeid=},卸载变量模版
if(html.indexOf("<!--templateVarStart-->") > -1){
Template temp = new Template(site);
Pattern p = Pattern.compile("<!--templateVarStart-->([\\s|\\S]*?)<!--templateVarEnd-->");
Matcher m = p.matcher(html);
while (m.find()) {
String templateVarText = m.group(1); //<!--templateVarName=-->+模版变量的内容
String templateVarName = temp.getConfigValue(templateVarText, "templateVarName"); //模版变量的名字
templateVarName = Sql.filter(templateVarName);
//替换出当前模版变量的内容,即去掉templateVarText注释
templateVarText = templateVarText.replace("<!--templateVarName="+templateVarName+"-->", "");
//判断模版变量是否有过变动,当前用户是否修改过模版变量,如果修改过,将修改过的模版变量保存
//从内存中取模版变量内容
String content = null;
BaseVO tvVO = getTemplateVarByCache(templateVarName);
if(tvVO.getResult() - BaseVO.SUCCESS == 0){
content = tvVO.getInfo();
}else{
vo.setBaseVO(BaseVO.FAILURE, "其中使用的模版变量“"+templateVarName+"”不存在!保存失败,请检查修改后再尝试保存");
return vo;
}
// String content = G.templateVarMap.get(site.getTemplateName()).get(templateVarName);
//讲用户保存的跟内存中的模版变量内容比较,是否一样,若不一样,要将当前的保存
if(!(content.replaceAll("\r|\n|\t", "").equals(templateVarText.replaceAll("\r|\n|\t", "")))){
//不一样,进行保存
//模版名字检索,是否是使用的导入的模版,若是使用的导入的模版,则只列出导入的模版变量
String templateNameWhere = "";
if(site.getTemplateName() != null && site.getTemplateName().length() > 0){
templateNameWhere = " AND template_var.template_name = '"+ site.getTemplateName() +"'";
}
com.xnx3.wangmarket.admin.entity.TemplateVar tv = sqlDAO.findAloneBySqlQuery("SELECT * FROM template_var WHERE siteid = " + site.getId() + templateNameWhere + " AND var_name = '"+templateVarName+"'", com.xnx3.wangmarket.admin.entity.TemplateVar.class);
if(tv != null){
tv.setUpdatetime(DateUtil.timeForUnix10());
sqlDAO.save(tv);
TemplateVarData templateVarData = sqlDAO.findById(TemplateVarData.class, tv.getId());
templateVarData.setText(templateVarText);
sqlDAO.save(templateVarData);
//保存完后,要将其更新到全局缓存中
updateTemplateVarForCache(tv, templateVarData);
}
}
// 将用户保存的当前的模版页面,模版变量摘除出来,还原为模版调用的模式
html = html.replaceAll("<!--templateVarStart--><!--templateVarName="+templateVarName+"-->([\\s|\\S]*?)<!--templateVarEnd-->", "{include="+templateVarName+"}");
}
}
}
templatePageData.setText(html);
sqlDAO.save(templatePageData);
//刷新Session缓存
updateTemplatePageForCache(templatePage, templatePageData, request);
vo.setTemplatePage(templatePage);
vo.setTemplatePageData(templatePageData);
return vo;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public BaseVO refreshForTemplate(HttpServletRequest request){
BaseVO vo = new BaseVO();
Site site = Func.getCurrentSite();
TemplateCMS template = new TemplateCMS(site);
//取得当前网站所有模版页面
// TemplatePageListVO templatePageListVO = templateService.getTemplatePageListByCache(request);
//取得当前网站首页模版页面
TemplatePageVO templatePageIndexVO = templateService.getTemplatePageIndexByCache(request);
//取得网站所有栏目信息
List<SiteColumn> siteColumnList = sqlDAO.findBySqlQuery("SELECT * FROM site_column WHERE siteid = "+site.getId()+" ORDER BY rank ASC", SiteColumn.class);
//取得网站所有文章News信息
List<News> newsList = sqlDAO.findBySqlQuery("SELECT * FROM news WHERE siteid = "+site.getId() + " AND status = "+News.STATUS_NORMAL+" ORDER BY addtime DESC", News.class);
List<NewsData> newsDataList = sqlDAO.findBySqlQuery("SELECT news_data.* FROM news,news_data WHERE news.siteid = "+site.getId() + " AND news.status = "+News.STATUS_NORMAL+" AND news.id = news_data.id ORDER BY news.id DESC", NewsData.class);
//对栏目进行重新调整,以栏目codeName为key,将栏目加入进Map中。用codeName来取栏目
Map<String, SiteColumn> columnMap = new HashMap<String, SiteColumn>();
//对文章-栏目进行分类,以栏目codeName为key,将文章List加入进自己对应的栏目。同时,若传入父栏目代码,其栏目下有多个新闻子栏目,会调出所有子栏目的内容(20条以内)
Map<String, List<News>> columnNewsMap = new HashMap<String, List<News>>();
for (int i = 0; i < siteColumnList.size(); i++) { //遍历栏目,将对应的文章加入其所属栏目
SiteColumn siteColumn = siteColumnList.get(i);
List<News> nList = new ArrayList<News>();
for (int j = 0; j < newsList.size(); j++) {
News news = newsList.get(j);
if(news.getCid() - siteColumn.getId() == 0){
nList.add(news);
newsList.remove(j); //将已经加入Map的文章从newsList中移除,提高效率。同时j--。
j--;
continue;
}
}
//默认是按照时间倒序,但是v4.4以后,用户可以自定义,可以根据时间正序排序,如果不是默认的倒序的话,就需要重新排序
//这里是某个具体子栏目的排序,父栏目排序调整的在下面
if(siteColumn.getListRank() != null && siteColumn.getListRank() - SiteColumn.LIST_RANK_ADDTIME_ASC == 0 ){
Collections.sort(nList, new Comparator<News>() {
public int compare(News n1, News n2) {
//按照发布时间正序排序,发布时间越早,排列越靠前
return n1.getAddtime() - n2.getAddtime();
}
});
}
columnMap.put(siteColumn.getCodeName(), siteColumn);
columnNewsMap.put(siteColumn.getCodeName(), nList);
}
//对 newsDataList 网站文章的内容进行调整,调整为map key:newsData.id value:newsData.text
Map<Integer, NewsDataBean> newsDataMap = new HashMap<Integer, NewsDataBean>();
for (int i = 0; i < newsDataList.size(); i++) {
NewsData nd = newsDataList.get(i);
newsDataMap.put(nd.getId(), new NewsDataBean(nd));
}
/*
* 对栏目进行上下级初始化,找到哪个是父级栏目,哪些是子栏目。并可以根据栏目代码来获取父栏目下的自栏目。 获取栏目树
*/
Map<String, SiteColumnTreeVO> columnTreeMap = new HashMap<String, SiteColumnTreeVO>(); //栏目树,根据栏目id获取当前栏目,以及下级栏目
//首先,遍历父栏目,将最顶级栏目(一级栏目)拿出来
for (int i = 0; i < siteColumnList.size(); i++) {
SiteColumn siteColumn = siteColumnList.get(i);
//根据父栏目代码,判断是否有上级栏目,若没有的话,那就是顶级栏目了,将其加入栏目树
if(siteColumn.getParentCodeName() == null || siteColumn.getParentCodeName().length() == 0){
SiteColumnTreeVO scTree = new SiteColumnTreeVO();
scTree.setSiteColumn(siteColumn);
scTree.setList(new ArrayList<SiteColumnTreeVO>());
scTree.setLevel(1); //顶级栏目,1级栏目
columnTreeMap.put(siteColumn.getCodeName(), scTree);
}
}
//然后,再遍历父栏目,将二级栏目拿出来
for (int i = 0; i < siteColumnList.size(); i++) {
SiteColumn siteColumn = siteColumnList.get(i);
//判断是否有上级栏目,根据父栏目代码,如果有的话,那就是子栏目了,符合
if(siteColumn.getParentCodeName() != null && siteColumn.getParentCodeName().length() > 0){
SiteColumnTreeVO scTree = new SiteColumnTreeVO();
scTree.setSiteColumn(siteColumn);
scTree.setList(new ArrayList<SiteColumnTreeVO>());
scTree.setLevel(2); //子栏目,二级栏目
if(columnTreeMap.get(siteColumn.getParentCodeName()) != null){
columnTreeMap.get(siteColumn.getParentCodeName()).getList().add(scTree);
}else{
//没有找到该子栏目的父栏目
}
}
}
/*
* 栏目树取完了,接着进行对栏目树内,有子栏目的父栏目,进行信息汇总,将子栏目的信息列表,都合并起来,汇总成一个父栏目的
*/
//对文章-父栏目进行分类,以栏目codeName为key,将每个子栏目的文章加入进总的所属的父栏目的List中,然后进行排序
Map<String, List<com.xnx3.wangmarket.admin.bean.News>> columnTreeNewsMap = new HashMap<String, List<com.xnx3.wangmarket.admin.bean.News>>();
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
//有子栏目,才会对其进行数据汇总
columnTreeNewsMap.put(sct.getSiteColumn().getCodeName(), new ArrayList<com.xnx3.wangmarket.admin.bean.News>());
//遍历其子栏目,将每个子栏目的News信息合并在一块,供父栏目直接调用
for (int i = 0; i < sct.getList().size(); i++) {
SiteColumnTreeVO subSct = sct.getList().get(i); //子栏目的栏目信息
//v4.7版本更新,增加判断,只有栏目类型是列表页面的,才会将子栏目的信息合并入父栏目。
if(subSct.getSiteColumn().getType() - SiteColumn.TYPE_LIST == 0){
//将该栏目的News文章,创建一个新的List
List<com.xnx3.wangmarket.admin.bean.News> nList = new ArrayList<com.xnx3.wangmarket.admin.bean.News>();
List<News> oList = columnNewsMap.get(subSct.getSiteColumn().getCodeName());
for (int j = 0; j < oList.size(); j++) {
com.xnx3.wangmarket.admin.bean.News n = new com.xnx3.wangmarket.admin.bean.News();
News news = oList.get(j);
n.setNews(news);
n.setRank(news.getId());
nList.add(n);
}
//将新的List,合并入父栏目CodeName的List
columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()).addAll(nList);
}
}
}
}
//合并完后,对每个父栏目的List进行先后顺序排序
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
// Collections.sort(columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()));
Collections.sort(columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()), new Comparator<com.xnx3.wangmarket.admin.bean.News>() {
public int compare(com.xnx3.wangmarket.admin.bean.News n1, com.xnx3.wangmarket.admin.bean.News n2) {
if(sct.getSiteColumn().getListRank() != null && sct.getSiteColumn().getListRank() - SiteColumn.LIST_RANK_ADDTIME_ASC == 0){
//按照发布时间正序排序,发布时间越早,排列越靠前
return n2.getNews().getAddtime() - n1.getNews().getAddtime();
}else{
//按照发布时间倒序排序,发布时间越晚,排列越靠前
return n1.getNews().getAddtime() - n2.getNews().getAddtime();
}
}
});
}
}
//排序完后,将其取出,加入columnNewsMap中,供模版中动态调用父栏目代码,就能直接拿到其的所有子栏目信息数据
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
List<com.xnx3.wangmarket.admin.bean.News> nList = columnTreeNewsMap.get(sct.getSiteColumn().getCodeName());
for (int i = nList.size()-1; i >= 0 ; i--) {
columnNewsMap.get(sct.getSiteColumn().getCodeName()).add(nList.get(i).getNews());
}
}
}
/*
* sitemap.xml
*/
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<urlset\n"
+ "\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n"
+ "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ "\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n"
+ "\t\thttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
//加入首页
String indexUrl = "http://"+Func.getDomain(site);
xml = xml + getSitemapUrl(indexUrl, "1.00");
/*
* 模版替换生成页面的步骤
* 1.替换模版变量的标签
* 1.1 通用标签
* 1.2 动态栏目调用标签 (这里要将动态调用标签最先替换。不然动态调用标签非常可能会生成列表,会增加替换通用标签的数量,所以先替换通用标签后,在替换动态模版调用标签)
* 2.替换列表页模版、详情页模版的标签
* 2.1 通用标签
* 2.2 动态栏目调用标签
* 2.3 模版变量装载
*
*
* 分支--1->生成首页
* 分支--2->生成栏目列表页、详情页
* 分支--2->生成sitemap.xml
*/
//1.替换模版变量的标签,并在替换完毕后将其加入Session缓存
// Map<String, String> varMap = new HashMap<String, String>();
// Map<String, String> varMap = Func.getUserBeanForShiroSession().getTemplateVarDataMapForOriginal();
//v2.24,将模版变量的比对,改为模版页面
TemplatePageListVO tplVO = templateService.getTemplatePageListByCache(request);
if(tplVO == null || tplVO.getList().size() == 0){
vo.setBaseVO(BaseVO.FAILURE, "当前网站尚未选择/导入/增加模版,生成失败!网站有模版后才能根据模版生成整站!");
return vo;
}
//当网站只有一个首页时,是不需要这个的。所以只需要上面的,判断一下是否有模版页就够了。 v2.24更新
if(Func.getUserBeanForShiroSession().getTemplateVarMapForOriginal() != null){ //v4.7加入,避免只有一个首页时,生成整站第一次报错
}
for (Map.Entry<String, TemplateVarVO> entry : Func.getUserBeanForShiroSession().getTemplateVarMapForOriginal().entrySet()) {
//替换公共标签
String v = template.replacePublicTag(entry.getValue().getTemplateVarData().getText());
//替换栏目的动态调用标签
v = template.replaceSiteColumnBlock(v, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
Func.getUserBeanForShiroSession().getTemplateVarCompileDataMap().put(entry.getKey(), v);
}
/*
* 进行第二步,对列表页模版、详情页模版进行通用标签等的替换,将其处理好。等生成的时候,直接取出来替换news、column即可
*/
TemplatePageListVO tpl = templateService.getTemplatePageListByCache(request); //取缓存中的模版页列表
Map<String, String> templateCacheMap = new HashMap<String, String>(); //替换好通用标签等的模版都缓存入此。Map<templatePage.name, templatePageData.text>
for (int i = 0; i < tpl.getList().size(); i++) {
TemplatePageVO tpVO = tpl.getList().get(i);
String text = null; //模版页内容
if(tpVO.getTemplatePageData() == null){
//若缓存中没有缓存上模版页详情,那么从数据库中挨个取出来(暂时先这么做,反正RDS剩余。后续将执行单挑SQL将所有页面一块拿出来再分配)(并且取出来后,要加入缓存,之后在点击生成整站,就不用再去数据库取了)
TemplatePageData tpd = sqlDAO.findById(TemplatePageData.class, tpVO.getTemplatePage().getId());
if(tpd != null){
text = tpd.getText();
}
}else{
text = tpVO.getTemplatePageData().getText();
}
if(text == null){
vo.setBaseVO(BaseVO.FAILURE, "模版页"+tpVO.getTemplatePage().getName()+"的内容不存在!请先检查此模版页");
return vo;
}
//进行2.1、2.2、2.3预操作
//替换公共标签
text = template.replacePublicTag(text);
//替换栏目的动态调用标签
text = template.replaceSiteColumnBlock(text, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
//装载模版变量
text = template.assemblyTemplateVar(text);
//预处理后,将其缓存入Map,等待生成页面时直接获取
templateCacheMap.put(tpVO.getTemplatePage().getName(), text);
}
//最后还要将获得到的内容缓存入Session,下次就不用去数据库取了
//生成首页
String indexHtml = templateCacheMap.get(templatePageIndexVO.getTemplatePage().getName());
//替换首页中存在的栏目的动态调用标签
indexHtml = template.replaceSiteColumnBlock(indexHtml, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
indexHtml = template.replacePublicTag(indexHtml); //替换公共标签
//生成首页保存到OSS或本地盘
AttachmentFile.putStringFile("site/"+site.getId()+"/index.html", indexHtml);
/*
* 生成栏目、内容页面
*/
//遍历出所有列表栏目
for (SiteColumn siteColumn : columnMap.values()) {
if(siteColumn.getCodeName() == null || siteColumn.getCodeName().length() == 0){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]的“栏目代码”不存在,请先为其设置栏目代码");
return vo;
}
//取得当前栏目下的News列表
List<News> columnNewsList = columnNewsMap.get(siteColumn.getCodeName());
//获取当前栏目的内容页模版
String viewTemplateHtml = templateCacheMap.get(siteColumn.getTemplatePageViewName());
if(viewTemplateHtml == null){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]未绑定页面内容模版,请去绑定");
return vo;
}
//替换内容模版中的动态栏目调用(动态标签引用)
viewTemplateHtml = template.replaceSiteColumnBlock(viewTemplateHtml, columnNewsMap, columnMap, columnTreeMap, false, siteColumn, newsDataMap);
//如果是新闻或者图文列表,那么才会生成栏目列表页面
if(siteColumn.getType() - SiteColumn.TYPE_LIST == 0 || siteColumn.getType() - SiteColumn.TYPE_NEWS == 0 || siteColumn.getType() - SiteColumn.TYPE_IMAGENEWS == 0){
//当前栏目的列表模版
String listTemplateHtml = templateCacheMap.get(siteColumn.getTemplatePageListName());
if(listTemplateHtml == null){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]未绑定模版列表页面,请去绑定");
return vo;
}
//替换列表模版中的动态栏目调用(动态标签引用)
listTemplateHtml = template.replaceSiteColumnBlock(listTemplateHtml, columnNewsMap, columnMap, columnTreeMap, false, siteColumn, newsDataMap);
//生成其列表页面
template.generateListHtmlForWholeSite(listTemplateHtml, siteColumn, columnNewsList, newsDataMap);
//XML加入栏目页面
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateSiteColumnListPageHtmlName(siteColumn, 1)+".html", "0.4");
/*
* 生成当前栏目的内容页面
*/
//判断栏目属性中,是否设置了生成内容详情页面, v4.7增加
if(siteColumn.getUseGenerateView() == null || siteColumn.getUseGenerateView() - SiteColumn.USED_ENABLE == 0){
for (int i = 0; i < columnNewsList.size(); i++) {
News news = columnNewsList.get(i);
if(siteColumn.getId() - news.getCid() == 0){
//当前文章是此栏目的,那么生成文章详情。不然是不生成的,免得在父栏目中生成子栏目的页面,导致siteColumn调用出现错误
//列表页的内容详情页面,还会有上一篇、下一篇的功能
News upNews = null;
News nextNews = null;
if(i > 0){
upNews = columnNewsList.get(i-1);
}
if((i+1) < columnNewsList.size()){
nextNews = columnNewsList.get(i+1);
}
//生成内容页面
template.generateViewHtmlForTemplateForWholeSite(news, siteColumn, newsDataMap.get(news.getId()), viewTemplateHtml, upNews, nextNews);
//XML加入内容页面
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, news)+".html", "0.5");
}
}
}
}else if(siteColumn.getType() - SiteColumn.TYPE_ALONEPAGE == 0 || siteColumn.getType() - SiteColumn.TYPE_PAGE == 0){
//独立页面,只生成内容模版
if(siteColumn.getEditMode() - SiteColumn.EDIT_MODE_TEMPLATE == 0){
//模版式编辑,无 news , 则直接生成
template.generateViewHtmlForTemplateForWholeSite(null, siteColumn, new NewsDataBean(null), viewTemplateHtml, null, null);
//独立页面享有更大的权重,赋予其 0.8
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, null)+".html", "0.8");
}else{
//UEditor、输入模型编辑方式
for (int i = 0; i < columnNewsList.size(); i++) {
News news = columnNewsList.get(i);
template.generateViewHtmlForTemplateForWholeSite(news, siteColumn, newsDataMap.get(news.getId()), viewTemplateHtml, null, null);
//独立页面享有更大的权重,赋予其 0.8
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, news)+".html", "0.8");
}
}
}else{
//其他栏目不管,当然,也没有其他类型栏目了,v4.6版本更新后,CMS模式一共就这两种类型的
}
}
//生成 sitemap.xml
xml = xml + "</urlset>";
AttachmentFile.putStringFile("site/"+site.getId()+"/sitemap.xml", xml);
return new BaseVO();
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public BaseVO refreshForTemplate(HttpServletRequest request){
BaseVO vo = new BaseVO();
Site site = Func.getCurrentSite();
if(site == null){
vo.setBaseVO(BaseVO.FAILURE, "尚未登陆");
return vo;
}
TemplateCMS template = new TemplateCMS(site);
//取得当前网站所有模版页面
// TemplatePageListVO templatePageListVO = templateService.getTemplatePageListByCache(request);
//取得当前网站首页模版页面
TemplatePageVO templatePageIndexVO = templateService.getTemplatePageIndexByCache(request);
//取得网站所有栏目信息
List<SiteColumn> siteColumnList = sqlDAO.findBySqlQuery("SELECT * FROM site_column WHERE siteid = "+site.getId()+" ORDER BY rank ASC", SiteColumn.class);
//取得网站所有文章News信息
List<News> newsList = sqlDAO.findBySqlQuery("SELECT * FROM news WHERE siteid = "+site.getId() + " AND status = "+News.STATUS_NORMAL+" ORDER BY addtime DESC", News.class);
List<NewsData> newsDataList = sqlDAO.findBySqlQuery("SELECT news_data.* FROM news,news_data WHERE news.siteid = "+site.getId() + " AND news.status = "+News.STATUS_NORMAL+" AND news.id = news_data.id ORDER BY news.id DESC", NewsData.class);
//对栏目进行重新调整,以栏目codeName为key,将栏目加入进Map中。用codeName来取栏目
Map<String, SiteColumn> columnMap = new HashMap<String, SiteColumn>();
//对文章-栏目进行分类,以栏目codeName为key,将文章List加入进自己对应的栏目。同时,若传入父栏目代码,其栏目下有多个新闻子栏目,会调出所有子栏目的内容(20条以内)
Map<String, List<News>> columnNewsMap = new HashMap<String, List<News>>();
for (int i = 0; i < siteColumnList.size(); i++) { //遍历栏目,将对应的文章加入其所属栏目
SiteColumn siteColumn = siteColumnList.get(i);
List<News> nList = new ArrayList<News>();
for (int j = 0; j < newsList.size(); j++) {
News news = newsList.get(j);
if(news.getCid() - siteColumn.getId() == 0){
nList.add(news);
newsList.remove(j); //将已经加入Map的文章从newsList中移除,提高效率。同时j--。
j--;
continue;
}
}
//默认是按照时间倒序,但是v4.4以后,用户可以自定义,可以根据时间正序排序,如果不是默认的倒序的话,就需要重新排序
//这里是某个具体子栏目的排序,父栏目排序调整的在下面
if(siteColumn.getListRank() != null && siteColumn.getListRank() - SiteColumn.LIST_RANK_ADDTIME_ASC == 0 ){
Collections.sort(nList, new Comparator<News>() {
public int compare(News n1, News n2) {
//按照发布时间正序排序,发布时间越早,排列越靠前
return n1.getAddtime() - n2.getAddtime();
}
});
}
columnMap.put(siteColumn.getCodeName(), siteColumn);
columnNewsMap.put(siteColumn.getCodeName(), nList);
}
//对 newsDataList 网站文章的内容进行调整,调整为map key:newsData.id value:newsData.text
Map<Integer, NewsDataBean> newsDataMap = new HashMap<Integer, NewsDataBean>();
for (int i = 0; i < newsDataList.size(); i++) {
NewsData nd = newsDataList.get(i);
newsDataMap.put(nd.getId(), new NewsDataBean(nd));
}
/*
* 对栏目进行上下级初始化,找到哪个是父级栏目,哪些是子栏目。并可以根据栏目代码来获取父栏目下的自栏目。 获取栏目树
*/
Map<String, SiteColumnTreeVO> columnTreeMap = new HashMap<String, SiteColumnTreeVO>(); //栏目树,根据栏目id获取当前栏目,以及下级栏目
//首先,遍历父栏目,将最顶级栏目(一级栏目)拿出来
for (int i = 0; i < siteColumnList.size(); i++) {
SiteColumn siteColumn = siteColumnList.get(i);
//根据父栏目代码,判断是否有上级栏目,若没有的话,那就是顶级栏目了,将其加入栏目树
if(siteColumn.getParentCodeName() == null || siteColumn.getParentCodeName().length() == 0){
SiteColumnTreeVO scTree = new SiteColumnTreeVO();
scTree.setSiteColumn(siteColumn);
scTree.setList(new ArrayList<SiteColumnTreeVO>());
scTree.setLevel(1); //顶级栏目,1级栏目
columnTreeMap.put(siteColumn.getCodeName(), scTree);
}
}
//然后,再遍历父栏目,将二级栏目拿出来
for (int i = 0; i < siteColumnList.size(); i++) {
SiteColumn siteColumn = siteColumnList.get(i);
//判断是否有上级栏目,根据父栏目代码,如果有的话,那就是子栏目了,符合
if(siteColumn.getParentCodeName() != null && siteColumn.getParentCodeName().length() > 0){
SiteColumnTreeVO scTree = new SiteColumnTreeVO();
scTree.setSiteColumn(siteColumn);
scTree.setList(new ArrayList<SiteColumnTreeVO>());
scTree.setLevel(2); //子栏目,二级栏目
if(columnTreeMap.get(siteColumn.getParentCodeName()) != null){
columnTreeMap.get(siteColumn.getParentCodeName()).getList().add(scTree);
}else{
//没有找到该子栏目的父栏目
}
}
}
/*
* 栏目树取完了,接着进行对栏目树内,有子栏目的父栏目,进行信息汇总,将子栏目的信息列表,都合并起来,汇总成一个父栏目的
*/
//对文章-父栏目进行分类,以栏目codeName为key,将每个子栏目的文章加入进总的所属的父栏目的List中,然后进行排序
Map<String, List<com.xnx3.wangmarket.admin.bean.News>> columnTreeNewsMap = new HashMap<String, List<com.xnx3.wangmarket.admin.bean.News>>();
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
//有子栏目,才会对其进行数据汇总
columnTreeNewsMap.put(sct.getSiteColumn().getCodeName(), new ArrayList<com.xnx3.wangmarket.admin.bean.News>());
//遍历其子栏目,将每个子栏目的News信息合并在一块,供父栏目直接调用
for (int i = 0; i < sct.getList().size(); i++) {
SiteColumnTreeVO subSct = sct.getList().get(i); //子栏目的栏目信息
//v4.7版本更新,增加判断,只有栏目类型是列表页面的,才会将子栏目的信息合并入父栏目。
if(subSct.getSiteColumn().getType() - SiteColumn.TYPE_LIST == 0){
//将该栏目的News文章,创建一个新的List
List<com.xnx3.wangmarket.admin.bean.News> nList = new ArrayList<com.xnx3.wangmarket.admin.bean.News>();
List<News> oList = columnNewsMap.get(subSct.getSiteColumn().getCodeName());
for (int j = 0; j < oList.size(); j++) {
com.xnx3.wangmarket.admin.bean.News n = new com.xnx3.wangmarket.admin.bean.News();
News news = oList.get(j);
n.setNews(news);
n.setRank(news.getId());
nList.add(n);
}
//将新的List,合并入父栏目CodeName的List
columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()).addAll(nList);
}
}
}
}
//合并完后,对每个父栏目的List进行先后顺序排序
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
// Collections.sort(columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()));
Collections.sort(columnTreeNewsMap.get(sct.getSiteColumn().getCodeName()), new Comparator<com.xnx3.wangmarket.admin.bean.News>() {
public int compare(com.xnx3.wangmarket.admin.bean.News n1, com.xnx3.wangmarket.admin.bean.News n2) {
if(sct.getSiteColumn().getListRank() != null && sct.getSiteColumn().getListRank() - SiteColumn.LIST_RANK_ADDTIME_ASC == 0){
//按照发布时间正序排序,发布时间越早,排列越靠前
return n2.getNews().getAddtime() - n1.getNews().getAddtime();
}else{
//按照发布时间倒序排序,发布时间越晚,排列越靠前
return n1.getNews().getAddtime() - n2.getNews().getAddtime();
}
}
});
}
}
//排序完后,将其取出,加入columnNewsMap中,供模版中动态调用父栏目代码,就能直接拿到其的所有子栏目信息数据
for (Map.Entry<String, SiteColumnTreeVO> entry : columnTreeMap.entrySet()) {
SiteColumnTreeVO sct = entry.getValue();
if(sct.getList().size() > 0){
List<com.xnx3.wangmarket.admin.bean.News> nList = columnTreeNewsMap.get(sct.getSiteColumn().getCodeName());
for (int i = nList.size()-1; i >= 0 ; i--) {
columnNewsMap.get(sct.getSiteColumn().getCodeName()).add(nList.get(i).getNews());
}
}
}
/*
* sitemap.xml
*/
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<urlset\n"
+ "\txmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n"
+ "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ "\txsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n"
+ "\t\thttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n";
//加入首页
String indexUrl = "http://"+Func.getDomain(site);
xml = xml + getSitemapUrl(indexUrl, "1.00");
/*
* 模版替换生成页面的步骤
* 1.替换模版变量的标签
* 1.1 通用标签
* 1.2 动态栏目调用标签 (这里要将动态调用标签最先替换。不然动态调用标签非常可能会生成列表,会增加替换通用标签的数量,所以先替换通用标签后,在替换动态模版调用标签)
* 2.替换列表页模版、详情页模版的标签
* 2.1 通用标签
* 2.2 动态栏目调用标签
* 2.3 模版变量装载
*
*
* 分支--1->生成首页
* 分支--2->生成栏目列表页、详情页
* 分支--2->生成sitemap.xml
*/
//1.替换模版变量的标签,并在替换完毕后将其加入Session缓存
// Map<String, String> varMap = new HashMap<String, String>();
// Map<String, String> varMap = Func.getUserBeanForShiroSession().getTemplateVarDataMapForOriginal();
//v2.24,将模版变量的比对,改为模版页面
TemplatePageListVO tplVO = templateService.getTemplatePageListByCache(request);
if(tplVO == null || tplVO.getList().size() == 0){
vo.setBaseVO(BaseVO.FAILURE, "当前网站尚未选择/导入/增加模版,生成失败!网站有模版后才能根据模版生成整站!");
return vo;
}
//v4.7加入,避免没有模版变量时,生成整站报错
if(Func.getUserBeanForShiroSession().getTemplateVarMapForOriginal() == null){
Func.getUserBeanForShiroSession().setTemplateVarMapForOriginal(new HashMap<String, TemplateVarVO>());
}
for (Map.Entry<String, TemplateVarVO> entry : Func.getUserBeanForShiroSession().getTemplateVarMapForOriginal().entrySet()) {
//替换公共标签
String v = template.replacePublicTag(entry.getValue().getTemplateVarData().getText());
//替换栏目的动态调用标签
v = template.replaceSiteColumnBlock(v, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
Func.getUserBeanForShiroSession().getTemplateVarCompileDataMap().put(entry.getKey(), v);
}
/*
* 进行第二步,对列表页模版、详情页模版进行通用标签等的替换,将其处理好。等生成的时候,直接取出来替换news、column即可
*/
TemplatePageListVO tpl = templateService.getTemplatePageListByCache(request); //取缓存中的模版页列表
Map<String, String> templateCacheMap = new HashMap<String, String>(); //替换好通用标签等的模版都缓存入此。Map<templatePage.name, templatePageData.text>
for (int i = 0; i < tpl.getList().size(); i++) {
TemplatePageVO tpVO = tpl.getList().get(i);
String text = null; //模版页内容
if(tpVO.getTemplatePageData() == null){
//若缓存中没有缓存上模版页详情,那么从数据库中挨个取出来(暂时先这么做,反正RDS剩余。后续将执行单挑SQL将所有页面一块拿出来再分配)(并且取出来后,要加入缓存,之后在点击生成整站,就不用再去数据库取了)
TemplatePageData tpd = sqlDAO.findById(TemplatePageData.class, tpVO.getTemplatePage().getId());
if(tpd != null){
text = tpd.getText();
}
}else{
text = tpVO.getTemplatePageData().getText();
}
if(text == null){
vo.setBaseVO(BaseVO.FAILURE, "模版页"+tpVO.getTemplatePage().getName()+"的内容不存在!请先检查此模版页");
return vo;
}
//进行2.1、2.2、2.3预操作
//替换公共标签
text = template.replacePublicTag(text);
//替换栏目的动态调用标签
text = template.replaceSiteColumnBlock(text, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
//装载模版变量
text = template.assemblyTemplateVar(text);
//预处理后,将其缓存入Map,等待生成页面时直接获取
templateCacheMap.put(tpVO.getTemplatePage().getName(), text);
}
//最后还要将获得到的内容缓存入Session,下次就不用去数据库取了
//生成首页
String indexHtml = templateCacheMap.get(templatePageIndexVO.getTemplatePage().getName());
//替换首页中存在的栏目的动态调用标签
indexHtml = template.replaceSiteColumnBlock(indexHtml, columnNewsMap, columnMap, columnTreeMap, true, null, newsDataMap);
indexHtml = template.replacePublicTag(indexHtml); //替换公共标签
//生成首页保存到OSS或本地盘
AttachmentFile.putStringFile("site/"+site.getId()+"/index.html", indexHtml);
/*
* 生成栏目、内容页面
*/
//遍历出所有列表栏目
for (SiteColumn siteColumn : columnMap.values()) {
if(siteColumn.getCodeName() == null || siteColumn.getCodeName().length() == 0){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]的“栏目代码”不存在,请先为其设置栏目代码");
return vo;
}
//取得当前栏目下的News列表
List<News> columnNewsList = columnNewsMap.get(siteColumn.getCodeName());
//获取当前栏目的内容页模版
String viewTemplateHtml = templateCacheMap.get(siteColumn.getTemplatePageViewName());
if(viewTemplateHtml == null){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]未绑定页面内容模版,请去绑定");
return vo;
}
//替换内容模版中的动态栏目调用(动态标签引用)
viewTemplateHtml = template.replaceSiteColumnBlock(viewTemplateHtml, columnNewsMap, columnMap, columnTreeMap, false, siteColumn, newsDataMap);
//如果是新闻或者图文列表,那么才会生成栏目列表页面
if(siteColumn.getType() - SiteColumn.TYPE_LIST == 0 || siteColumn.getType() - SiteColumn.TYPE_NEWS == 0 || siteColumn.getType() - SiteColumn.TYPE_IMAGENEWS == 0){
//当前栏目的列表模版
String listTemplateHtml = templateCacheMap.get(siteColumn.getTemplatePageListName());
if(listTemplateHtml == null){
vo.setBaseVO(BaseVO.FAILURE, "栏目["+siteColumn.getName()+"]未绑定模版列表页面,请去绑定");
return vo;
}
//替换列表模版中的动态栏目调用(动态标签引用)
listTemplateHtml = template.replaceSiteColumnBlock(listTemplateHtml, columnNewsMap, columnMap, columnTreeMap, false, siteColumn, newsDataMap);
//生成其列表页面
template.generateListHtmlForWholeSite(listTemplateHtml, siteColumn, columnNewsList, newsDataMap);
//XML加入栏目页面
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateSiteColumnListPageHtmlName(siteColumn, 1)+".html", "0.4");
/*
* 生成当前栏目的内容页面
*/
//判断栏目属性中,是否设置了生成内容详情页面, v4.7增加
if(siteColumn.getUseGenerateView() == null || siteColumn.getUseGenerateView() - SiteColumn.USED_ENABLE == 0){
for (int i = 0; i < columnNewsList.size(); i++) {
News news = columnNewsList.get(i);
if(siteColumn.getId() - news.getCid() == 0){
//当前文章是此栏目的,那么生成文章详情。不然是不生成的,免得在父栏目中生成子栏目的页面,导致siteColumn调用出现错误
//列表页的内容详情页面,还会有上一篇、下一篇的功能
News upNews = null;
News nextNews = null;
if(i > 0){
upNews = columnNewsList.get(i-1);
}
if((i+1) < columnNewsList.size()){
nextNews = columnNewsList.get(i+1);
}
//生成内容页面
template.generateViewHtmlForTemplateForWholeSite(news, siteColumn, newsDataMap.get(news.getId()), viewTemplateHtml, upNews, nextNews);
//XML加入内容页面
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, news)+".html", "0.5");
}
}
}
}else if(siteColumn.getType() - SiteColumn.TYPE_ALONEPAGE == 0 || siteColumn.getType() - SiteColumn.TYPE_PAGE == 0){
//独立页面,只生成内容模版
if(siteColumn.getEditMode() - SiteColumn.EDIT_MODE_TEMPLATE == 0){
//模版式编辑,无 news , 则直接生成
template.generateViewHtmlForTemplateForWholeSite(null, siteColumn, new NewsDataBean(null), viewTemplateHtml, null, null);
//独立页面享有更大的权重,赋予其 0.8
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, null)+".html", "0.8");
}else{
//UEditor、输入模型编辑方式
for (int i = 0; i < columnNewsList.size(); i++) {
News news = columnNewsList.get(i);
template.generateViewHtmlForTemplateForWholeSite(news, siteColumn, newsDataMap.get(news.getId()), viewTemplateHtml, null, null);
//独立页面享有更大的权重,赋予其 0.8
xml = xml + getSitemapUrl(indexUrl+"/"+template.generateNewsPageHtmlName(siteColumn, news)+".html", "0.8");
}
}
}else{
//其他栏目不管,当然,也没有其他类型栏目了,v4.6版本更新后,CMS模式一共就这两种类型的
}
}
//生成 sitemap.xml
xml = xml + "</urlset>";
AttachmentFile.putStringFile("site/"+site.getId()+"/sitemap.xml", xml);
return new BaseVO();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping(value="uploadImportTemplate${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public void uploadImportTemplate(HttpServletResponse response, HttpServletRequest request,
@RequestParam("templateFile") MultipartFile multipartFile){
if(multipartFile == null){
responseJson(response, BaseVO.FAILURE, "请选择要导入的模版");
return;
}
String wscsoTemplateText = null; //wscso后缀的模版文件
//判断导入的模版文件格式,是wscso还是zip格式
//判断一下上传文件大小
int lengthKB = 0;
try {
lengthKB = (int) Math.ceil(multipartFile.getInputStream().available()/1024);
} catch (IOException e1) {
e1.printStackTrace();
responseJson(response, BaseVO.FAILURE, "未获取到所导入的文件大小");
return;
}
//获取上传的文件的后缀
String fileSuffix = Lang.findFileSuffix(multipartFile.getOriginalFilename()).toLowerCase();
if(fileSuffix.equals("wscso")){
//wscso的限制在配置文件applilcation.properties的大小以内
if(lengthKB > AttachmentFile.getMaxFileSizeKB()){
//超过
responseJson(response, BaseVO.FAILURE, "纯模版文件最大限制"+AttachmentFile.getMaxFileSizeKB()+"KB以内");
return;
}
try {
wscsoTemplateText = StringUtil.inputStreamToString(multipartFile.getInputStream(), "UTF-8");
} catch (IOException e) {
Log.error("获取到的,导入模版没有内容");
e.printStackTrace();
responseJson(response, BaseVO.FAILURE, "所获取到所导入的模版未发现模版内容");
return;
}
}else if (fileSuffix.equals("zip")) {
//上传的是模版文件,包含素材,将其上传到服务器本地 , v4.7 增加
//zip的限制在50MB以内
if(lengthKB > 50*1025){
//超过50MB
responseJson(response, BaseVO.FAILURE, "最大限制50MB以内");
return;
}
String fileName = DateUtil.timeForUnix13()+"_"+StringUtil.getRandom09AZ(20);
File file = new File(TemplateTemporaryFolder.folderPath+fileName+".zip");
try {
multipartFile.transferTo(file);
} catch (IllegalStateException | IOException e1) {
e1.printStackTrace();
responseJson(response, BaseVO.FAILURE, e1.getMessage());
return;
}
//将其解压到同文件夹中
try {
ZipUtil.unzip(TemplateTemporaryFolder.folderPath+fileName+".zip",TemplateTemporaryFolder.folderPath+fileName+"/");
} catch (IOException e) {
e.printStackTrace();
}
//既然已经解压出来了,那么删除掉zip文件
file.delete();
//判断一下解压出来的文件中,是否存在 template.wscso 这个模版文件
File wscsoFile = new File(TemplateTemporaryFolder.folderPath+fileName+"/template.wscso");
if(wscsoFile.exists()){
wscsoTemplateText = FileUtil.read(wscsoFile, FileUtil.UTF8);
}else{
//不存在,那就报错吧
responseJson(response, BaseVO.FAILURE, "template.wscso模版文件未发现!");
return;
}
TemplateVO tvo = new TemplateVO();
//导入JSON,生成对象
tvo.importText(FileUtil.read(TemplateTemporaryFolder.folderPath+fileName+"/template.wscso", FileUtil.UTF8));
//v4.7版本以后,导出的都会有 tvo.template 对象
String templateName = tvo.getTemplate().getName();
//判断数据库中,是否已经有这个模版了
com.xnx3.wangmarket.admin.entity.Template template = sqlService.findAloneByProperty(com.xnx3.wangmarket.admin.entity.Template.class, "name", templateName);
if(template == null){
//为空,没有这个模版,这个是正常的,可以将模版资源文件导入
//将zip解压出来的文件,进行过滤,过滤掉不合法的后缀文件,将合法的文件后缀转移到新建立的模版文件夹中去
new TemplateUtil(templateName, new TemplateUtilFileMove() {
public void move(String path, InputStream inputStream) {
AttachmentFile.put(path, inputStream);
}
}).filterTemplateFile(new File(TemplateTemporaryFolder.folderPath+fileName+"/"));
//将这个模版模版信息记录入数据库
template = tvo.getTemplate();
template.setIscommon(com.xnx3.wangmarket.admin.entity.Template.ISCOMMON_NO); //用户自己导入的,默认是私有的,不加入公共模版库。除非通过模版中心来指定(模版中心属于授权版本)
template.setUserid(getUserId());
sqlService.save(template);
}else{
//不为空,已经有这个模版了,那么就不可以导入资源文件,只导入 wscso 文件就可以了
System.out.println("已经有这个模版的资源文件了,忽略:"+template.getName());
}
}
//将 wscso 模版文件导入
BaseVO vo = templateService.importTemplate(wscsoTemplateText, true, request);
if(vo.getResult() - BaseVO.SUCCESS == 0){
AliyunLog.addActionLog(getSiteId(), "本地导入模版文件成功!");
}else{
AliyunLog.addActionLog(getSiteId(), "本地导入模版文件失败!");
}
responseJson(response, vo.getResult(), vo.getInfo());
}
#location 82
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequestMapping(value="uploadImportTemplate${url.suffix}", method = RequestMethod.POST)
@ResponseBody
public void uploadImportTemplate(HttpServletResponse response, HttpServletRequest request,
@RequestParam("templateFile") MultipartFile multipartFile){
if(multipartFile == null){
responseJson(response, BaseVO.FAILURE, "请选择要导入的模版");
return;
}
String wscsoTemplateText = null; //wscso后缀的模版文件
//判断导入的模版文件格式,是wscso还是zip格式
//判断一下上传文件大小
int lengthKB = 0;
try {
lengthKB = (int) Math.ceil(multipartFile.getInputStream().available()/1024);
} catch (IOException e1) {
e1.printStackTrace();
responseJson(response, BaseVO.FAILURE, "未获取到所导入的文件大小");
return;
}
//获取上传的文件的后缀
String fileSuffix = Lang.findFileSuffix(multipartFile.getOriginalFilename()).toLowerCase();
if(fileSuffix.equals("wscso")){
//wscso的限制在配置文件applilcation.properties的大小以内
if(lengthKB > AttachmentFile.getMaxFileSizeKB()){
//超过
responseJson(response, BaseVO.FAILURE, "纯模版文件最大限制"+AttachmentFile.getMaxFileSizeKB()+"KB以内");
return;
}
try {
wscsoTemplateText = StringUtil.inputStreamToString(multipartFile.getInputStream(), "UTF-8");
} catch (IOException e) {
Log.error("获取到的,导入模版没有内容");
e.printStackTrace();
responseJson(response, BaseVO.FAILURE, "所获取到所导入的模版未发现模版内容");
return;
}
}else if (fileSuffix.equals("zip")) {
//v4.9增加,禁止zip模版通过此处上传。统一通过总管理后台-功能插件-模版库进行导入
if(true){
responseJson(response, BaseVO.FAILURE, "已禁止上传zip格式模版!您可通过总管理后台-功能插件-模版库进行导入");
return;
}
//上传的是模版文件,包含素材,将其上传到服务器本地 , v4.7 增加
//zip的限制在50MB以内
if(lengthKB > 50*1025){
//超过50MB
responseJson(response, BaseVO.FAILURE, "最大限制50MB以内");
return;
}
String fileName = DateUtil.timeForUnix13()+"_"+StringUtil.getRandom09AZ(20);
File file = new File(TemplateTemporaryFolder.folderPath+fileName+".zip");
try {
multipartFile.transferTo(file);
} catch (IllegalStateException | IOException e1) {
e1.printStackTrace();
responseJson(response, BaseVO.FAILURE, e1.getMessage());
return;
}
//将其解压到同文件夹中
try {
ZipUtil.unzip(TemplateTemporaryFolder.folderPath+fileName+".zip",TemplateTemporaryFolder.folderPath+fileName+"/");
} catch (IOException e) {
e.printStackTrace();
}
//既然已经解压出来了,那么删除掉zip文件
file.delete();
//判断一下解压出来的文件中,是否存在 template.wscso 这个模版文件
File wscsoFile = new File(TemplateTemporaryFolder.folderPath+fileName+"/template.wscso");
if(wscsoFile.exists()){
wscsoTemplateText = FileUtil.read(wscsoFile, FileUtil.UTF8);
}else{
//不存在,那就报错吧
responseJson(response, BaseVO.FAILURE, "template.wscso模版文件未发现!");
return;
}
TemplateVO tvo = new TemplateVO();
//导入JSON,生成对象
tvo.importText(FileUtil.read(TemplateTemporaryFolder.folderPath+fileName+"/template.wscso", FileUtil.UTF8));
//v4.7版本以后,导出的都会有 tvo.template 对象
String templateName = tvo.getTemplate().getName();
//判断数据库中,是否已经有这个模版了
com.xnx3.wangmarket.admin.entity.Template template = sqlService.findAloneByProperty(com.xnx3.wangmarket.admin.entity.Template.class, "name", templateName);
if(template == null){
//为空,没有这个模版,这个是正常的,可以将模版资源文件导入
//将zip解压出来的文件,进行过滤,过滤掉不合法的后缀文件,将合法的文件后缀转移到新建立的模版文件夹中去
new TemplateUtil(templateName, new TemplateUtilFileMove() {
public void move(String path, InputStream inputStream) {
AttachmentFile.put(path, inputStream);
}
}).filterTemplateFile(new File(TemplateTemporaryFolder.folderPath+fileName+"/"));
//将这个模版模版信息记录入数据库
template = tvo.getTemplate();
template.setIscommon(com.xnx3.wangmarket.admin.entity.Template.ISCOMMON_NO); //用户自己导入的,默认是私有的,不加入公共模版库。除非通过模版中心来指定(模版中心属于授权版本)
template.setUserid(getUserId());
sqlService.save(template);
}else{
//不为空,已经有这个模版了,那么就不可以导入资源文件,只导入 wscso 文件就可以了
System.out.println("已经有这个模版的资源文件了,忽略:"+template.getName());
}
}
//将 wscso 模版文件导入
BaseVO vo = templateService.importTemplate(wscsoTemplateText, true, request);
if(vo.getResult() - BaseVO.SUCCESS == 0){
AliyunLog.addActionLog(getSiteId(), "本地导入模版文件成功!");
}else{
AliyunLog.addActionLog(getSiteId(), "本地导入模版文件失败!");
}
responseJson(response, vo.getResult(), vo.getInfo());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static UploadFileVO put(String path,InputStream inputStream){
UploadFileVO vo = new UploadFileVO();
if(isMode(MODE_ALIYUN_OSS)){
PutResult pr = OSSUtil.put(path, inputStream);
vo = PutResultToUploadFileVO(pr);
}else if(isMode(MODE_LOCAL_FILE)){
directoryInit(path);
File file = new File(localFilePath+path);
OutputStream os;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
inputStream.close();
vo.setFileName(file.getName());
vo.setInfo("success");
vo.setPath(path);
vo.setUrl(AttachmentFile.netUrl()+path);
} catch (IOException e) {
e.printStackTrace();
}
}
return vo;
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
public static UploadFileVO put(String path,InputStream inputStream){
UploadFileVO vo = new UploadFileVO();
//判断文件大小是否超出最大限制的大小
int lengthKB = 0;
try {
lengthKB = (int) Math.ceil(inputStream.available()/1024);
} catch (IOException e) {
e.printStackTrace();
}
vo = verifyFileMaxLength(lengthKB);
if(vo.getResult() - UploadFileVO.FAILURE == 0){
return vo;
}
vo.setSize(lengthKB);
if(isMode(MODE_ALIYUN_OSS)){
PutResult pr = OSSUtil.put(path, inputStream);
vo = PutResultToUploadFileVO(pr);
}else if(isMode(MODE_LOCAL_FILE)){
directoryInit(path);
File file = new File(localFilePath+path);
OutputStream os;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
inputStream.close();
vo.setFileName(file.getName());
vo.setInfo("success");
vo.setPath(path);
vo.setUrl(AttachmentFile.netUrl()+path);
} catch (IOException e) {
e.printStackTrace();
}
}
return vo;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void connect() throws IOException, InterruptedException,
ServiceLocatorException {
connect(false);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void connect() throws IOException, InterruptedException,
ServiceLocatorException {
try {
synchronized (this) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Start connect session");
}
blockedByRunUpOperation = true;
connect(false);
blockedByRunUpOperation = false;
if (LOG.isLoggable(Level.FINER)) {
LOG.log(Level.FINER, "End connect session");
}
}
} catch (IOException e) {
blockedByRunUpOperation = false;
throw e;
} catch (InterruptedException e) {
blockedByRunUpOperation = false;
throw e;
} catch (ServiceLocatorException e) {
blockedByRunUpOperation = false;
throw e;
} catch (Exception e) {
blockedByRunUpOperation = false;
if (LOG.isLoggable(Level.SEVERE)) {
LOG.log(Level.SEVERE, "Connect not passed: " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void disconnect() throws InterruptedException,
ServiceLocatorException {
disconnect(true, false);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void disconnect() throws InterruptedException,
ServiceLocatorException {
try {
synchronized (this) {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "Start disconnect session");
}
blockedByRunUpOperation = true;
disconnect(false);
blockedByRunUpOperation = false;
if (LOG.isLoggable(Level.FINER)) {
LOG.log(Level.FINER, "End disconnect session");
}
}
} catch (InterruptedException e) {
blockedByRunUpOperation = false;
throw e;
} catch (ServiceLocatorException e) {
blockedByRunUpOperation = false;
throw e;
} catch (Exception e) {
blockedByRunUpOperation = false;
if (LOG.isLoggable(Level.SEVERE)) {
LOG.log(Level.SEVERE, "Connect not passed: " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Keyspace keyspace()
{
if (keyspace != null)
return keyspace;
synchronized (AstyanaxConnection.class)
{
// double check...
if (keyspace != null)
return keyspace;
try
{
File propFile = new File("cassandra.properties");
if (propFile.exists())
config.load(new FileReader(propFile));
AstyanaxConfigurationImpl configuration = new AstyanaxConfigurationImpl();
configuration.setDiscoveryType(NodeDiscoveryType.valueOf(config.getProperty("astyanax.connection.discovery", "NONE")));
configuration.setConnectionPoolType(ConnectionPoolType.valueOf(config.getProperty("astyanax.connection.pool", "ROUND_ROBIN")));
configuration.setDefaultReadConsistencyLevel(ConsistencyLevel.valueOf(com.netflix.jmeter.properties.Properties.instance.cassandra.getReadConsistency()));
configuration.setDefaultWriteConsistencyLevel(ConsistencyLevel.valueOf(com.netflix.jmeter.properties.Properties.instance.cassandra.getWriteConsistency()));
logger.info("AstyanaxConfiguration: " + configuration.toString());
String property = config.getProperty("astyanax.connection.latency.stategy", "EmptyLatencyScoreStrategyImpl");
LatencyScoreStrategy latencyScoreStrategy = null;
if (property.equalsIgnoreCase("SmaLatencyScoreStrategyImpl"))
{
int updateInterval = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.updateInterval", "2000"));
int resetInterval = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.resetInterval", "10000"));
int windowSize = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.windowSize", "100"));
double badnessThreshold = Double.parseDouble(config.getProperty("astyanax.connection.latency.stategy.badnessThreshold", "0.1"));
// latencyScoreStrategy = new SmaLatencyScoreStrategyImpl(updateInterval, resetInterval, windowSize, badnessThreshold);
}
else
{
latencyScoreStrategy = new EmptyLatencyScoreStrategyImpl();
}
String maxConnection = com.netflix.jmeter.properties.Properties.instance.cassandra.getMaxConnsPerHost();
ConnectionPoolConfigurationImpl poolConfig = new ConnectionPoolConfigurationImpl(getClusterName()).setPort(port);
poolConfig.setMaxConnsPerHost(Integer.parseInt(maxConnection));
poolConfig.setSeeds(StringUtils.join(endpoints, ":" + port + ","));
poolConfig.setLatencyScoreStrategy(latencyScoreStrategy);
logger.info("ConnectionPoolConfiguration: " + poolConfig.toString());
// set this as field for logging purpose only.
Builder builder = new AstyanaxContext.Builder();
builder.forCluster(getClusterName());
builder.forKeyspace(getKeyspaceName());
builder.withAstyanaxConfiguration(configuration);
builder.withConnectionPoolConfiguration(poolConfig);
builder.withConnectionPoolMonitor(connectionPoolMonitor);
builder.withConnectionPoolMonitor(new CountingConnectionPoolMonitor());
AstyanaxContext<Keyspace> context = builder.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
keyspace = context.getEntity();
return keyspace;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Keyspace keyspace()
{
if (keyspace != null)
return keyspace;
synchronized (AstyanaxConnection.class)
{
// double check...
if (keyspace != null)
return keyspace;
try
{
File propFile = new File("cassandra.properties");
if (propFile.exists())
config.load(new FileReader(propFile));
AstyanaxConfigurationImpl configuration = new AstyanaxConfigurationImpl();
configuration.setDiscoveryType(NodeDiscoveryType.valueOf(config.getProperty("astyanax.connection.discovery", "NONE")));
configuration.setConnectionPoolType(ConnectionPoolType.valueOf(config.getProperty("astyanax.connection.pool", "ROUND_ROBIN")));
configuration.setDefaultReadConsistencyLevel(ConsistencyLevel.valueOf(com.netflix.jmeter.properties.Properties.instance.cassandra.getReadConsistency()));
configuration.setDefaultWriteConsistencyLevel(ConsistencyLevel.valueOf(com.netflix.jmeter.properties.Properties.instance.cassandra.getWriteConsistency()));
logger.info("AstyanaxConfiguration: " + configuration.toString());
String property = config.getProperty("astyanax.connection.latency.stategy", "EmptyLatencyScoreStrategyImpl");
LatencyScoreStrategy latencyScoreStrategy = null;
if (property.equalsIgnoreCase("SmaLatencyScoreStrategyImpl"))
{
int updateInterval = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.updateInterval", "2000"));
int resetInterval = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.resetInterval", "10000"));
int windowSize = Integer.parseInt(config.getProperty("astyanax.connection.latency.stategy.windowSize", "100"));
double badnessThreshold = Double.parseDouble(config.getProperty("astyanax.connection.latency.stategy.badnessThreshold", "0.1"));
// latencyScoreStrategy = new SmaLatencyScoreStrategyImpl(updateInterval, resetInterval, windowSize, badnessThreshold);
}
else
{
latencyScoreStrategy = new EmptyLatencyScoreStrategyImpl();
}
String maxConnection = com.netflix.jmeter.properties.Properties.instance.cassandra.getMaxConnsPerHost();
ConnectionPoolConfigurationImpl poolConfig = new ConnectionPoolConfigurationImpl(getClusterName()).setPort(port);
poolConfig.setMaxConnsPerHost(Integer.parseInt(maxConnection));
poolConfig.setSeeds(StringUtils.join(endpoints, ":" + port + ","));
poolConfig.setLatencyScoreStrategy(latencyScoreStrategy);
logger.info("ConnectionPoolConfiguration: " + poolConfig.toString());
ConnectionPoolMonitor connectionPoolMonitor = new CountingConnectionPoolMonitor();
// set this as field for logging purpose only.
Builder builder = new AstyanaxContext.Builder();
builder.forCluster(getClusterName());
builder.forKeyspace(getKeyspaceName());
builder.withAstyanaxConfiguration(configuration);
builder.withConnectionPoolConfiguration(poolConfig);
builder.withConnectionPoolMonitor(connectionPoolMonitor);
builder.withConnectionPoolMonitor(new CountingConnectionPoolMonitor());
context = builder.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
keyspace = context.getEntity();
return keyspace;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReframe() throws Exception {
final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder());
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
// Request a frame with margin in anticipation of a larger payload...
// ... but write a smaller payload
final ByteBuf content = copiedBuffer("hello world", UTF_8);
writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate());
// And rewrite the frame accordingly
writer.reframe(content.readableBytes(), false);
// Verify that the message can be parsed
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
// Write and verify another message
final ByteBuf next = copiedBuffer("next", UTF_8);
writer.frame(next.readableBytes(), false).writeBytes(next.duplicate());
out.clear();
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(next)));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReframe() throws Exception {
final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder());
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
// Request a frame with margin in anticipation of a larger payload...
// ... but write a smaller payload
final ByteBuf content = copiedBuffer("hello world", UTF_8);
writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate());
// And rewrite the frame accordingly
writer.reframe(content.readableBytes(), false);
// Verify that the message can be parsed
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
// Write and verify another message
final ByteBuf next = copiedBuffer("next", UTF_8);
writer.frame(next.readableBytes(), false).writeBytes(next.duplicate());
out.clear();
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(next)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSingleFrame() throws Exception {
final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder();
final ByteBuf content = Unpooled.copiedBuffer("hello", UTF_8);
final List<Object> out = Lists.newArrayList();
decoder.header(content.readableBytes(), false, out);
decoder.content(content, out);
decoder.finish(out);
final Object expected = new ZMTPIncomingMessage(fromUTF8(ALLOC, "hello"), false, 5);
assertThat(out, hasSize(1));
assertThat(out, contains(expected));
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSingleFrame() throws Exception {
final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder();
final ByteBuf content = Unpooled.copiedBuffer("hello", UTF_8);
final List<Object> out = Lists.newArrayList();
decoder.header(content.readableBytes(), false, out);
decoder.content(content, out);
decoder.finish(out);
final Object expected = ZMTPMessage.fromUTF8(ALLOC, "hello");
assertThat(out, hasSize(1));
assertThat(out, contains(expected));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testOneFrame() throws Exception {
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
ByteBuf frame = writer.frame(11, false);
assertThat(frame, is(sameInstance(buf)));
final ByteBuf content = copiedBuffer("hello world", UTF_8);
frame.writeBytes(content.duplicate());
final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder());
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testOneFrame() throws Exception {
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
ByteBuf frame = writer.frame(11, false);
assertThat(frame, is(sameInstance(buf)));
final ByteBuf content = copiedBuffer("hello world", UTF_8);
frame.writeBytes(content.duplicate());
final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder());
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReframe() throws Exception {
final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder());
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
// Request a frame with margin in anticipation of a larger payload...
// ... but write a smaller payload
final ByteBuf content = copiedBuffer("hello world", UTF_8);
writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate());
// And rewrite the frame accordingly
writer.reframe(content.readableBytes(), false);
// Verify that the message can be parsed
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
// Write and verify another message
final ByteBuf next = copiedBuffer("next", UTF_8);
writer.frame(next.readableBytes(), false).writeBytes(next.duplicate());
out.clear();
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(next)));
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReframe() throws Exception {
final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder());
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
// Request a frame with margin in anticipation of a larger payload...
// ... but write a smaller payload
final ByteBuf content = copiedBuffer("hello world", UTF_8);
writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate());
// And rewrite the frame accordingly
writer.reframe(content.readableBytes(), false);
// Verify that the message can be parsed
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(content)));
// Write and verify another message
final ByteBuf next = copiedBuffer("next", UTF_8);
writer.frame(next.readableBytes(), false).writeBytes(next.duplicate());
out.clear();
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) singletonList(next)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTwoFrames() throws Exception {
final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder();
final ByteBuf f0 = Unpooled.copiedBuffer("hello", UTF_8);
final ByteBuf f1 = Unpooled.copiedBuffer("world", UTF_8);
final List<Object> out = Lists.newArrayList();
decoder.header(f0.readableBytes(), true, out);
decoder.content(f0, out);
decoder.header(f1.readableBytes(), false, out);
decoder.content(f1, out);
decoder.finish(out);
final Object expected = new ZMTPIncomingMessage(fromUTF8(ALLOC, "hello", "world"), false, 10);
assertThat(out, hasSize(1));
assertThat(out, contains(expected));
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTwoFrames() throws Exception {
final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder();
final ByteBuf f0 = Unpooled.copiedBuffer("hello", UTF_8);
final ByteBuf f1 = Unpooled.copiedBuffer("world", UTF_8);
final List<Object> out = Lists.newArrayList();
decoder.header(f0.readableBytes(), true, out);
decoder.content(f0, out);
decoder.header(f1.readableBytes(), false, out);
decoder.content(f1, out);
decoder.finish(out);
final Object expected = ZMTPMessage.fromUTF8(ALLOC, "hello", "world");
assertThat(out, hasSize(1));
assertThat(out, contains(expected));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTwoFrames() throws Exception {
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
final ByteBuf f0 = copiedBuffer("hello ", UTF_8);
final ByteBuf f1 = copiedBuffer("hello ", UTF_8);
writer.frame(f0.readableBytes(), true).writeBytes(f0.duplicate());
writer.frame(f1.readableBytes(), false).writeBytes(f1.duplicate());
final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder());
parser.parse(buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) asList(f0, f1)));
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTwoFrames() throws Exception {
final ZMTPWriter writer = ZMTPWriter.create(ZMTP10);
final ByteBuf buf = Unpooled.buffer();
writer.reset(buf);
final ByteBuf f0 = copiedBuffer("hello ", UTF_8);
final ByteBuf f1 = copiedBuffer("hello ", UTF_8);
writer.frame(f0.readableBytes(), true).writeBytes(f0.duplicate());
writer.frame(f1.readableBytes(), false).writeBytes(f1.duplicate());
final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder());
decoder.decode(null, buf, out);
assertThat(out, hasSize(1));
assertThat(out, contains((Object) asList(f0, f1)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public final Cache buildCache(String name) throws CacheException {
if (log.isDebugEnabled()) {
log.debug("Loading a new EhCache cache named [" + name + "]");
}
try {
net.sf.ehcache.Cache cache = getCacheManager().getCache(name);
if (cache == null) {
if (log.isWarnEnabled()) {
log.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults.");
}
if ( name.equals(DEFAULT_ACTIVE_SESSIONS_CACHE_NAME) ) {
if ( log.isInfoEnabled() ) {
log.info("Creating " + DEFAULT_ACTIVE_SESSIONS_CACHE_NAME + " cache with default JSecurity " +
"session cache settings." );
}
cache = buildDefaultActiveSessionsCache();
manager.addCache( cache );
} else {
manager.addCache( name );
cache = manager.getCache( name );
}
cache.initialise();
if (log.isDebugEnabled()) {
log.debug("Started EHCache named [" + name + "]");
}
}
return new EhCache(cache);
} catch (net.sf.ehcache.CacheException e) {
throw new CacheException(e);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
public final Cache buildCache(String name) throws CacheException {
if (log.isDebugEnabled()) {
log.debug("Loading a new EhCache cache named [" + name + "]");
}
try {
net.sf.ehcache.Cache cache = getCacheManager().getCache(name);
if (cache == null) {
if (log.isWarnEnabled()) {
log.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults.");
}
if ( name.equals(DEFAULT_ACTIVE_SESSIONS_CACHE_NAME) ) {
if ( log.isInfoEnabled() ) {
log.info("Creating " + DEFAULT_ACTIVE_SESSIONS_CACHE_NAME + " cache with default JSecurity " +
"session cache settings." );
}
cache = buildDefaultActiveSessionsCache();
manager.addCache( cache );
} else {
manager.addCache( name );
cache = manager.getCache( name );
}
if (log.isDebugEnabled()) {
log.debug("Started EHCache named [" + name + "]");
}
}
return new EhCache(cache);
} catch (net.sf.ehcache.CacheException e) {
throw new CacheException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void bindPrincipalsToSessionIfNecessary( HttpServletRequest request ) {
SecurityContext ctx = (SecurityContext) ThreadContext.get( ThreadContext.SECURITY_CONTEXT_KEY );
if ( ctx != null ) {
Session session = ThreadLocalSecurityContext.current().getSession( false );
if( session != null && session.getAttribute( PRINCIPALS_SESSION_KEY) == null ) {
session.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() );
} else {
HttpSession httpSession = request.getSession();
if( httpSession.getAttribute( PRINCIPALS_SESSION_KEY ) == null ) {
httpSession.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() );
}
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void bindPrincipalsToSessionIfNecessary( HttpServletRequest request ) {
SecurityContext ctx = (SecurityContext) ThreadContext.get( ThreadContext.SECURITY_CONTEXT_KEY );
if ( ctx != null ) {
Session session = ThreadLocalSecurityContext.current().getSession();
if( session != null && session.getAttribute( PRINCIPALS_SESSION_KEY) == null ) {
session.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() );
} else {
HttpSession httpSession = request.getSession();
if( httpSession.getAttribute( PRINCIPALS_SESSION_KEY ) == null ) {
httpSession.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int onDoStartTag() throws JspException {
if ( getSecurityContext().isAuthenticated() ) {
return TagSupport.EVAL_BODY_INCLUDE;
} else {
return TagSupport.SKIP_BODY;
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public int onDoStartTag() throws JspException {
if ( getSecurityContext() != null && getSecurityContext().isAuthenticated() ) {
return TagSupport.EVAL_BODY_INCLUDE;
} else {
return TagSupport.SKIP_BODY;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void create( Session session ) {
assignId( session );
Serializable id = session.getSessionId();
if ( id == null ) {
String msg = "session must be assigned an id. Please check assignId( Session s ) " +
"implementation.";
throw new IllegalStateException( msg );
}
if ( activeSessions.containsKey( id ) || stoppedSessions.containsKey( id ) ) {
String msg = "There is an existing session already created with session id [" +
id + "]. Session Id's must be unique.";
throw new IllegalArgumentException( msg );
}
synchronized ( activeSessions ) {
activeSessions.put( id, session );
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void create( Session session ) {
Serializable id = session.getSessionId();
if ( id == null ) {
String msg = "session must be assigned an id. Please check assignId( Session s ) " +
"implementation.";
throw new IllegalStateException( msg );
}
if ( activeSessions.containsKey( id ) || stoppedSessions.containsKey( id ) ) {
String msg = "There is an existing session already created with session id [" +
id + "]. Session Id's must be unique.";
throw new IllegalArgumentException( msg );
}
synchronized ( activeSessions ) {
activeSessions.put( id, session );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int onDoStartTag() throws JspException {
String strValue = null;
if( getSecurityContext().isAuthenticated() ) {
// Get the principal to print out
Principal principal;
if( type == null ) {
principal = getSecurityContext().getPrincipal();
} else {
principal = getSecurityContext().getPrincipalByType( type );
}
// Get the string value of the principal
if( principal != null ) {
if( property == null ) {
strValue = principal.toString();
} else {
strValue = getPrincipalProperty( principal, property );
}
}
}
// Print out the principal value if not null
if( strValue != null ) {
try {
pageContext.getOut().write( strValue );
} catch (IOException e) {
throw new JspTagException( "Error writing [" + strValue + "] to JSP.", e );
}
}
return SKIP_BODY;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
public int onDoStartTag() throws JspException {
String strValue = null;
if( getSecurityContext() != null && getSecurityContext().isAuthenticated() ) {
// Get the principal to print out
Principal principal;
if( type == null ) {
principal = getSecurityContext().getPrincipal();
} else {
principal = getSecurityContext().getPrincipalByType( type );
}
// Get the string value of the principal
if( principal != null ) {
if( property == null ) {
strValue = principal.toString();
} else {
strValue = getPrincipalProperty( principal, property );
}
}
}
// Print out the principal value if not null
if( strValue != null ) {
try {
pageContext.getOut().write( strValue );
} catch (IOException e) {
throw new JspTagException( "Error writing [" + strValue + "] to JSP.", e );
}
}
return SKIP_BODY;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
Session session = ThreadLocalSecurityContext.current().getSession( false );
Serializable sessionId;
if( session != null ) {
sessionId = session.getSessionId();
} else {
sessionId = UUID.fromString( System.getProperty( "jsecurity.session.id" ) );
}
if( sessionId != null ) {
return new SecureRemoteInvocation( methodInvocation, sessionId );
} else {
return super.createRemoteInvocation( methodInvocation );
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
Session session = (Session) ThreadContext.get( ThreadContext.SESSION_KEY );
Serializable sessionId;
if( session != null ) {
sessionId = session.getSessionId();
} else {
sessionId = UUID.fromString( System.getProperty( "jsecurity.session.id" ) );
}
if( sessionId != null ) {
return new SecureRemoteInvocation( methodInvocation, sessionId );
} else {
return super.createRemoteInvocation( methodInvocation );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean showTagBody( Permission p ) {
boolean permitted = getSecurityContext().implies( p );
return !permitted;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean showTagBody( Permission p ) {
boolean permitted = getSecurityContext() != null && getSecurityContext().implies( p );
return !permitted;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean executeLogin(ServletRequest request, ServletResponse response) {
if (log.isDebugEnabled()) {
log.debug("Attempting to authenticate Subject based on Http BASIC Authentication request...");
}
HttpServletRequest httpRequest = toHttp(request);
String authorizationHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
if (authorizationHeader != null && authorizationHeader.length() > 0) {
if (log.isDebugEnabled()) {
log.debug("Executing login with headers [" + authorizationHeader + "]");
}
String[] authTokens = authorizationHeader.split(" ");
if (authTokens[0].trim().equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) {
String encodedCredentials = authTokens[1];
String decodedCredentials = Base64.decodeToString(encodedCredentials);
String[] credentials = decodedCredentials.split(":");
if (credentials != null && credentials.length > 1) {
if (log.isDebugEnabled()) {
log.debug("Processing login request [" + credentials[0] + "]");
}
Subject subject = getSubject(request, response);
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(credentials[0], credentials[1]);
try {
subject.login(usernamePasswordToken);
if (log.isDebugEnabled()) {
log.debug("Successfully logged in user [" + credentials[0] + "]");
}
return true;
} catch (AuthenticationException ae) {
if (log.isDebugEnabled()) {
log.debug("Unable to log in subject [" + credentials[0] + "]", ae);
}
}
}
}
}
//always default to false. If we've made it to this point in the code, that
//means the authentication attempt either never occured, or wasn't successful:
return false;
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean executeLogin(ServletRequest request, ServletResponse response) {
if (log.isDebugEnabled()) {
log.debug("Attempting to authenticate Subject based on Http BASIC Authentication request...");
}
String authorizationHeader = getAuthzHeader(request);
if (authorizationHeader == null || authorizationHeader.length() == 0 ) {
return false;
}
if (log.isDebugEnabled()) {
log.debug("Attempting to execute login with headers [" + authorizationHeader + "]");
}
String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request);
if ( prinCred == null || prinCred.length < 2 ) {
return false;
}
String username = prinCred[0];
String password = prinCred[1];
if (log.isDebugEnabled()) {
log.debug("Processing login request for username [" + username + "]");
}
AuthenticationToken token = createToken(username, password, request );
if ( token != null ) {
return executeLogin(token, request, response );
}
//always default to false. If we've made it to this point in the code, that
//means the authentication attempt either never occured, or wasn't successful:
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void send( AuthenticationEvent event ) {
if ( listeners != null && !listeners.isEmpty() ) {
synchronized ( listeners ) {
for ( AuthenticationEventListener ael : listeners ) {
if ( event instanceof SuccessfulAuthenticationEvent) {
ael.accountAuthenticated( event );
} else if ( event instanceof UnlockedAccountEvent) {
ael.accountUnlocked( event );
} else if ( event instanceof LogoutEvent) {
ael.accountLoggedOut( event );
} else if ( event instanceof FailedAuthenticationEvent) {
FailedAuthenticationEvent failedEvent = (FailedAuthenticationEvent)event;
AuthenticationException cause = failedEvent.getCause();
if ( cause != null && ( cause instanceof LockedAccountException ) ) {
ael.accountLocked( event );
} else {
ael.authenticationFailed( event );
}
} else {
String msg = "Received argument of type [" + event.getClass() + "]. This " +
"implementation can only send event instances of types " +
SuccessfulAuthenticationEvent.class.getName() + ", " +
FailedAuthenticationEvent.class.getName() + ", " +
UnlockedAccountEvent.class.getName() + ", or " +
LogoutEvent.class.getName();
throw new IllegalArgumentException( msg );
}
}
}
} else {
if ( log.isWarnEnabled() ) {
String msg = "internal listeners collection is null. No " +
"AuthenticationEventListeners will be notified of event [" +
event + "]";
log.warn( msg );
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void send( AuthenticationEvent event ) {
if ( listeners != null && !listeners.isEmpty() ) {
for ( AuthenticationEventListener ael : listeners ) {
ael.onEvent( event );
}
} else {
if ( log.isWarnEnabled() ) {
String msg = "internal listeners collection is null. No " +
"AuthenticationEventListeners will be notified of event [" +
event + "]";
log.warn( msg );
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
Set<String> roles = (Set<String>) mappedValue;
boolean hasRoles = true;
if (roles != null && !roles.isEmpty()) {
if (roles.size() == 1) {
if (!subject.hasRole(roles.iterator().next())) {
hasRoles = false;
}
} else {
if (!subject.hasAllRoles(roles)) {
hasRoles = false;
}
}
}
return hasRoles;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
String[] rolesArray = (String[]) mappedValue;
if (rolesArray == null || rolesArray.length == 0) {
//no roles specified, so nothing to check - allow access.
return true;
}
Set<String> roles = CollectionUtils.asSet(rolesArray);
return subject.hasAllRoles(roles);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean showTagBody( Permission p ) {
return getSecurityContext().implies( p );
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean showTagBody( Permission p ) {
return getSecurityContext() != null && getSecurityContext().implies( p );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void send( SessionEvent event ) {
synchronized( listeners ) {
for( SessionEventListener sel : listeners ) {
if ( event instanceof StartedSessionEvent) {
sel.sessionStarted( event );
} else if ( event instanceof ExpiredSessionEvent) {
sel.sessionExpired( event );
} else if ( event instanceof StoppedSessionEvent) {
sel.sessionStopped( event );
} else {
String msg = "Received argument of type [" + event.getClass() + "]. This " +
"implementation can only send event instances of types " +
StartedSessionEvent.class.getName() + ", " +
ExpiredSessionEvent.class.getName() + ", or " +
StoppedSessionEvent.class.getName();
throw new IllegalArgumentException( msg );
}
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void send( SessionEvent event ) {
if ( listeners != null && !listeners.isEmpty() ) {
for( SessionEventListener sel : listeners ) {
sel.onEvent( event );
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
Set<String> roles = (Set<String>) mappedValue;
boolean hasRoles = true;
if (roles != null && !roles.isEmpty()) {
if (roles.size() == 1) {
if (!subject.hasRole(roles.iterator().next())) {
hasRoles = false;
}
} else {
if (!subject.hasAllRoles(roles)) {
hasRoles = false;
}
}
}
return hasRoles;
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
String[] rolesArray = (String[]) mappedValue;
if (rolesArray == null || rolesArray.length == 0) {
//no roles specified, so nothing to check - allow access.
return true;
}
Set<String> roles = CollectionUtils.asSet(rolesArray);
return subject.hasAllRoles(roles);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int onDoStartTag() throws JspException {
if ( !getSecurityContext().isAuthenticated() ) {
return TagSupport.EVAL_BODY_INCLUDE;
} else {
return TagSupport.SKIP_BODY;
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public int onDoStartTag() throws JspException {
if ( getSecurityContext() == null || !getSecurityContext().isAuthenticated() ) {
return TagSupport.EVAL_BODY_INCLUDE;
} else {
return TagSupport.SKIP_BODY;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean showTagBody( String roleName ) {
return getSecurityContext().hasRole( roleName );
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean showTagBody( String roleName ) {
return getSecurityContext() != null && getSecurityContext().hasRole( roleName );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean bindInHttpSessionForSubsequentRequests( HttpServletRequest request, HttpServletResponse response,
SecurityContext securityContext ) {
HttpSession httpSession = request.getSession();
Object currentPrincipal = httpSession.getAttribute(PRINCIPALS_SESSION_KEY);
if ( currentPrincipal == null && !securityContext.getAllPrincipals().isEmpty() ) {
httpSession.setAttribute( PRINCIPALS_SESSION_KEY, securityContext.getAllPrincipals() );
}
Boolean currentAuthenticated = (Boolean) httpSession.getAttribute( AUTHENTICATED_SESSION_KEY );
if ( !currentAuthenticated.equals( securityContext.isAuthenticated() ) ) {
httpSession.setAttribute( AUTHENTICATED_SESSION_KEY, securityContext.getAllPrincipals() );
}
return true;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean bindInHttpSessionForSubsequentRequests( HttpServletRequest request, HttpServletResponse response,
SecurityContext securityContext ) {
HttpSession httpSession = request.getSession();
// Don't overwrite any previous credentials - i.e. SecurityContext swapping for a previously
// initialized session is not allowed.
// Only store principals if they exist in the security context
Object currentPrincipal = httpSession.getAttribute(PRINCIPALS_SESSION_KEY);
if ( currentPrincipal == null && !securityContext.getAllPrincipals().isEmpty() ) {
httpSession.setAttribute( PRINCIPALS_SESSION_KEY, securityContext.getAllPrincipals() );
}
// Only bind if the current value in the session is null or it doesn't equal the security context value
Boolean currentAuthenticated = (Boolean) httpSession.getAttribute( AUTHENTICATED_SESSION_KEY );
if ( currentAuthenticated == null || !currentAuthenticated.equals( securityContext.isAuthenticated() ) ) {
httpSession.setAttribute( AUTHENTICATED_SESSION_KEY, securityContext.isAuthenticated() );
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected boolean showTagBody( String roleName ) {
boolean hasRole = getSecurityContext().hasRole( roleName );
return !hasRole;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected boolean showTagBody( String roleName ) {
boolean hasRole = getSecurityContext() != null && getSecurityContext().hasRole( roleName );
return !hasRole;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDefaultConfig() {
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
subject.login(token);
assertTrue(subject.isAuthenticated());
assertTrue("guest".equals(subject.getPrincipal()));
assertTrue(subject.hasRole("guest"));
Session session = subject.getSession();
session.setAttribute("key", "value");
assertEquals(session.getAttribute("key"), "value");
subject.logout();
assertNull(subject.getSession(false));
assertNull(subject.getPrincipal());
assertNull(subject.getPrincipals());
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDefaultConfig() {
Subject subject = sm.getSubject();
AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
subject.login(token);
assertTrue(subject.isAuthenticated());
assertTrue("guest".equals(subject.getPrincipal()));
assertTrue(subject.hasRole("guest"));
Session session = subject.getSession();
session.setAttribute("key", "value");
assertEquals(session.getAttribute("key"), "value");
subject.logout();
assertNull(subject.getSession(false));
assertNull(subject.getPrincipal());
assertNull(subject.getPrincipals());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings( "unchecked" )
private static List<Principal> getPrincipals(HttpServletRequest request) {
List<Principal> principals = null;
Session session = ThreadLocalSecurityContext.current().getSession( false );
if( session != null ) {
principals = (List<Principal>) session.getAttribute( PRINCIPALS_SESSION_KEY );
} else {
HttpSession httpSession = request.getSession( false );
if( httpSession != null ) {
principals = (List<Principal>) httpSession.getAttribute( PRINCIPALS_SESSION_KEY );
}
}
return principals;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@SuppressWarnings( "unchecked" )
private static List<Principal> getPrincipals(HttpServletRequest request) {
List<Principal> principals = null;
Session session = (Session) ThreadContext.get( ThreadContext.SESSION_KEY );
if( session != null ) {
principals = (List<Principal>) session.getAttribute( PRINCIPALS_SESSION_KEY );
} else {
HttpSession httpSession = request.getSession( false );
if( httpSession != null ) {
principals = (List<Principal>) httpSession.getAttribute( PRINCIPALS_SESSION_KEY );
}
}
return principals;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
DbAction.Insert<?> createDeepInsert(String propertyName, Object value, Object key,
@Nullable DbAction.Insert<?> parentInsert) {
PersistentPropertyPath<RelationalPersistentProperty> propertyPath = toPath(parentInsert.getPropertyPath().toDotPath() + "." + propertyName);
DbAction.Insert<Object> insert = new DbAction.Insert<>(value, propertyPath, parentInsert);
insert.getQualifiers().put(propertyPath, key);
return insert;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
DbAction.Insert<?> createInsert(String propertyName, Object value, @Nullable Object key) {
DbAction.Insert<Object> insert = new DbAction.Insert<>(value,
context.getPersistentPropertyPath(propertyName, DummyEntity.class), rootInsert);
insert.getQualifiers().put(toPath(propertyName), key);
return insert;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Class<?> getQualifierColumnType() {
Assert.isTrue(isQualified(), "The qualifier column type is only defined for properties that are qualified");
if (isMap()) {
return getTypeInformation().getComponentType().getType();
}
// for lists and arrays
return Integer.class;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Class<?> getQualifierColumnType() {
Assert.isTrue(isQualified(), "The qualifier column type is only defined for properties that are qualified");
if (isMap()) {
return getTypeInformation().getRequiredComponentType().getType();
}
// for lists and arrays
return Integer.class;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws IOException {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Flowable.just("hi there".getBytes())
.compose(Transformers.outputStream(new Function<OutputStream, OutputStream>() {
@Override
public OutputStream apply(OutputStream os) throws Exception {
return new GZIPOutputStream(os);
}
}, 8192, 16)).doOnNext(new Consumer<byte[]>() {
@Override
public void accept(byte[] b) throws Exception {
bytes.write(b);
}
}).test()
.assertComplete();
InputStream is = new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray()));
assertEquals("hi there",read(is));
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() {
Flowable.just("hi there".getBytes())
.compose(Transformers.outputStream(new Function<OutputStream, OutputStream>() {
@Override
public OutputStream apply(OutputStream os) throws Exception {
return new GZIPOutputStream(os);
}
}, 8192, 16))
.test();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void load() {
String home = System.getProperty("user.home");
Properties awsConfigProperties = new Properties();
try {
// todo: use default profile
awsConfigProperties.load(new FileInputStream(home + "/.aws/config"));
} catch (IOException e) {
throw new RuntimeException("Could not load configuration. Please run 'aws configure'");
}
String region = awsConfigProperties.getProperty("region");
if (region != null) {
this.region = region;
} else {
LOG.warn("Could not load region configuration. Please ensure AWS CLI is configured via 'aws configure'. Will use default region of " + this.region);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public void load() {
Optional<String> region = loadRegion();
if (region.isPresent()) {
this.region = region.get();
} else {
this.region = DEFAULT_REGION;
LOG.warn("Could not load region configuration. Please ensure AWS CLI is " +
"configured via 'aws configure'. Will use default region of " + this.region);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
EntryLocation getLocationForOffset(long offset)
{
EntryLocation ret = new EntryLocation();
SegmentView sv = this.getSegmentForOffset(offset);
long reloff = offset - sv.startoff;
//select the group using a simple modulo mapping function
int gnum = (int)(reloff%sv.numgroups);
ret.group = sv.groups[gnum];
ret.relativeOff = reloff/sv.numgroups + ret.group.localstartoff;
log.info("location({}): seg.startOff={} gnum={} group-startOff={} relativeOff={} ",
offset,
sv.startoff,
gnum,
ret.group.localstartoff, ret.relativeOff);
return ret;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
SegmentView getActiveSegmentView() { return segmentlist.get(segmentlist.size()-1); } | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists()) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadProblem(url, "File already exists: " + prettySaveAs);
return;
}
}
int tries = 0; // Number of attempts to download
do {
try {
logger.info(" Downloading file: " + url + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
tries += 1;
Response response;
response = Jsoup.connect(url.toExternalForm())
.ignoreContentType(true)
.userAgent(AbstractRipper.USER_AGENT)
.header("accept", "*/*")
.timeout(TIMEOUT)
.maxBodySize(MAX_BODY_SIZE)
.cookies(cookies)
.referrer(referrer)
.execute();
if (response.statusCode() != 200) {
logger.error("[!] Non-OK status code " + response.statusCode() + " while downloading from " + url);
observer.downloadErrored(url, "Non-OK status code " + response.statusCode() + " while downloading " + url.toExternalForm());
return;
}
byte[] bytes = response.bodyAsBytes();
if (bytes.length == 503 && url.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
FileOutputStream out = new FileOutputStream(saveAs);
out.write(response.bodyAsBytes());
out.close();
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + url);
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
return;
}
} catch (IOException e) {
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage(), e);
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
}
#location 51
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists()) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadProblem(url, "File already exists: " + prettySaveAs);
return;
}
}
int tries = 0; // Number of attempts to download
do {
tries += 1;
InputStream bis = null; OutputStream fos = null;
try {
logger.info(" Downloading file: " + url + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc = (HttpURLConnection) this.url.openConnection();
huc.setConnectTimeout(TIMEOUT);
huc.setRequestProperty("accept", "*/*");
huc.setRequestProperty("Referer", referrer); // Sic
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
String cookie = "";
for (String key : cookies.keySet()) {
if (!cookie.equals("")) {
cookie += "; ";
}
cookie += key + "=" + cookies.get(key);
}
huc.setRequestProperty("Cookie", cookie);
huc.connect();
int statusCode = huc.getResponseCode();
if (statusCode / 100 == 4) { // 4xx errors
logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url);
observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm());
return; // Not retriable, drop out.
}
if (statusCode / 100 == 5) { // 5xx errors
observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm());
// Throw exception so download can be retried
throw new IOException("Retriable status code " + statusCode);
}
if (huc.getContentLength() == 503 && url.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
// Save file
bis = new BufferedInputStream(huc.getInputStream());
fos = new FileOutputStream(saveAs);
IOUtils.copy(bis, fos);
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + url);
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
return;
}
} catch (IOException e) {
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage(), e);
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testTwitterAlbums() throws IOException {
List<URL> contentURLs = new ArrayList<URL>();
//contentURLs.add(new URL("https://twitter.com/danngamber01/media"));
contentURLs.add(new URL("https://twitter.com/search?q=from%3Apurrbunny%20filter%3Aimages&src=typd"));
for (URL url : contentURLs) {
try {
TwitterRipper ripper = new TwitterRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testTwitterAlbums() throws IOException {
if (!DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
//contentURLs.add(new URL("https://twitter.com/danngamber01/media"));
contentURLs.add(new URL("https://twitter.com/search?q=from%3Apurrbunny%20filter%3Aimages&src=typd"));
for (URL url : contentURLs) {
try {
TwitterRipper ripper = new TwitterRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testTumblrAlbums() throws IOException {
if (false && !DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://wrouinr.tumblr.com/archive"));
//contentURLs.add(new URL("http://topinstagirls.tumblr.com/tagged/berlinskaya"));
//contentURLs.add(new URL("http://fittingroomgirls.tumblr.com/post/78268776776"));
for (URL url : contentURLs) {
try {
TumblrRipper ripper = new TumblrRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testTumblrAlbums() throws IOException {
if (!DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://wrouinr.tumblr.com/archive"));
contentURLs.add(new URL("http://topinstagirls.tumblr.com/tagged/berlinskaya"));
contentURLs.add(new URL("http://fittingroomgirls.tumblr.com/post/78268776776"));
for (URL url : contentURLs) {
try {
TumblrRipper ripper = new TumblrRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static List<Constructor<?>> getRipperConstructors() throws Exception {
List<Constructor<?>> constructors = new ArrayList<Constructor<?>>();
String rippersPackage = "com.rarchives.ripme.ripper.rippers";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = cl.getResources(rippersPackage.replaceAll("\\.", "/"));
if (!urls.hasMoreElements()) {
return constructors;
}
URL classURL = urls.nextElement();
for (File f : new File(classURL.toURI()).listFiles()) {
String className = f.getName();
if (!className.endsWith(".class")
|| className.contains("$")
|| className.endsWith("Test.class")) {
// Ignore non-class or nested classes.
continue;
}
className = className.substring(0, className.length() - 6); // Strip .class
String fqname = rippersPackage + "." + className;
Class<?> clazz = Class.forName(fqname);
constructors.add( (Constructor<?>) clazz.getConstructor(URL.class));
}
return constructors;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private static List<Constructor<?>> getRipperConstructors() throws Exception {
List<Constructor<?>> constructors = new ArrayList<Constructor<?>>();
for (Class<?> clazz : getClassesForPackage("com.rarchives.ripme.ripper.rippers")) {
if (AbstractRipper.class.isAssignableFrom(clazz)) {
constructors.add( (Constructor<?>) clazz.getConstructor(URL.class) );
}
}
return constructors;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testXvideosRipper() throws IOException {
if (false && !DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://www.xvideos.com/video1428195/stephanie_first_time_anal"));
contentURLs.add(new URL("http://www.xvideos.com/video7136868/vid-20140205-wa0011"));
for (URL url : contentURLs) {
try {
XvideosRipper ripper = new XvideosRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testXvideosRipper() throws IOException {
if (!DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://www.xvideos.com/video1428195/stephanie_first_time_anal"));
contentURLs.add(new URL("http://www.xvideos.com/video7136868/vid-20140205-wa0011"));
for (URL url : contentURLs) {
try {
XvideosRipper ripper = new XvideosRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void downloadProblem(URL url, String message) {
if (observer == null) {
return;
}
synchronized(observer) {
itemsPending.remove(url);
itemsErrored.put(url, message);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message));
observer.notifyAll();
checkIfComplete();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void downloadProblem(URL url, String message) {
if (observer == null) {
return;
}
synchronized(observer) {
itemsPending.remove(url);
itemsErrored.put(url, message);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message));
observer.notifyAll();
}
checkIfComplete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testRedditAlbums() throws IOException {
if (false && !DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
//contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc"));
//contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc/top?t=all"));
//contentURLs.add(new URL("http://www.reddit.com/u/gingerpuss"));
contentURLs.add(new URL("http://www.reddit.com/r/UnrealGirls/comments/1ziuhl/in_class_veronique_popa/"));
for (URL url : contentURLs) {
try {
RedditRipper ripper = new RedditRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testRedditAlbums() throws IOException {
if (!DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
//contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc"));
//contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc/top?t=all"));
//contentURLs.add(new URL("http://www.reddit.com/u/gingerpuss"));
contentURLs.add(new URL("http://www.reddit.com/r/UnrealGirls/comments/1ziuhl/in_class_veronique_popa/"));
for (URL url : contentURLs) {
try {
RedditRipper ripper = new RedditRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
e.printStackTrace();
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void login() throws IOException {
File f = new File("DACookie.toDelete");
if (!f.exists()) {
f.createNewFile();
f.deleteOnExit();
// Load login page
Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET)
.referrer(referer).userAgent(userAgent).execute();
// Find tokens
Document doc = res.parse();
Element form = doc.getElementById("login");
String token = form.select("input[name=\"validate_token\"]").first().attr("value");
String key = form.select("input[name=\"validate_key\"]").first().attr("value");
System.out.println(
"------------------------------" + token + " & " + key + "------------------------------");
// Build Login Data
HashMap<String, String> loginData = new HashMap<String, String>();
loginData.put("challenge", "");
loginData.put("username", username);
loginData.put("password", password);
loginData.put("remember_me", "1");
loginData.put("validate_token", token);
loginData.put("validate_key", key);
Map<String, String> cookies = res.cookies();
// Log in using data. Handle redirect
res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent)
.method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute();
this.cookies = res.cookies();
res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent)
.method(Method.GET).cookies(cookies).followRedirects(false).execute();
// Store cookies
updateCookie(res.cookies());
// Apply agegate
this.cookies.put("agegate_state", "1");
// Write Cookie to file for other RipMe Instances
try {
FileOutputStream fileOut = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this.cookies);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}
} else {
// When cookie file already exists (from another RipMe instance)
while (this.cookies == null) {
try {
Thread.sleep(2000);
FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.cookies = (Map<String, String>) in.readObject();
in.close();
fileIn.close();
} catch (IOException | ClassNotFoundException | InterruptedException i) {
i.printStackTrace();
}
}
}
System.out.println("------------------------------" + this.cookies + "------------------------------");
}
#location 66
#vulnerability type RESOURCE_LEAK | #fixed code
private void login() throws IOException {
try {
String dACookies = Utils.getConfigString(utilsKey, null);
this.cookies = dACookies != null ? deserialize(dACookies) : null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (this.cookies == null) {
LOGGER.info("Log in now");
// Do login now
// Load login page
Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET)
.referrer(referer).userAgent(userAgent).execute();
// Find tokens
Document doc = res.parse();
Element form = doc.getElementById("login");
String token = form.select("input[name=\"validate_token\"]").first().attr("value");
String key = form.select("input[name=\"validate_key\"]").first().attr("value");
LOGGER.info("Token: " + token + " & Key: " + key);
// Build Login Data
HashMap<String, String> loginData = new HashMap<String, String>();
loginData.put("challenge", "");
loginData.put("username", username);
loginData.put("password", password);
loginData.put("remember_me", "1");
loginData.put("validate_token", token);
loginData.put("validate_key", key);
Map<String, String> cookies = res.cookies();
// Log in using data. Handle redirect
res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent)
.method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute();
this.cookies = res.cookies();
res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent)
.method(Method.GET).cookies(cookies).followRedirects(false).execute();
// Store cookies
updateCookie(res.cookies());
// Apply agegate
this.cookies.put("agegate_state", "1");
// Write Cookie to file for other RipMe Instances or later use
Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(this.cookies)));
Utils.saveConfig(); // save now because of other instances that might work simultaneously
}
LOGGER.info("DA Cookies: " + this.cookies);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
Document userpage_doc;
// We check for the following string to see if this is a user page or not
if (doc.toString().contains("content=\"gallery\"")) {
for (Element elem : doc.select("a.image-container")) {
String link = elem.attr("href");
logger.info("Grabbing album " + link);
try {
userpage_doc = Http.url(link).get();
} catch(IOException e){
logger.warn("Failed to log link in Jsoup");
userpage_doc = null;
e.printStackTrace();
}
for (Element element : userpage_doc.select("a.image-container > img")) {
String imageSource = element.attr("src");
logger.info("Found image " + link);
// We remove the .md from images so we download the full size image
// not the medium ones
imageSource = imageSource.replace(".md", "");
result.add(imageSource);
}
}
}
else {
for (Element el : doc.select("a.image-container > img")) {
String imageSource = el.attr("src");
// We remove the .md from images so we download the full size image
// not the medium ones
imageSource = imageSource.replace(".md", "");
result.add(imageSource);
}
}
return result;
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<String>();
for (Element el : doc.select("a.image-container > img")) {
String imageSource = el.attr("src");
// We remove the .md from images so we download the full size image
// not the medium ones
imageSource = imageSource.replace(".md", "");
result.add(imageSource);
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
long fileSize = 0;
int bytesTotal = 0;
int bytesDownloaded = 0;
if (saveAs.exists() && observer.tryResumeDownload()) {
fileSize = saveAs.length();
}
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists() && !observer.tryResumeDownload()) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadExists(url, saveAs);
return;
}
}
URL urlToDownload = this.url;
boolean redirected = false;
int tries = 0; // Number of attempts to download
do {
tries += 1;
InputStream bis = null; OutputStream fos = null;
try {
logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc;
if (this.url.toString().startsWith("https")) {
huc = (HttpsURLConnection) urlToDownload.openConnection();
}
else {
huc = (HttpURLConnection) urlToDownload.openConnection();
}
huc.setInstanceFollowRedirects(true);
huc.setConnectTimeout(TIMEOUT);
huc.setRequestProperty("accept", "*/*");
if (!referrer.equals("")) {
huc.setRequestProperty("Referer", referrer); // Sic
}
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
String cookie = "";
for (String key : cookies.keySet()) {
if (!cookie.equals("")) {
cookie += "; ";
}
cookie += key + "=" + cookies.get(key);
}
huc.setRequestProperty("Cookie", cookie);
if (observer.tryResumeDownload()) {
if (fileSize != 0) {
huc.setRequestProperty("Range", "bytes=" + fileSize + "-");
}
}
logger.debug("Request properties: " + huc.getRequestProperties());
huc.connect();
int statusCode = huc.getResponseCode();
logger.debug("Status code: " + statusCode);
if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) {
// TODO find a better way to handle servers that don't support resuming downloads then just erroring out
throw new IOException("Server doesn't support resuming downloads");
}
if (statusCode / 100 == 3) { // 3xx Redirect
if (!redirected) {
// Don't increment retries on the first redirect
tries--;
redirected = true;
}
String location = huc.getHeaderField("Location");
urlToDownload = new URL(location);
// Throw exception so download can be retried
throw new IOException("Redirect status code " + statusCode + " - redirect to " + location);
}
if (statusCode / 100 == 4) { // 4xx errors
logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url);
observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm());
return; // Not retriable, drop out.
}
if (statusCode / 100 == 5) { // 5xx errors
observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm());
// Throw exception so download can be retried
throw new IOException("Retriable status code " + statusCode);
}
if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
// If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength()
if (observer.useByteProgessBar()) {
bytesTotal = huc.getContentLength();
observer.setBytesTotal(bytesTotal);
observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal);
logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b");
}
// Save file
bis = new BufferedInputStream(huc.getInputStream());
// Check if we should get the file ext from the MIME type
if (getFileExtFromMIME) {
String fileExt = URLConnection.guessContentTypeFromStream(bis);
if (fileExt != null) {
fileExt = fileExt.replaceAll("image/", "");
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type from stream");
// Try to get the file type from the magic number
byte[] magicBytes = new byte[8];
bis.read(magicBytes,0, 5);
bis.reset();
fileExt = Utils.getEXTFromMagic(magicBytes);
if (fileExt != null) {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type using magic number");
logger.error("Magic number was: " + Arrays.toString(magicBytes));
}
}
}
// If we're resuming a download we append data to the existing file
if (statusCode == 206) {
fos = new FileOutputStream(saveAs, true);
} else {
fos = new FileOutputStream(saveAs);
}
byte[] data = new byte[1024 * 256];
int bytesRead;
while ( (bytesRead = bis.read(data)) != -1) {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
fos.write(data, 0, bytesRead);
if (observer.useByteProgessBar()) {
bytesDownloaded += bytesRead;
observer.setBytesCompleted(bytesDownloaded);
observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded);
}
}
bis.close();
fos.close();
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.debug("HTTP status exception", hse);
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload);
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
return;
}
} catch (IOException e) {
logger.debug("IOException", e);
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage());
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
}
#location 108
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
long fileSize = 0;
int bytesTotal = 0;
int bytesDownloaded = 0;
if (saveAs.exists() && observer.tryResumeDownload()) {
fileSize = saveAs.length();
}
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists() && !observer.tryResumeDownload() || Utils.fuzzyExists(new File(saveAs.getParent()), saveAs.getName())) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadExists(url, saveAs);
return;
}
}
URL urlToDownload = this.url;
boolean redirected = false;
int tries = 0; // Number of attempts to download
do {
tries += 1;
InputStream bis = null; OutputStream fos = null;
try {
logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc;
if (this.url.toString().startsWith("https")) {
huc = (HttpsURLConnection) urlToDownload.openConnection();
}
else {
huc = (HttpURLConnection) urlToDownload.openConnection();
}
huc.setInstanceFollowRedirects(true);
huc.setConnectTimeout(TIMEOUT);
huc.setRequestProperty("accept", "*/*");
if (!referrer.equals("")) {
huc.setRequestProperty("Referer", referrer); // Sic
}
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
String cookie = "";
for (String key : cookies.keySet()) {
if (!cookie.equals("")) {
cookie += "; ";
}
cookie += key + "=" + cookies.get(key);
}
huc.setRequestProperty("Cookie", cookie);
if (observer.tryResumeDownload()) {
if (fileSize != 0) {
huc.setRequestProperty("Range", "bytes=" + fileSize + "-");
}
}
logger.debug("Request properties: " + huc.getRequestProperties());
huc.connect();
int statusCode = huc.getResponseCode();
logger.debug("Status code: " + statusCode);
if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) {
// TODO find a better way to handle servers that don't support resuming downloads then just erroring out
throw new IOException("Server doesn't support resuming downloads");
}
if (statusCode / 100 == 3) { // 3xx Redirect
if (!redirected) {
// Don't increment retries on the first redirect
tries--;
redirected = true;
}
String location = huc.getHeaderField("Location");
urlToDownload = new URL(location);
// Throw exception so download can be retried
throw new IOException("Redirect status code " + statusCode + " - redirect to " + location);
}
if (statusCode / 100 == 4) { // 4xx errors
logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url);
observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm());
return; // Not retriable, drop out.
}
if (statusCode / 100 == 5) { // 5xx errors
observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm());
// Throw exception so download can be retried
throw new IOException("Retriable status code " + statusCode);
}
if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
// If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength()
if (observer.useByteProgessBar()) {
bytesTotal = huc.getContentLength();
observer.setBytesTotal(bytesTotal);
observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal);
logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b");
}
// Save file
bis = new BufferedInputStream(huc.getInputStream());
// Check if we should get the file ext from the MIME type
if (getFileExtFromMIME) {
String fileExt = URLConnection.guessContentTypeFromStream(bis);
if (fileExt != null) {
fileExt = fileExt.replaceAll("image/", "");
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type from stream");
// Try to get the file type from the magic number
byte[] magicBytes = new byte[8];
bis.read(magicBytes,0, 5);
bis.reset();
fileExt = Utils.getEXTFromMagic(magicBytes);
if (fileExt != null) {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type using magic number");
logger.error("Magic number was: " + Arrays.toString(magicBytes));
}
}
}
// If we're resuming a download we append data to the existing file
if (statusCode == 206) {
fos = new FileOutputStream(saveAs, true);
} else {
fos = new FileOutputStream(saveAs);
}
byte[] data = new byte[1024 * 256];
int bytesRead;
while ( (bytesRead = bis.read(data)) != -1) {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
fos.write(data, 0, bytesRead);
if (observer.useByteProgessBar()) {
bytesDownloaded += bytesRead;
observer.setBytesCompleted(bytesDownloaded);
observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded);
}
}
bis.close();
fos.close();
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.debug("HTTP status exception", hse);
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload);
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
return;
}
} catch (IOException e) {
logger.debug("IOException", e);
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage());
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void downloadErrored(URL url, String reason) {
if (observer == null) {
return;
}
synchronized(observer) {
itemsPending.remove(url);
itemsErrored.put(url, reason);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason));
observer.notifyAll();
checkIfComplete();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void downloadErrored(URL url, String reason) {
if (observer == null) {
return;
}
itemsPending.remove(url);
itemsErrored.put(url, reason);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason));
checkIfComplete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
void testKeyCount() {
((ConsoleAppender) Logger.getRootLogger().getAppender("stdout")).setThreshold(Level.DEBUG);
File f = new File("E:\\Downloads\\_Isaaku\\dev\\ripme-1.7.86-jar-with-dependencies.jar");
File[] files = f.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
logger.info("name: " + name);
return name.startsWith("LabelsBundle_");
}
});
for (String s : getResourcesNames("\\**")) {
logger.info(s);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
void testKeyCount() {
ResourceBundle defaultBundle = Utils.getResourceBundle(null);
HashMap<String, ArrayList<String>> dictionary = new HashMap<>();
for (String lang : Utils.getSupportedLanguages()) {
ResourceBundle.clearCache();
if (lang.equals(DEFAULT_LANG))
continue;
ResourceBundle selectedLang = Utils.getResourceBundle(lang);
for (final Enumeration<String> keys = defaultBundle.getKeys(); keys.hasMoreElements();) {
String element = keys.nextElement();
if (selectedLang.containsKey(element)
&& !selectedLang.getString(element).equals(defaultBundle.getString(element))) {
if (dictionary.get(lang) == null)
dictionary.put(lang, new ArrayList<>());
dictionary.get(lang).add(element);
}
}
}
dictionary.keySet().forEach(d -> {
logger.warn(String.format("Keys missing in %s", d));
dictionary.get(d).forEach(v -> logger.warn(v));
logger.warn("\n");
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String[] getDescription(String url,Document page) {
if (isThisATest()) {
return null;
}
try {
// Fetch the image page
Response resp = Http.url(url)
.referrer(this.url)
.cookies(cookies)
.response();
cookies.putAll(resp.cookies());
// Try to find the description
Elements els = resp.parse().select("div[class=dev-description]");
if (els.size() == 0) {
throw new IOException("No description found");
}
Document documentz = resp.parse();
Element ele = documentz.select("div[class=dev-description]").get(0);
documentz.outputSettings(new Document.OutputSettings().prettyPrint(false));
ele.select("br").append("\\n");
ele.select("p").prepend("\\n\\n");
String fullSize = null;
Element thumb = page.select("div.zones-container span.thumb[href=\"" + url + "\"]").get(0);
if (!thumb.attr("data-super-full-img").isEmpty()) {
fullSize = thumb.attr("data-super-full-img");
String[] split = fullSize.split("/");
fullSize = split[split.length - 1];
} else {
String spanUrl = thumb.attr("href");
fullSize = jsonToImage(page,spanUrl.substring(spanUrl.lastIndexOf('-') + 1));
String[] split = fullSize.split("/");
fullSize = split[split.length - 1];
}
if (fullSize == null) {
return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false))};
}
fullSize = fullSize.substring(0, fullSize.lastIndexOf("."));
return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)),fullSize};
// TODO Make this not make a newline if someone just types \n into the description.
} catch (IOException ioe) {
logger.info("Failed to get description " + page + " : '" + ioe.getMessage() + "'");
return null;
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String[] getDescription(String url,Document page) {
if (isThisATest()) {
return null;
}
try {
// Fetch the image page
Response resp = Http.url(url)
.referrer(this.url)
.cookies(cookies)
.response();
cookies.putAll(resp.cookies());
// Try to find the description
Document documentz = resp.parse();
Element ele = documentz.select("div.dev-description").first();
if (ele == null) {
throw new IOException("No description found");
}
documentz.outputSettings(new Document.OutputSettings().prettyPrint(false));
ele.select("br").append("\\n");
ele.select("p").prepend("\\n\\n");
String fullSize = null;
Element thumb = page.select("div.zones-container span.thumb[href=\"" + url + "\"]").get(0);
if (!thumb.attr("data-super-full-img").isEmpty()) {
fullSize = thumb.attr("data-super-full-img");
String[] split = fullSize.split("/");
fullSize = split[split.length - 1];
} else {
String spanUrl = thumb.attr("href");
fullSize = jsonToImage(page,spanUrl.substring(spanUrl.lastIndexOf('-') + 1));
if (fullSize != null) {
String[] split = fullSize.split("/");
fullSize = split[split.length - 1];
}
}
if (fullSize == null) {
return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false))};
}
fullSize = fullSize.substring(0, fullSize.lastIndexOf("."));
return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)),fullSize};
// TODO Make this not make a newline if someone just types \n into the description.
} catch (IOException ioe) {
logger.info("Failed to get description at " + url + ": '" + ioe.getMessage() + "'");
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
long fileSize = 0;
int bytesTotal = 0;
int bytesDownloaded = 0;
if (saveAs.exists() && observer.tryResumeDownload()) {
fileSize = saveAs.length();
}
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists() && !observer.tryResumeDownload()) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadExists(url, saveAs);
return;
}
}
URL urlToDownload = this.url;
boolean redirected = false;
int tries = 0; // Number of attempts to download
do {
tries += 1;
InputStream bis = null; OutputStream fos = null;
try {
logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc;
if (this.url.toString().startsWith("https")) {
huc = (HttpsURLConnection) urlToDownload.openConnection();
}
else {
huc = (HttpURLConnection) urlToDownload.openConnection();
}
huc.setInstanceFollowRedirects(true);
huc.setConnectTimeout(TIMEOUT);
huc.setRequestProperty("accept", "*/*");
if (!referrer.equals("")) {
huc.setRequestProperty("Referer", referrer); // Sic
}
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
String cookie = "";
for (String key : cookies.keySet()) {
if (!cookie.equals("")) {
cookie += "; ";
}
cookie += key + "=" + cookies.get(key);
}
huc.setRequestProperty("Cookie", cookie);
if (observer.tryResumeDownload()) {
if (fileSize != 0) {
huc.setRequestProperty("Range", "bytes=" + fileSize + "-");
}
}
logger.debug("Request properties: " + huc.getRequestProperties());
huc.connect();
int statusCode = huc.getResponseCode();
logger.debug("Status code: " + statusCode);
if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) {
// TODO find a better way to handle servers that don't support resuming downloads then just erroring out
throw new IOException("Server doesn't support resuming downloads");
}
if (statusCode / 100 == 3) { // 3xx Redirect
if (!redirected) {
// Don't increment retries on the first redirect
tries--;
redirected = true;
}
String location = huc.getHeaderField("Location");
urlToDownload = new URL(location);
// Throw exception so download can be retried
throw new IOException("Redirect status code " + statusCode + " - redirect to " + location);
}
if (statusCode / 100 == 4) { // 4xx errors
logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url);
observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm());
return; // Not retriable, drop out.
}
if (statusCode / 100 == 5) { // 5xx errors
observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm());
// Throw exception so download can be retried
throw new IOException("Retriable status code " + statusCode);
}
if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
// If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength()
if (observer.useByteProgessBar()) {
bytesTotal = huc.getContentLength();
observer.setBytesTotal(bytesTotal);
observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal);
logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b");
}
// Save file
bis = new BufferedInputStream(huc.getInputStream());
// Check if we should get the file ext from the MIME type
if (getFileExtFromMIME) {
String fileExt = URLConnection.guessContentTypeFromStream(bis);
if (fileExt != null) {
fileExt = fileExt.replaceAll("image/", "");
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type from stream");
// Try to get the file type from the magic number
byte[] magicBytes = new byte[8];
bis.read(magicBytes,0, 5);
bis.reset();
fileExt = Utils.getEXTFromMagic(magicBytes);
if (fileExt != null) {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type using magic number");
logger.error("Magic number was: " + Arrays.toString(magicBytes));
}
}
}
// If we're resuming a download we append data to the existing file
if (statusCode == 206) {
fos = new FileOutputStream(saveAs, true);
} else {
fos = new FileOutputStream(saveAs);
}
byte[] data = new byte[1024 * 256];
int bytesRead;
while ( (bytesRead = bis.read(data)) != -1) {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
fos.write(data, 0, bytesRead);
if (observer.useByteProgessBar()) {
bytesDownloaded += bytesRead;
observer.setBytesCompleted(bytesDownloaded);
observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded);
}
}
bis.close();
fos.close();
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.debug("HTTP status exception", hse);
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload);
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
return;
}
} catch (IOException e) {
logger.debug("IOException", e);
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage());
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
}
#location 108
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
long fileSize = 0;
int bytesTotal = 0;
int bytesDownloaded = 0;
if (saveAs.exists() && observer.tryResumeDownload()) {
fileSize = saveAs.length();
}
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
if (saveAs.exists() && !observer.tryResumeDownload() || Utils.fuzzyExists(new File(saveAs.getParent()), saveAs.getName())) {
if (Utils.getConfigBoolean("file.overwrite", false)) {
logger.info("[!] Deleting existing file" + prettySaveAs);
saveAs.delete();
} else {
logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs);
observer.downloadExists(url, saveAs);
return;
}
}
URL urlToDownload = this.url;
boolean redirected = false;
int tries = 0; // Number of attempts to download
do {
tries += 1;
InputStream bis = null; OutputStream fos = null;
try {
logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : ""));
observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm());
// Setup HTTP request
HttpURLConnection huc;
if (this.url.toString().startsWith("https")) {
huc = (HttpsURLConnection) urlToDownload.openConnection();
}
else {
huc = (HttpURLConnection) urlToDownload.openConnection();
}
huc.setInstanceFollowRedirects(true);
huc.setConnectTimeout(TIMEOUT);
huc.setRequestProperty("accept", "*/*");
if (!referrer.equals("")) {
huc.setRequestProperty("Referer", referrer); // Sic
}
huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT);
String cookie = "";
for (String key : cookies.keySet()) {
if (!cookie.equals("")) {
cookie += "; ";
}
cookie += key + "=" + cookies.get(key);
}
huc.setRequestProperty("Cookie", cookie);
if (observer.tryResumeDownload()) {
if (fileSize != 0) {
huc.setRequestProperty("Range", "bytes=" + fileSize + "-");
}
}
logger.debug("Request properties: " + huc.getRequestProperties());
huc.connect();
int statusCode = huc.getResponseCode();
logger.debug("Status code: " + statusCode);
if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) {
// TODO find a better way to handle servers that don't support resuming downloads then just erroring out
throw new IOException("Server doesn't support resuming downloads");
}
if (statusCode / 100 == 3) { // 3xx Redirect
if (!redirected) {
// Don't increment retries on the first redirect
tries--;
redirected = true;
}
String location = huc.getHeaderField("Location");
urlToDownload = new URL(location);
// Throw exception so download can be retried
throw new IOException("Redirect status code " + statusCode + " - redirect to " + location);
}
if (statusCode / 100 == 4) { // 4xx errors
logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url);
observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm());
return; // Not retriable, drop out.
}
if (statusCode / 100 == 5) { // 5xx errors
observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm());
// Throw exception so download can be retried
throw new IOException("Retriable status code " + statusCode);
}
if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) {
// Imgur image with 503 bytes is "404"
logger.error("[!] Imgur image is 404 (503 bytes long): " + url);
observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm());
return;
}
// If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength()
if (observer.useByteProgessBar()) {
bytesTotal = huc.getContentLength();
observer.setBytesTotal(bytesTotal);
observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal);
logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b");
}
// Save file
bis = new BufferedInputStream(huc.getInputStream());
// Check if we should get the file ext from the MIME type
if (getFileExtFromMIME) {
String fileExt = URLConnection.guessContentTypeFromStream(bis);
if (fileExt != null) {
fileExt = fileExt.replaceAll("image/", "");
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type from stream");
// Try to get the file type from the magic number
byte[] magicBytes = new byte[8];
bis.read(magicBytes,0, 5);
bis.reset();
fileExt = Utils.getEXTFromMagic(magicBytes);
if (fileExt != null) {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type using magic number");
logger.error("Magic number was: " + Arrays.toString(magicBytes));
}
}
}
// If we're resuming a download we append data to the existing file
if (statusCode == 206) {
fos = new FileOutputStream(saveAs, true);
} else {
fos = new FileOutputStream(saveAs);
}
byte[] data = new byte[1024 * 256];
int bytesRead;
while ( (bytesRead = bis.read(data)) != -1) {
try {
observer.stopCheck();
} catch (IOException e) {
observer.downloadErrored(url, "Download interrupted");
return;
}
fos.write(data, 0, bytesRead);
if (observer.useByteProgessBar()) {
bytesDownloaded += bytesRead;
observer.setBytesCompleted(bytesDownloaded);
observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded);
}
}
bis.close();
fos.close();
break; // Download successful: break out of infinite loop
} catch (HttpStatusException hse) {
logger.debug("HTTP status exception", hse);
logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload);
if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) {
observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm());
return;
}
} catch (IOException e) {
logger.debug("IOException", e);
logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage());
} finally {
// Close any open streams
try {
if (bis != null) { bis.close(); }
} catch (IOException e) { }
try {
if (fos != null) { fos.close(); }
} catch (IOException e) { }
}
if (tries > this.retries) {
logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url);
observer.downloadErrored(url, "Failed to download " + url.toExternalForm());
return;
}
} while (true);
observer.downloadCompleted(url, saveAs);
logger.info("[+] Saved " + url + " as " + this.prettySaveAs);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void sendUpdate(STATUS status, Object message) {
if (observer == null) {
return;
}
synchronized (observer) {
observer.update(this, new RipStatusMessage(status, message));
observer.notifyAll();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void sendUpdate(STATUS status, Object message) {
if (observer == null) {
return;
}
observer.update(this, new RipStatusMessage(status, message));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void downloadCompleted(URL url, File saveAs) {
if (observer == null) {
return;
}
try {
String path = Utils.removeCWD(saveAs);
RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path);
synchronized(observer) {
itemsPending.remove(url);
itemsCompleted.put(url, saveAs);
observer.update(this, msg);
observer.notifyAll();
checkIfComplete();
}
} catch (Exception e) {
logger.error("Exception while updating observer: ", e);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void downloadCompleted(URL url, File saveAs) {
if (observer == null) {
return;
}
try {
String path = Utils.removeCWD(saveAs);
RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path);
itemsPending.remove(url);
itemsCompleted.put(url, saveAs);
observer.update(this, msg);
checkIfComplete();
} catch (Exception e) {
logger.error("Exception while updating observer: ", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static File getJarDirectory() {
String[] classPath = System.getProperty("java.class.path").split(";");
return classPath.length > 1 ? new File(System.getProperty("user.dir")) : new File(classPath[0]).getParentFile();
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
private static File getJarDirectory() {
return Utils.class.getResource("/rip.properties").toString().contains("jar:") ? new File(System.getProperty("java.class.path")).getParentFile() : new File(System.getProperty("user.dir"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (getHost().contains("www.totempole666.com")
|| getHost().contains("buttsmithy.com")
|| getHost().contains("themonsterunderthebed.net")
|| getHost().contains("prismblush.com")
|| getHost().contains("www.konradokonski.com")
|| getHost().contains("thisis.delvecomic.com")
|| getHost().contains("tnbtu.com")) {
Element elem = doc.select("div.comic-table > div#comic > a > img").first();
// If doc is the last page in the comic then elem.attr("src") returns null
// because there is no link <a> to the next page
if (elem == null) {
elem = doc.select("div.comic-table > div#comic > img").first();
}
// Check if this is a site where we can get the page number from the title
if (url.toExternalForm().contains("buttsmithy.com")) {
// Set the page title
pageTitle = doc.select("meta[property=og:title]").attr("content");
pageTitle = pageTitle.replace(" ", "");
pageTitle = pageTitle.replace("P", "p");
}
if (url.toExternalForm().contains("www.totempole666.com")) {
String postDate = doc.select("span.post-date").first().text().replaceAll("/", "_");
String postTitle = doc.select("h2.post-title").first().text().replaceAll("#", "");
pageTitle = postDate + "_" + postTitle;
}
if (url.toExternalForm().contains("themonsterunderthebed.net")) {
pageTitle = doc.select("title").first().text().replaceAll("#", "");
pageTitle = pageTitle.replace("“", "");
pageTitle = pageTitle.replace("”", "");
pageTitle = pageTitle.replace("The Monster Under the Bed", "");
pageTitle = pageTitle.replace("–", "");
pageTitle = pageTitle.replace(",", "");
pageTitle = pageTitle.replace(" ", "");
}
result.add(elem.attr("src"));
}
// freeadultcomix gets it own if because it needs to add http://freeadultcomix.com to the start of each link
// TODO review the above comment which no longer applies -- see if there's a refactoring we should do here.
if (url.toExternalForm().contains("freeadultcomix.com")) {
for (Element elem : doc.select("div.single-post > p > img.aligncenter")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("comics-xxx.com")) {
for (Element elem : doc.select("div.single-post > center > p > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("shipinbottle.pepsaga.com")) {
for (Element elem : doc.select("div#comic > div.comicpane > a > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("8muses.download")) {
for (Element elem : doc.select("div.popup-gallery > figure > a")) {
result.add(elem.attr("href"));
}
}
return result;
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public List<String> getURLsFromPage(Document doc) {
List<String> result = new ArrayList<>();
if (theme1.contains(getHost())) {
Element elem = doc.select("div.comic-table > div#comic > a > img").first();
// If doc is the last page in the comic then elem.attr("src") returns null
// because there is no link <a> to the next page
if (elem == null) {
elem = doc.select("div.comic-table > div#comic > img").first();
}
// Check if this is a site where we can get the page number from the title
if (url.toExternalForm().contains("buttsmithy.com")) {
// Set the page title
pageTitle = doc.select("meta[property=og:title]").attr("content");
pageTitle = pageTitle.replace(" ", "");
pageTitle = pageTitle.replace("P", "p");
}
if (url.toExternalForm().contains("www.totempole666.com")) {
String postDate = doc.select("span.post-date").first().text().replaceAll("/", "_");
String postTitle = doc.select("h2.post-title").first().text().replaceAll("#", "");
pageTitle = postDate + "_" + postTitle;
}
if (url.toExternalForm().contains("themonsterunderthebed.net")) {
pageTitle = doc.select("title").first().text().replaceAll("#", "");
pageTitle = pageTitle.replace("“", "");
pageTitle = pageTitle.replace("”", "");
pageTitle = pageTitle.replace("The Monster Under the Bed", "");
pageTitle = pageTitle.replace("–", "");
pageTitle = pageTitle.replace(",", "");
pageTitle = pageTitle.replace(" ", "");
}
result.add(elem.attr("src"));
}
// freeadultcomix gets it own if because it needs to add http://freeadultcomix.com to the start of each link
// TODO review the above comment which no longer applies -- see if there's a refactoring we should do here.
if (url.toExternalForm().contains("freeadultcomix.com")) {
for (Element elem : doc.select("div.single-post > p > img.aligncenter")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("comics-xxx.com")) {
for (Element elem : doc.select("div.single-post > center > p > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("shipinbottle.pepsaga.com")) {
for (Element elem : doc.select("div#comic > div.comicpane > a > img")) {
result.add(elem.attr("src"));
}
}
if (url.toExternalForm().contains("8muses.download")) {
for (Element elem : doc.select("div.popup-gallery > figure > a")) {
result.add(elem.attr("href"));
}
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void downloadProblem(URL url, String message) {
if (observer == null) {
return;
}
synchronized(observer) {
itemsPending.remove(url);
itemsErrored.put(url, message);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message));
observer.notifyAll();
}
checkIfComplete();
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void downloadProblem(URL url, String message) {
if (observer == null) {
return;
}
itemsPending.remove(url);
itemsErrored.put(url, message);
observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message));
checkIfComplete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void login() throws IOException {
try {
String dACookies = Utils.getConfigString(utilsKey, null);
updateCookie(dACookies != null ? deserialize(dACookies) : null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (getDACookie() == null || !checkLogin()) {
LOGGER.info("Do Login now");
// Do login now
// Load login page
Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET)
.referrer(referer).userAgent(userAgent).execute();
updateCookie(res.cookies());
// Find tokens
Document doc = res.parse();
Element form = doc.getElementById("login");
String token = form.select("input[name=\"validate_token\"]").first().attr("value");
String key = form.select("input[name=\"validate_key\"]").first().attr("value");
LOGGER.info("Token: " + token + " & Key: " + key);
// Build Login Data
HashMap<String, String> loginData = new HashMap<String, String>();
loginData.put("challenge", "");
loginData.put("username", this.username);
loginData.put("password", this.password);
loginData.put("remember_me", "1");
loginData.put("validate_token", token);
loginData.put("validate_key", key);
Map<String, String> cookies = res.cookies();
// Log in using data. Handle redirect
res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent)
.method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute();
updateCookie(res.cookies());
res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent)
.method(Method.GET).cookies(cookies).followRedirects(false).execute();
// Store cookies
updateCookie(res.cookies());
// Write Cookie to file for other RipMe Instances or later use
Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(getDACookie())));
Utils.saveConfig(); // save now because of other instances that might work simultaneously
}else {
LOGGER.info("No new Login needed");
}
LOGGER.info("DA Cookies: " + getDACookie());
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private void login() throws IOException {
String customUsername = Utils.getConfigString("DeviantartCustomLoginUsername", this.username);
String customPassword = Utils.getConfigString("DeviantartCustomLoginPassword", this.password);
try {
String dACookies = Utils.getConfigString(utilsKey, null);
updateCookie(dACookies != null ? deserialize(dACookies) : null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (getDACookie() == null || !checkLogin()) {
LOGGER.info("Do Login now");
// Do login now
// Load login page
Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET)
.referrer(referer).userAgent(userAgent).execute();
updateCookie(res.cookies());
// Find tokens
Document doc = res.parse();
Element form = doc.getElementById("login");
String token = form.select("input[name=\"validate_token\"]").first().attr("value");
String key = form.select("input[name=\"validate_key\"]").first().attr("value");
LOGGER.info("Token: " + token + " & Key: " + key);
// Build Login Data
HashMap<String, String> loginData = new HashMap<String, String>();
loginData.put("challenge", "");
loginData.put("username", customUsername);
loginData.put("password", customPassword);
loginData.put("remember_me", "1");
loginData.put("validate_token", token);
loginData.put("validate_key", key);
Map<String, String> cookies = res.cookies();
// Log in using data. Handle redirect
res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent)
.method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute();
updateCookie(res.cookies());
res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent)
.method(Method.GET).cookies(cookies).followRedirects(false).execute();
// Store cookies
updateCookie(res.cookies());
// Write Cookie to file for other RipMe Instances or later use
Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(getDACookie())));
Utils.saveConfig(); // save now because of other instances that might work simultaneously
}else {
LOGGER.info("No new Login needed");
}
LOGGER.info("DA Cookies: " + getDACookie());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testInstagramAlbums() throws IOException {
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://instagram.com/feelgoodincc#"));
for (URL url : contentURLs) {
try {
InstagramRipper ripper = new InstagramRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testInstagramAlbums() throws IOException {
if (!DOWNLOAD_CONTENT) {
return;
}
List<URL> contentURLs = new ArrayList<URL>();
contentURLs.add(new URL("http://instagram.com/feelgoodincc#"));
for (URL url : contentURLs) {
try {
InstagramRipper ripper = new InstagramRipper(url);
ripper.rip();
assert(ripper.getWorkingDir().listFiles().length > 1);
deleteDir(ripper.getWorkingDir());
} catch (Exception e) {
fail("Error while ripping URL " + url + ": " + e.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void replyToStatus(String content, String replyTo) throws ArchivedGroupException, ReplyStatusException {
AbstractStatus abstractOriginalStatus = statusRepository.findStatusById(replyTo);
if (abstractOriginalStatus != null &&
!abstractOriginalStatus.getType().equals(StatusType.STATUS) &&
!abstractOriginalStatus.getType().equals(StatusType.SHARE)) {
log.debug("Can not reply to a status of this type");
throw new ReplyStatusException();
}
if (abstractOriginalStatus != null &&
abstractOriginalStatus.getType().equals(StatusType.SHARE)) {
Share share = (Share) abstractOriginalStatus;
AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(share.getOriginalStatusId());
abstractOriginalStatus = abstractRealOriginalStatus;
}
Status originalStatus = (Status) abstractOriginalStatus;
Group group = null;
if (originalStatus.getGroupId() != null) {
group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId());
if (group.isArchivedGroup()) {
throw new ArchivedGroupException();
}
}
if (!originalStatus.getReplyTo().equals("")) {
// Original status is also a reply, replying to the real original status instead
AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId());
if (abstractRealOriginalStatus == null ||
!abstractRealOriginalStatus.getType().equals(StatusType.STATUS)) {
throw new ReplyStatusException();
}
Status realOriginalStatus = (Status) abstractRealOriginalStatus;
Status replyStatus = createStatus(
content,
realOriginalStatus.getStatusPrivate(),
group,
realOriginalStatus.getStatusId(),
originalStatus.getStatusId(),
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId());
} else {
// The original status of the discussion is the one we reply to
Status replyStatus =
createStatus(content,
originalStatus.getStatusPrivate(),
group,
replyTo,
replyTo,
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId());
}
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
public void replyToStatus(String content, String replyTo) throws ArchivedGroupException, ReplyStatusException {
AbstractStatus abstractStatus = statusRepository.findStatusById(replyTo);
if (abstractStatus != null &&
!abstractStatus.getType().equals(StatusType.STATUS) &&
!abstractStatus.getType().equals(StatusType.SHARE)) {
log.debug("Can not reply to a status of this type");
throw new ReplyStatusException();
}
if (abstractStatus != null &&
abstractStatus.getType().equals(StatusType.SHARE)) {
log.debug("Replacing the share by the original status");
Share share = (Share) abstractStatus;
AbstractStatus abstractRealStatus = statusRepository.findStatusById(share.getOriginalStatusId());
abstractStatus = abstractRealStatus;
}
Status status = (Status) abstractStatus;
Group group = null;
if (status.getGroupId() != null) {
group = groupService.getGroupById(status.getDomain(), status.getGroupId());
if (group.isArchivedGroup()) {
throw new ArchivedGroupException();
}
}
if (!status.getReplyTo().equals("")) {
log.debug("Replacing the status by the status at the origin of the disucssion");
// Original status is also a reply, replying to the real original status instead
AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(status.getDiscussionId());
if (abstractRealOriginalStatus == null ||
!abstractRealOriginalStatus.getType().equals(StatusType.STATUS)) {
throw new ReplyStatusException();
}
Status realOriginalStatus = (Status) abstractRealOriginalStatus;
Status replyStatus = createStatus(
content,
realOriginalStatus.getStatusPrivate(),
group,
realOriginalStatus.getStatusId(),
status.getStatusId(),
status.getUsername());
discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId());
} else {
log.debug("Replying directly to the status at the origin of the disucssion");
// The original status of the discussion is the one we reply to
Status replyStatus =
createStatus(content,
status.getStatusPrivate(),
group,
status.getStatusId(),
status.getStatusId(),
status.getUsername());
discussionRepository.addReplyToDiscussion(status.getStatusId(), replyStatus.getStatusId());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
@Cacheable("attachment-cache")
public Attachment findAttachmentById(String attachmentId) {
if (attachmentId == null) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("Finding attachment : " + attachmentId);
}
Attachment attachment = this.findAttachmentMetadataById(attachmentId);
ColumnQuery<String, String, byte[]> queryAttachment = HFactory.createColumnQuery(keyspaceOperator,
StringSerializer.get(), StringSerializer.get(), BytesArraySerializer.get());
HColumn<String, byte[]> columnAttachment =
queryAttachment.setColumnFamily(ATTACHMENT_CF)
.setKey(attachmentId)
.setName(CONTENT)
.execute()
.get();
attachment.setContent(columnAttachment.getValue());
return attachment;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
@Cacheable("attachment-cache")
public Attachment findAttachmentById(String attachmentId) {
if (attachmentId == null) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("Finding attachment : " + attachmentId);
}
Attachment attachment = this.findAttachmentMetadataById(attachmentId);
if (attachment == null) {
return null;
}
ColumnQuery<String, String, byte[]> queryAttachment = HFactory.createColumnQuery(keyspaceOperator,
StringSerializer.get(), StringSerializer.get(), BytesArraySerializer.get());
HColumn<String, byte[]> columnAttachment =
queryAttachment.setColumnFamily(ATTACHMENT_CF)
.setKey(attachmentId)
.setName(CONTENT)
.execute()
.get();
attachment.setContent(columnAttachment.getValue());
return attachment;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping(value = "/rest/statuses/{statusId}",
method = RequestMethod.PATCH)
@ResponseBody
public StatusDTO updateStatusV3(@RequestBody ActionStatus action, @PathVariable("statusId") String statusId) {
try {
StatusDTO status = timelineService.getStatus(statusId);
if(action.isFavorite() != null && status.isFavorite() != action.isFavorite()){
if(action.isFavorite()){
timelineService.addFavoriteStatus(statusId);
}
else {
timelineService.removeFavoriteStatus(statusId);
}
status.setFavorite(action.isFavorite());
}
if(action.isShared() != null && action.isShared()){
timelineService.shareStatus(statusId);
}
return status;
} catch (Exception e) {
if (log.isDebugEnabled()) {
e.printStackTrace();
}
return null;
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequestMapping(value = "/rest/statuses/{statusId}",
method = RequestMethod.PATCH)
@ResponseBody
public StatusDTO updateStatusV3(@RequestBody ActionStatus action, @PathVariable("statusId") String statusId) {
try {
StatusDTO status = timelineService.getStatus(statusId);
if(action.isFavorite() != null && status.isFavorite() != action.isFavorite()){
if(action.isFavorite()){
timelineService.addFavoriteStatus(statusId);
}
else {
timelineService.removeFavoriteStatus(statusId);
}
status.setFavorite(action.isFavorite());
}
if(action.isShared() != null && action.isShared()){
timelineService.shareStatus(statusId);
}
if(action.isAnnounced() != null && action.isAnnounced()){
timelineService.announceStatus(statusId);
}
return status;
} catch (Exception e) {
if (log.isDebugEnabled()) {
e.printStackTrace();
}
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void replyToStatus(String content, String replyTo) throws ArchivedGroupException {
Status originalStatus = statusRepository.findStatusById(replyTo);
Group group = null;
if (originalStatus.getGroupId() != null) {
group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId());
}
if (group.isArchivedGroup()) {
throw new ArchivedGroupException();
}
if (!originalStatus.getReplyTo().equals("")) {
// Original status is also a reply, replying to the real original status instead
Status realOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId());
Status replyStatus = createStatus(
content,
realOriginalStatus.getStatusPrivate(),
group,
realOriginalStatus.getStatusId(),
originalStatus.getStatusId(),
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId());
} else {
// The original status of the discussion is the one we reply to
Status replyStatus =
createStatus(content,
originalStatus.getStatusPrivate(),
group,
replyTo,
replyTo,
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId());
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public void replyToStatus(String content, String replyTo) throws ArchivedGroupException {
Status originalStatus = statusRepository.findStatusById(replyTo);
Group group = null;
if (originalStatus.getGroupId() != null) {
group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId());
if (group.isArchivedGroup()) {
throw new ArchivedGroupException();
}
}
if (!originalStatus.getReplyTo().equals("")) {
// Original status is also a reply, replying to the real original status instead
Status realOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId());
Status replyStatus = createStatus(
content,
realOriginalStatus.getStatusPrivate(),
group,
realOriginalStatus.getStatusId(),
originalStatus.getStatusId(),
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId());
} else {
// The original status of the discussion is the one we reply to
Status replyStatus =
createStatus(content,
originalStatus.getStatusPrivate(),
group,
replyTo,
replyTo,
originalStatus.getUsername());
discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = this.blockWhenExhausted;
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
_factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = _factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
_factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = _factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException {
Map toDestroy = new HashMap();
synchronized (this) {
assertOpen();
if (0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
if (pool != null) {
// Copy objects to new list so pool.queue can be cleared
// inside the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
_factory = factory;
}
}
destroy(toDestroy);
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException {
Map toDestroy = new HashMap();
final KeyedPoolableObjectFactory oldFactory = _factory;
synchronized (this) {
assertOpen();
if (0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
if (pool != null) {
// Copy objects to new list so pool.queue can be cleared
// inside the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
_factory = factory;
}
}
destroy(toDestroy, oldFactory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object borrowObject() throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch();
synchronized (this) {
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated from the pool above
if(latch._pair == null) {
// check if we were allowed to create one
if(latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(_whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(_maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = _maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if(null == latch._pair) {
try {
Object obj = _factory.makeObject();
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
_numInternalProcessing--;
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(latch._pair.value);
if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized(this) {
_numInternalProcessing--;
_numActive++;
}
return latch._pair.value;
}
catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
_numInternalProcessing--;
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
else {
continue; // keep looping
}
}
}
}
#location 56
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object borrowObject() throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch();
byte whenExhaustedAction;
long maxWait;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
whenExhaustedAction = _whenExhaustedAction;
maxWait = _maxWait;
// Add this request to the queue
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated from the pool above
if(latch._pair == null) {
// check if we were allowed to create one
if(latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if(null == latch._pair) {
try {
Object obj = _factory.makeObject();
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
_numInternalProcessing--;
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(latch._pair.value);
if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized(this) {
_numInternalProcessing--;
_numActive++;
}
return latch._pair.value;
}
catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
_numInternalProcessing--;
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
else {
continue; // keep looping
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object borrowObject(Object key) throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch(key);
synchronized (this) {
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated
if (null == latch._pair) {
// Check to see if we were allowed to create one
if (latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(_whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(_maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = _maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if (null == latch._pair) {
try {
Object obj = _factory.makeObject(key);
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(key, latch._pair.value);
if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch._pool.incrementActiveCount();
}
return latch._pair.value;
} catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(key, latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: "
+ e.getMessage());
}
else {
continue; // keep looping
}
}
}
}
#location 55
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object borrowObject(Object key) throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch(key);
byte whenExhaustedAction;
long maxWait;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
whenExhaustedAction = _whenExhaustedAction;
maxWait = _maxWait;
// Add this request to the queue
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated
if (null == latch._pair) {
// Check to see if we were allowed to create one
if (latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if (null == latch._pair) {
try {
Object obj = _factory.makeObject(key);
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(key, latch._pair.value);
if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch._pool.incrementActiveCount();
}
return latch._pair.value;
} catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(key, latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: "
+ e.getMessage());
}
else {
continue; // keep looping
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void addObject(Object key) throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
Object obj = _factory.makeObject(key);
synchronized (this) {
try {
assertOpen();
addObjectToPool(key, obj, false);
} catch (IllegalStateException ex) { // Pool closed
try {
_factory.destroyObject(key, obj);
} catch (Exception ex2) {
// swallow
}
throw ex;
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void addObject(Object key) throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
Object obj = _factory.makeObject(key);
try {
assertOpen();
addObjectToPool(key, obj, false);
} catch (IllegalStateException ex) { // Pool closed
try {
_factory.destroyObject(key, obj);
} catch (Exception ex2) {
// swallow
}
throw ex;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clear(Object key) {
Map toDestroy = new HashMap();
final ObjectQueue pool;
synchronized (this) {
pool = (ObjectQueue)(_poolMap.remove(key));
if (pool == null) {
return;
} else {
_poolList.remove(key);
}
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
destroy(toDestroy);
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clear(Object key) {
Map toDestroy = new HashMap();
final ObjectQueue pool;
synchronized (this) {
pool = (ObjectQueue)(_poolMap.remove(key));
if (pool == null) {
return;
} else {
_poolList.remove(key);
}
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
destroy(toDestroy, _factory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object borrowObject(Object key) throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch(key);
synchronized (this) {
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated
if (null == latch._pair) {
// Check to see if we were allowed to create one
if (latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(_whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(_maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = _maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if (null == latch._pair) {
try {
Object obj = _factory.makeObject(key);
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(key, latch._pair.value);
if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch._pool.incrementActiveCount();
}
return latch._pair.value;
} catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(key, latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: "
+ e.getMessage());
}
else {
continue; // keep looping
}
}
}
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object borrowObject(Object key) throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch(key);
byte whenExhaustedAction;
long maxWait;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
whenExhaustedAction = _whenExhaustedAction;
maxWait = _maxWait;
// Add this request to the queue
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated
if (null == latch._pair) {
// Check to see if we were allowed to create one
if (latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if (null == latch._pair) {
try {
Object obj = _factory.makeObject(key);
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(key, latch._pair.value);
if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch._pool.incrementActiveCount();
}
return latch._pair.value;
} catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(key, latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
latch._pool.decrementInternalProcessingCount();
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: "
+ e.getMessage());
}
else {
continue; // keep looping
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clearOldest() {
// Map of objects to destroy my key
final Map toDestroy = new HashMap();
// build sorted map of idle objects
final Map map = new TreeMap();
synchronized (this) {
for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) {
final Object key = keyiter.next();
final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
for (Iterator it = list.iterator(); it.hasNext();) {
// each item into the map uses the objectimestamppair object
// as the key. It then gets sorted based on the timstamp field
// each value in the map is the parent list it belongs in.
map.put(it.next(), key);
}
}
// Now iterate created map and kill the first 15% plus one to account for zero
Set setPairKeys = map.entrySet();
int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
Iterator iter = setPairKeys.iterator();
while (iter.hasNext() && itemsToRemove > 0) {
Map.Entry entry = (Map.Entry) iter.next();
// kind of backwards on naming. In the map, each key is the objecttimestamppair
// because it has the ordering with the timestamp value. Each value that the
// key references is the key of the list it belongs to.
Object key = entry.getValue();
ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey();
final CursorableLinkedList list =
((ObjectQueue)(_poolMap.get(key))).queue;
list.remove(pairTimeStamp);
if (toDestroy.containsKey(key)) {
((List)toDestroy.get(key)).add(pairTimeStamp);
} else {
List listForKey = new ArrayList();
listForKey.add(pairTimeStamp);
toDestroy.put(key, listForKey);
}
// if that was the last object for that key, drop that pool
if (list.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
_totalIdle--;
_totalInternalProcessing++;
itemsToRemove--;
}
}
destroy(toDestroy);
}
#location 53
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clearOldest() {
// Map of objects to destroy my key
final Map toDestroy = new HashMap();
// build sorted map of idle objects
final Map map = new TreeMap();
synchronized (this) {
for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) {
final Object key = keyiter.next();
final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
for (Iterator it = list.iterator(); it.hasNext();) {
// each item into the map uses the objectimestamppair object
// as the key. It then gets sorted based on the timstamp field
// each value in the map is the parent list it belongs in.
map.put(it.next(), key);
}
}
// Now iterate created map and kill the first 15% plus one to account for zero
Set setPairKeys = map.entrySet();
int itemsToRemove = ((int) (map.size() * 0.15)) + 1;
Iterator iter = setPairKeys.iterator();
while (iter.hasNext() && itemsToRemove > 0) {
Map.Entry entry = (Map.Entry) iter.next();
// kind of backwards on naming. In the map, each key is the objecttimestamppair
// because it has the ordering with the timestamp value. Each value that the
// key references is the key of the list it belongs to.
Object key = entry.getValue();
ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey();
final CursorableLinkedList list =
((ObjectQueue)(_poolMap.get(key))).queue;
list.remove(pairTimeStamp);
if (toDestroy.containsKey(key)) {
((List)toDestroy.get(key)).add(pairTimeStamp);
} else {
List listForKey = new ArrayList();
listForKey.add(pairTimeStamp);
toDestroy.put(key, listForKey);
}
// if that was the last object for that key, drop that pool
if (list.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
_totalIdle--;
_totalInternalProcessing++;
itemsToRemove--;
}
}
destroy(toDestroy, _factory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public long getIdleTimeMillis() {
return System.currentTimeMillis() - lastActiveTime;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public long getIdleTimeMillis() {
return System.currentTimeMillis() - lastReturnTime;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clear() {
List toDestroy = new ArrayList();
synchronized(this) {
toDestroy.addAll(_pool);
_numInternalProcessing = _numInternalProcessing + _pool._size;
_pool.clear();
}
destroy(toDestroy);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clear() {
List toDestroy = new ArrayList();
synchronized(this) {
toDestroy.addAll(_pool);
_numInternalProcessing = _numInternalProcessing + _pool._size;
_pool.clear();
}
destroy(toDestroy, _factory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
synchronized (evictionLock) {
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
_factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = _factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
synchronized (this) {
if(_pool.isEmpty()) {
return;
}
if (null == _evictionCursor) {
_evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0));
}
}
for (int i=0,m=getNumTests();i<m;i++) {
final ObjectTimestampPair<T> pair;
synchronized (this) {
if ((_lifo && !_evictionCursor.hasPrevious()) ||
!_lifo && !_evictionCursor.hasNext()) {
_evictionCursor.close();
_evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0);
}
pair = _lifo ?
_evictionCursor.previous() :
_evictionCursor.next();
_evictionCursor.remove();
_numInternalProcessing++;
}
boolean removeObject = false;
final long idleTimeMilis = System.currentTimeMillis() - pair.getTstamp();
if ((getMinEvictableIdleTimeMillis() > 0) &&
(idleTimeMilis > getMinEvictableIdleTimeMillis())) {
removeObject = true;
} else if ((getSoftMinEvictableIdleTimeMillis() > 0) &&
(idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) &&
((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing
removeObject = true;
}
if(getTestWhileIdle() && !removeObject) {
boolean active = false;
try {
_factory.activateObject(pair.getValue());
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(pair.getValue())) {
removeObject=true;
} else {
try {
_factory.passivateObject(pair.getValue());
} catch(Exception e) {
removeObject=true;
}
}
}
}
if (removeObject) {
try {
_factory.destroyObject(pair.getValue());
} catch(Exception e) {
// ignored
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_numInternalProcessing--;
}
}
allocate();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (_pool.size() == 0) {
return;
}
PooledObject<T> underTest = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if (_evictionIterator == null || !_evictionIterator.hasNext()) {
if (getLifo()) {
_evictionIterator = _pool.descendingIterator();
} else {
_evictionIterator = _pool.iterator();
}
}
if (!_evictionIterator.hasNext()) {
// Pool exhausted, nothing to do here
return;
} else {
try {
underTest = _evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
_evictionIterator = null;
continue;
}
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (getMinEvictableIdleTimeMillis() > 0 &&
getMinEvictableIdleTimeMillis() <
underTest.getIdleTimeMillis() ||
(getSoftMinEvictableIdleTimeMillis() > 0 &&
getSoftMinEvictableIdleTimeMillis() <
underTest.getIdleTimeMillis() &&
getMinIdle() < _pool.size())) {
destroy(underTest);
} else {
if (getTestWhileIdle()) {
boolean active = false;
try {
_factory.activateObject(underTest.getObject());
active = true;
} catch(Exception e) {
destroy(underTest);
}
if(active) {
if(!_factory.validateObject(underTest.getObject())) {
destroy(underTest);
} else {
try {
_factory.passivateObject(underTest.getObject());
} catch(Exception e) {
destroy(underTest);
}
}
}
}
if (!underTest.endEvictionTest()) {
// TODO - May need to add code here once additional states
// are used
}
}
}
return;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
// Initialize key to last key value
Object key = null;
synchronized (this) {
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((_minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
_minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(_testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
}
#location 84
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
Object key = null;
boolean testWhileIdle;
long minEvictableIdleTimeMillis;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
testWhileIdle = _testWhileIdle;
minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis;
// Initialize key to last key value
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
synchronized (evictionLock) {
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public long getActiveTimeMillis() {
if (lastReturnTime > lastBorrowTime) {
return lastReturnTime - lastBorrowTime;
} else {
return System.currentTimeMillis() - lastBorrowTime;
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public long getActiveTimeMillis() {
// Take copies to avoid threading issues
long rTime = lastReturnTime;
long bTime = lastBorrowTime;
if (rTime > bTime) {
return rTime - bTime;
} else {
return System.currentTimeMillis() - bTime;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
List toDestroy = new ArrayList();
synchronized (this) {
assertOpen();
if(0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
toDestroy.addAll(_pool);
_numInternalProcessing = _numInternalProcessing + _pool._size;
_pool.clear();
}
_factory = factory;
}
destroy(toDestroy);
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
List toDestroy = new ArrayList();
final PoolableObjectFactory oldFactory = _factory;
synchronized (this) {
assertOpen();
if(0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
toDestroy.addAll(_pool);
_numInternalProcessing = _numInternalProcessing + _pool._size;
_pool.clear();
}
_factory = factory;
}
destroy(toDestroy, oldFactory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
updateStatsBorrow(p, waitTime);
return p.getObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
synchronized (this) {
if(_pool.isEmpty()) {
return;
}
if (null == _evictionCursor) {
_evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0));
}
}
for (int i=0,m=getNumTests();i<m;i++) {
final ObjectTimestampPair<T> pair;
synchronized (this) {
if ((_lifo && !_evictionCursor.hasPrevious()) ||
!_lifo && !_evictionCursor.hasNext()) {
_evictionCursor.close();
_evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0);
}
pair = _lifo ?
_evictionCursor.previous() :
_evictionCursor.next();
_evictionCursor.remove();
_numInternalProcessing++;
}
boolean removeObject = false;
final long idleTimeMilis = System.currentTimeMillis() - pair.getTstamp();
if ((getMinEvictableIdleTimeMillis() > 0) &&
(idleTimeMilis > getMinEvictableIdleTimeMillis())) {
removeObject = true;
} else if ((getSoftMinEvictableIdleTimeMillis() > 0) &&
(idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) &&
((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing
removeObject = true;
}
if(getTestWhileIdle() && !removeObject) {
boolean active = false;
try {
_factory.activateObject(pair.getValue());
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(pair.getValue())) {
removeObject=true;
} else {
try {
_factory.passivateObject(pair.getValue());
} catch(Exception e) {
removeObject=true;
}
}
}
}
if (removeObject) {
try {
_factory.destroyObject(pair.getValue());
} catch(Exception e) {
// ignored
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_numInternalProcessing--;
}
}
allocate();
}
#location 62
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (_pool.size() == 0) {
return;
}
PooledObject<T> underTest = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if (_evictionIterator == null || !_evictionIterator.hasNext()) {
if (getLifo()) {
_evictionIterator = _pool.descendingIterator();
} else {
_evictionIterator = _pool.iterator();
}
}
if (!_evictionIterator.hasNext()) {
// Pool exhausted, nothing to do here
return;
} else {
try {
underTest = _evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
_evictionIterator = null;
continue;
}
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (getMinEvictableIdleTimeMillis() > 0 &&
getMinEvictableIdleTimeMillis() <
underTest.getIdleTimeMillis() ||
(getSoftMinEvictableIdleTimeMillis() > 0 &&
getSoftMinEvictableIdleTimeMillis() <
underTest.getIdleTimeMillis() &&
getMinIdle() < _pool.size())) {
destroy(underTest);
} else {
if (getTestWhileIdle()) {
boolean active = false;
try {
_factory.activateObject(underTest.getObject());
active = true;
} catch(Exception e) {
destroy(underTest);
}
if(active) {
if(!_factory.validateObject(underTest.getObject())) {
destroy(underTest);
} else {
try {
_factory.passivateObject(underTest.getObject());
} catch(Exception e) {
destroy(underTest);
}
}
}
}
if (!underTest.endEvictionTest()) {
// TODO - May need to add code here once additional states
// are used
}
}
}
return;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clear() {
Map toDestroy = new HashMap();
synchronized (this) {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
destroy(toDestroy);
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clear() {
Map toDestroy = new HashMap();
synchronized (this) {
for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) {
Object key = it.next();
ObjectQueue pool = (ObjectQueue)_poolMap.get(key);
// Copy objects to new list so pool.queue can be cleared inside
// the sync
List objects = new ArrayList();
objects.addAll(pool.queue);
toDestroy.put(key, objects);
it.remove();
_poolList.remove(key);
_totalIdle = _totalIdle - pool.queue.size();
_totalInternalProcessing =
_totalInternalProcessing + pool.queue.size();
pool.queue.clear();
}
}
destroy(toDestroy, _factory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void printStackTrace(PrintWriter writer) {
if (borrowedBy != null) {
borrowedBy.printStackTrace(writer);
}
if (usedBy != null) {
usedBy.printStackTrace(writer);
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void printStackTrace(PrintWriter writer) {
Exception borrowedBy = this.borrowedBy;
if (borrowedBy != null) {
borrowedBy.printStackTrace(writer);
}
Exception usedBy = this.usedBy;
if (usedBy != null) {
usedBy.printStackTrace(writer);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
synchronized (evictionLock) {
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
// Initialize key to last key value
Object key = null;
synchronized (this) {
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((_minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
_minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(_testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
Object key = null;
boolean testWhileIdle;
long minEvictableIdleTimeMillis;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
testWhileIdle = _testWhileIdle;
minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis;
// Initialize key to last key value
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public long getActiveTimeMillis() {
if (lastReturnTime > lastBorrowTime) {
return lastReturnTime - lastBorrowTime;
} else {
return System.currentTimeMillis() - lastBorrowTime;
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public long getActiveTimeMillis() {
// Take copies to avoid threading issues
long rTime = lastReturnTime;
long bTime = lastBorrowTime;
if (rTime > bTime) {
return rTime - bTime;
} else {
return System.currentTimeMillis() - bTime;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void destroy(Map m, KeyedPoolableObjectFactory factory) {
for (Iterator keys = m.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Collection c = (Collection) m.get(key);
for (Iterator it = c.iterator(); it.hasNext();) {
try {
factory.destroyObject(
key,((ObjectTimestampPair)(it.next())).value);
} catch(Exception e) {
// ignore error, keep destroying the rest
} finally {
synchronized(this) {
_totalInternalProcessing--;
allocate();
}
}
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private void destroy(Map m, KeyedPoolableObjectFactory factory) {
for (Iterator entries = m.entrySet().iterator(); entries.hasNext();) {
Map.Entry entry = (Entry) entries.next();
Object key = entry.getKey();
Collection c = (Collection) entry.getValue();
for (Iterator it = c.iterator(); it.hasNext();) {
try {
factory.destroyObject(
key,((ObjectTimestampPair)(it.next())).value);
} catch(Exception e) {
// ignore error, keep destroying the rest
} finally {
synchronized(this) {
_totalInternalProcessing--;
allocate();
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
// Initialize key to last key value
Object key = null;
synchronized (this) {
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((_minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
_minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(_testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
}
#location 88
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
Object key = null;
boolean testWhileIdle;
long minEvictableIdleTimeMillis;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
testWhileIdle = _testWhileIdle;
minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis;
// Initialize key to last key value
if (_evictionKeyCursor != null &&
_evictionKeyCursor._lastReturned != null) {
key = _evictionKeyCursor._lastReturned.value();
}
}
for (int i=0,m=getNumTests(); i<m; i++) {
final ObjectTimestampPair pair;
synchronized (this) {
// make sure pool map is not empty; otherwise do nothing
if (_poolMap == null || _poolMap.size() == 0) {
continue;
}
// if we don't have a key cursor, then create one
if (null == _evictionKeyCursor) {
resetEvictionKeyCursor();
key = null;
}
// if we don't have an object cursor, create one
if (null == _evictionCursor) {
// if the _evictionKeyCursor has a next value, use this key
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else {
// Reset the key cursor and try again
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
if (_evictionCursor == null) {
continue; // should never happen; do nothing
}
// If eviction cursor is exhausted, try to move
// to the next key and reset
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
} else { // Need to reset Key cursor
resetEvictionKeyCursor();
if (_evictionKeyCursor != null) {
if (_evictionKeyCursor.hasNext()) {
key = _evictionKeyCursor.next();
resetEvictionObjectCursor(key);
}
}
}
}
}
if((_lifo && !_evictionCursor.hasPrevious()) ||
(!_lifo && !_evictionCursor.hasNext())) {
continue; // reset failed, do nothing
}
// if LIFO and the _evictionCursor has a previous object,
// or FIFO and _evictionCursor has a next object, test it
pair = _lifo ?
(ObjectTimestampPair) _evictionCursor.previous() :
(ObjectTimestampPair) _evictionCursor.next();
_evictionCursor.remove();
_totalIdle--;
_totalInternalProcessing++;
}
boolean removeObject=false;
if((minEvictableIdleTimeMillis > 0) &&
(System.currentTimeMillis() - pair.tstamp >
minEvictableIdleTimeMillis)) {
removeObject=true;
}
if(testWhileIdle && removeObject == false) {
boolean active = false;
try {
_factory.activateObject(key,pair.value);
active = true;
} catch(Exception e) {
removeObject=true;
}
if(active) {
if(!_factory.validateObject(key,pair.value)) {
removeObject=true;
} else {
try {
_factory.passivateObject(key,pair.value);
} catch(Exception e) {
removeObject=true;
}
}
}
}
if(removeObject) {
try {
_factory.destroyObject(key, pair.value);
} catch(Exception e) {
// ignored
} finally {
// Do not remove the key from the _poolList or _poolmap,
// even if the list stored in the _poolMap for this key is
// empty when minIdle > 0.
//
// Otherwise if it was the last object for that key,
// drop that pool
if (_minIdle == 0) {
synchronized (this) {
ObjectQueue objectQueue =
(ObjectQueue)_poolMap.get(key);
if (objectQueue != null &&
objectQueue.queue.isEmpty()) {
_poolMap.remove(key);
_poolList.remove(key);
}
}
}
}
}
synchronized (this) {
if(!removeObject) {
_evictionCursor.add(pair);
_totalIdle++;
if (_lifo) {
// Skip over the element we just added back
_evictionCursor.previous();
}
}
_totalInternalProcessing--;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int compareTo(PooledObject<T> other) {
final long lastActiveDiff =
this.getLastActiveTime() - other.getLastActiveTime();
if (lastActiveDiff == 0) {
// make sure the natural ordering is consistent with equals
// see java.lang.Comparable Javadocs
return System.identityHashCode(this) - System.identityHashCode(other);
}
// handle int overflow
return (int)Math.min(Math.max(lastActiveDiff, Integer.MIN_VALUE), Integer.MAX_VALUE);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public int compareTo(PooledObject<T> other) {
final long lastActiveDiff =
this.getLastReturnTime() - other.getLastReturnTime();
if (lastActiveDiff == 0) {
// make sure the natural ordering is consistent with equals
// see java.lang.Comparable Javadocs
return System.identityHashCode(this) - System.identityHashCode(other);
}
// handle int overflow
return (int)Math.min(Math.max(lastActiveDiff, Integer.MIN_VALUE), Integer.MAX_VALUE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
_factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = _factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T borrowObject(K key, long borrowMaxWait) throws Exception {
assertOpen();
PooledObject<T> p = null;
// Get local copy of current config so it is consistent for entire
// method execution
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
if (blockWhenExhausted) {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null && objectDeque != null) {
if (borrowMaxWait < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = objectDeque.getIdleObjects().pollFirst(
borrowMaxWait, TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
if (objectDeque != null) {
p = objectDeque.getIdleObjects().pollFirst();
}
if (p == null) {
create = true;
p = create(key);
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
factory.activateObject(key, p.getObject());
} catch (Exception e) {
try {
destroy(key, p, true);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(key, p.getObject());
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
}
if (!validate) {
try {
destroy(key, p, true);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
} finally {
deregister(key);
}
borrowedCount.incrementAndGet();
synchronized (idleTimes) {
idleTimes.add(Long.valueOf(p.getIdleTimeMillis()));
idleTimes.poll();
}
synchronized (waitTimes) {
waitTimes.add(Long.valueOf(waitTime));
waitTimes.poll();
}
synchronized (maxBorrowWaitTimeMillisLock) {
if (waitTime > maxBorrowWaitTimeMillis) {
maxBorrowWaitTimeMillis = waitTime;
}
}
return p.getObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object borrowObject() throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch();
synchronized (this) {
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated from the pool above
if(latch._pair == null) {
// check if we were allowed to create one
if(latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(_whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(_maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = _maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if(null == latch._pair) {
try {
Object obj = _factory.makeObject();
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
_numInternalProcessing--;
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(latch._pair.value);
if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized(this) {
_numInternalProcessing--;
_numActive++;
}
return latch._pair.value;
}
catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
_numInternalProcessing--;
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
else {
continue; // keep looping
}
}
}
}
#location 50
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object borrowObject() throws Exception {
long starttime = System.currentTimeMillis();
Latch latch = new Latch();
byte whenExhaustedAction;
long maxWait;
synchronized (this) {
// Get local copy of current config. Can't sync when used later as
// it can result in a deadlock. Has the added advantage that config
// is consistent for entire method execution
whenExhaustedAction = _whenExhaustedAction;
maxWait = _maxWait;
// Add this request to the queue
_allocationQueue.add(latch);
allocate();
}
for(;;) {
synchronized (this) {
assertOpen();
}
// If no object was allocated from the pool above
if(latch._pair == null) {
// check if we were allowed to create one
if(latch._mayCreate) {
// allow new object to be created
} else {
// the pool is exhausted
switch(whenExhaustedAction) {
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
synchronized (this) {
_allocationQueue.remove(latch);
}
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try {
synchronized (latch) {
if(maxWait <= 0) {
latch.wait();
} else {
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
latch.wait(waitTime);
}
}
}
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
throw new NoSuchElementException("Timeout waiting for idle object");
} else {
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized.");
}
}
}
boolean newlyCreated = false;
if(null == latch._pair) {
try {
Object obj = _factory.makeObject();
latch._pair = new ObjectTimestampPair(obj);
newlyCreated = true;
} finally {
if (!newlyCreated) {
// object cannot be created
synchronized (this) {
_numInternalProcessing--;
// No need to reset latch - about to throw exception
allocate();
}
}
}
}
// activate & validate the object
try {
_factory.activateObject(latch._pair.value);
if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) {
throw new Exception("ValidateObject failed");
}
synchronized(this) {
_numInternalProcessing--;
_numActive++;
}
return latch._pair.value;
}
catch (Throwable e) {
// object cannot be activated or is invalid
try {
_factory.destroyObject(latch._pair.value);
} catch (Throwable e2) {
// cannot destroy broken object
}
synchronized (this) {
_numInternalProcessing--;
latch.reset();
_allocationQueue.add(0, latch);
allocate();
}
if(newlyCreated) {
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
else {
continue; // keep looping
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
#location 50
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void evict() throws Exception {
assertOpen();
if (getNumIdle() == 0) {
return;
}
synchronized (evictionLock) {
boolean testWhileIdle = getTestWhileIdle();
long idleEvictTime = Long.MAX_VALUE;
if (getMinEvictableIdleTimeMillis() > 0) {
idleEvictTime = getMinEvictableIdleTimeMillis();
}
PooledObject<T> underTest = null;
LinkedBlockingDeque<PooledObject<T>> idleObjects = null;
for (int i = 0, m = getNumTests(); i < m; i++) {
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
List<K> keyCopy = new ArrayList<K>();
keyCopy.addAll(poolKeyList);
evictionKeyIterator = keyCopy.iterator();
}
while (evictionKeyIterator.hasNext()) {
evictionKey = evictionKeyIterator.next();
ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
if (objectDeque == null) {
continue;
}
idleObjects = objectDeque.getIdleObjects();
if (getLifo()) {
evictionIterator = idleObjects.descendingIterator();
} else {
evictionIterator = idleObjects.iterator();
}
if (evictionIterator.hasNext()) {
break;
}
evictionIterator = null;
}
}
if (evictionIterator == null) {
// Pools exhausted
return;
}
try {
underTest = evictionIterator.next();
} catch (NoSuchElementException nsee) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
evictionIterator = null;
continue;
}
if (!underTest.startEvictionTest()) {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--;
continue;
}
if (idleEvictTime < underTest.getIdleTimeMillis()) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
boolean active = false;
try {
factory.activateObject(evictionKey,
underTest.getObject());
active = true;
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
if (active) {
if (!factory.validateObject(evictionKey,
underTest.getObject())) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
try {
factory.passivateObject(evictionKey,
underTest.getObject());
} catch (Exception e) {
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
}
}
}
}
if (!underTest.endEvictionTest(idleObjects)) {
// TODO - May need to add code here once additional states
// are used
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) {
Elements elementUtils = processingEnv.getElementUtils();
Types typeUtils = processingEnv.getTypeUtils();
Filer filer = processingEnv.getFiler();
//
// Processor options
//
boolean isLibrary = false;
String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY);
if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) {
isLibrary = true;
}
String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS);
if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) {
supportAnnotations = false;
}
String additionalBuilderAnnotations[] = {};
String builderAnnotationsStr =
processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS);
if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) {
additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter
}
List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>();
JavaWriter jw = null;
// REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set
Set<TypeElement> fragmentClasses = new HashSet<TypeElement>();
Element[] origHelper = null;
// Search for @Arg fields
for (Element element : env.getElementsAnnotatedWith(Arg.class)) {
try {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Check if its a fragment
if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) {
throw new ProcessingException(element,
"@Arg can only be used on fragment fields (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers().contains(Modifier.FINAL)) {
throw new ProcessingException(element,
"@Arg fields must not be final (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers()
.contains(Modifier.STATIC)) {
throw new ProcessingException(element,
"@Arg fields must not be static (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
// Skip abstract classes
if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) {
fragmentClasses.add(enclosingElement);
}
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Search for "just" @InheritedFragmentArgs --> DEPRECATED
for (Element element : env.getElementsAnnotatedWith(FragmentArgsInherited.class)) {
try {
scanForAnnotatedFragmentClasses(env, FragmentArgsInherited.class, fragmentClasses, element);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Search for "just" @FragmentWithArgs
for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) {
try {
scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Store the key - value for the generated FragmentArtMap class
Map<String, String> autoMapping = new HashMap<String, String>();
for (TypeElement fragmentClass : fragmentClasses) {
JavaFileObject jfo = null;
try {
AnnotatedFragment fragment = collectArgumentsForType(fragmentClass);
String builder = fragment.getSimpleName() + "Builder";
List<Element> originating = new ArrayList<Element>(10);
originating.add(fragmentClass);
TypeMirror superClass = fragmentClass.getSuperclass();
while (superClass.getKind() != TypeKind.NONE) {
TypeElement element = (TypeElement) typeUtils.asElement(superClass);
if (element.getQualifiedName().toString().startsWith("android.")) {
break;
}
originating.add(element);
superClass = element.getSuperclass();
}
String qualifiedFragmentName = fragment.getQualifiedName();
String qualifiedBuilderName = qualifiedFragmentName + "Builder";
Element[] orig = originating.toArray(new Element[originating.size()]);
origHelper = orig;
jfo = filer.createSourceFile(qualifiedBuilderName, orig);
Writer writer = jfo.openWriter();
jw = new JavaWriter(writer);
writePackage(jw, fragmentClass);
jw.emitImports("android.os.Bundle");
if (supportAnnotations) {
jw.emitImports("android.support.annotation.NonNull");
if (!fragment.getOptionalFields().isEmpty()) {
jw.emitImports("android.support.annotation.Nullable");
}
}
jw.emitEmptyLine();
// Additional builder annotations
for (String builderAnnotation : additionalBuilderAnnotations) {
jw.emitAnnotation(builderAnnotation);
}
jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
if (!fragment.getBundlerVariableMap().isEmpty()) {
jw.emitEmptyLine();
for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) {
jw.emitField(e.getKey(), e.getValue(),
EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC),
"new " + e.getKey() + "()");
}
}
jw.emitEmptyLine();
jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL),
"new Bundle()");
jw.emitEmptyLine();
Set<ArgumentAnnotatedField> required = fragment.getRequiredFields();
String[] args = new String[required.size() * 2];
int index = 0;
for (ArgumentAnnotatedField arg : required) {
boolean annotate = supportAnnotations && !arg.isPrimitive();
args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType();
args[index++] = arg.getVariableName();
}
jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args);
for (ArgumentAnnotatedField arg : required) {
writePutArguments(jw, arg.getVariableName(), "mArguments", arg);
}
jw.endMethod();
if (!required.isEmpty()) {
jw.emitEmptyLine();
writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args);
}
Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields();
for (ArgumentAnnotatedField arg : optionalArguments) {
writeBuilderMethod(builder, jw, arg);
}
jw.emitEmptyLine();
writeBuildBundleMethod(jw);
jw.emitEmptyLine();
writeInjectMethod(jw, fragmentClass, fragment);
jw.emitEmptyLine();
writeBuildMethod(jw, fragmentClass);
jw.endType();
autoMapping.put(qualifiedFragmentName, qualifiedBuilderName);
} catch (IOException e) {
processingExceptions.add(
new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s",
fragmentClass, e.getMessage()));
} catch (ProcessingException e) {
processingExceptions.add(e);
if (jfo != null) {
jfo.delete();
}
} finally {
if (jw != null) {
try {
jw.close();
} catch (IOException e1) {
processingExceptions.add(new ProcessingException(fragmentClass,
"Unable to close javawriter while generating builder for type %s: %s",
fragmentClass, e1.getMessage()));
}
}
}
}
// Write the automapping class
if (origHelper != null && !isLibrary) {
try {
writeAutoMapping(autoMapping, origHelper);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Print errors
for (ProcessingException e : processingExceptions) {
error(e);
}
return true;
}
#location 76
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) {
Elements elementUtils = processingEnv.getElementUtils();
Types typeUtils = processingEnv.getTypeUtils();
Filer filer = processingEnv.getFiler();
//
// Processor options
//
boolean isLibrary = false;
String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY);
if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) {
isLibrary = true;
}
String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS);
if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) {
supportAnnotations = false;
}
String additionalBuilderAnnotations[] = {};
String builderAnnotationsStr =
processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS);
if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) {
additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter
}
List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>();
JavaWriter jw = null;
// REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set
Set<TypeElement> fragmentClasses = new HashSet<TypeElement>();
Element[] origHelper = null;
// Search for @Arg fields
for (Element element : env.getElementsAnnotatedWith(Arg.class)) {
try {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Check if its a fragment
if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) {
throw new ProcessingException(element,
"@Arg can only be used on fragment fields (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers().contains(Modifier.FINAL)) {
throw new ProcessingException(element,
"@Arg fields must not be final (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers()
.contains(Modifier.STATIC)) {
throw new ProcessingException(element,
"@Arg fields must not be static (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
// Skip abstract classes
if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) {
fragmentClasses.add(enclosingElement);
}
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Search for "just" @FragmentWithArgs
for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) {
try {
scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Store the key - value for the generated FragmentArtMap class
Map<String, String> autoMapping = new HashMap<String, String>();
for (TypeElement fragmentClass : fragmentClasses) {
JavaFileObject jfo = null;
try {
AnnotatedFragment fragment = collectArgumentsForType(fragmentClass);
String builder = fragment.getSimpleName() + "Builder";
List<Element> originating = new ArrayList<Element>(10);
originating.add(fragmentClass);
TypeMirror superClass = fragmentClass.getSuperclass();
while (superClass.getKind() != TypeKind.NONE) {
TypeElement element = (TypeElement) typeUtils.asElement(superClass);
if (element.getQualifiedName().toString().startsWith("android.")) {
break;
}
originating.add(element);
superClass = element.getSuperclass();
}
String qualifiedFragmentName = fragment.getQualifiedName();
String qualifiedBuilderName = qualifiedFragmentName + "Builder";
Element[] orig = originating.toArray(new Element[originating.size()]);
origHelper = orig;
jfo = filer.createSourceFile(qualifiedBuilderName, orig);
Writer writer = jfo.openWriter();
jw = new JavaWriter(writer);
writePackage(jw, fragmentClass);
jw.emitImports("android.os.Bundle");
if (supportAnnotations) {
jw.emitImports("android.support.annotation.NonNull");
if (!fragment.getOptionalFields().isEmpty()) {
jw.emitImports("android.support.annotation.Nullable");
}
}
jw.emitEmptyLine();
// Additional builder annotations
for (String builderAnnotation : additionalBuilderAnnotations) {
jw.emitAnnotation(builderAnnotation);
}
jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
if (!fragment.getBundlerVariableMap().isEmpty()) {
jw.emitEmptyLine();
for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) {
jw.emitField(e.getKey(), e.getValue(),
EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC),
"new " + e.getKey() + "()");
}
}
jw.emitEmptyLine();
jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL),
"new Bundle()");
jw.emitEmptyLine();
Set<ArgumentAnnotatedField> required = fragment.getRequiredFields();
String[] args = new String[required.size() * 2];
int index = 0;
for (ArgumentAnnotatedField arg : required) {
boolean annotate = supportAnnotations && !arg.isPrimitive();
args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType();
args[index++] = arg.getVariableName();
}
jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args);
for (ArgumentAnnotatedField arg : required) {
writePutArguments(jw, arg.getVariableName(), "mArguments", arg);
}
jw.endMethod();
if (!required.isEmpty()) {
jw.emitEmptyLine();
writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args);
}
Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields();
for (ArgumentAnnotatedField arg : optionalArguments) {
writeBuilderMethod(builder, jw, arg);
}
jw.emitEmptyLine();
writeBuildBundleMethod(jw);
jw.emitEmptyLine();
writeInjectMethod(jw, fragmentClass, fragment);
jw.emitEmptyLine();
writeBuildMethod(jw, fragmentClass);
jw.endType();
autoMapping.put(qualifiedFragmentName, qualifiedBuilderName);
} catch (IOException e) {
processingExceptions.add(
new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s",
fragmentClass, e.getMessage()));
} catch (ProcessingException e) {
processingExceptions.add(e);
if (jfo != null) {
jfo.delete();
}
} finally {
if (jw != null) {
try {
jw.close();
} catch (IOException e1) {
processingExceptions.add(new ProcessingException(fragmentClass,
"Unable to close javawriter while generating builder for type %s: %s",
fragmentClass, e1.getMessage()));
}
}
}
}
// Write the automapping class
if (origHelper != null && !isLibrary) {
try {
writeAutoMapping(autoMapping, origHelper);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Print errors
for (ProcessingException e : processingExceptions) {
error(e);
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) {
Types typeUtils = processingEnv.getTypeUtils();
Filer filer = processingEnv.getFiler();
//
// Processor options
//
boolean isLibrary = false;
String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY);
if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) {
isLibrary = true;
}
String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS);
if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) {
supportAnnotations = false;
}
String additionalBuilderAnnotations[] = {};
String builderAnnotationsStr =
processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS);
if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) {
additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter
}
String fragmentArgsLogWarnings = processingEnv.getOptions().get(OPTION_LOG_WARNINGS);
if(fragmentArgsLogWarnings != null && fragmentArgsLogWarnings.equalsIgnoreCase("false")) {
logWarnings = false;
}
List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>();
JavaWriter jw = null;
// REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set
Set<TypeElement> fragmentClasses = new HashSet<TypeElement>();
Element[] origHelper = null;
// Search for @Arg fields
for (Element element : env.getElementsAnnotatedWith(Arg.class)) {
try {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Check if its a fragment
if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) {
throw new ProcessingException(element,
"@Arg can only be used on fragment fields (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers().contains(Modifier.FINAL)) {
throw new ProcessingException(element,
"@Arg fields must not be final (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers()
.contains(Modifier.STATIC)) {
throw new ProcessingException(element,
"@Arg fields must not be static (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
// Skip abstract classes
if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) {
fragmentClasses.add(enclosingElement);
}
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Search for "just" @FragmentWithArgs
for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) {
try {
scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Store the key - value for the generated FragmentArtMap class
Map<String, String> autoMapping = new HashMap<String, String>();
for (TypeElement fragmentClass : fragmentClasses) {
JavaFileObject jfo = null;
try {
AnnotatedFragment fragment = collectArgumentsForType(fragmentClass);
String builder = fragment.getSimpleName() + "Builder";
List<Element> originating = new ArrayList<Element>(10);
originating.add(fragmentClass);
TypeMirror superClass = fragmentClass.getSuperclass();
while (superClass.getKind() != TypeKind.NONE) {
TypeElement element = (TypeElement) typeUtils.asElement(superClass);
if (element.getQualifiedName().toString().startsWith("android.")) {
break;
}
originating.add(element);
superClass = element.getSuperclass();
}
String qualifiedFragmentName = fragment.getQualifiedName();
String qualifiedBuilderName = qualifiedFragmentName + "Builder";
Element[] orig = originating.toArray(new Element[originating.size()]);
origHelper = orig;
jfo = filer.createSourceFile(qualifiedBuilderName, orig);
Writer writer = jfo.openWriter();
jw = new JavaWriter(writer);
writePackage(jw, fragmentClass);
jw.emitImports("android.os.Bundle");
if (supportAnnotations) {
jw.emitImports("android.support.annotation.NonNull");
if (!fragment.getOptionalFields().isEmpty()) {
jw.emitImports("android.support.annotation.Nullable");
}
}
jw.emitEmptyLine();
// Additional builder annotations
for (String builderAnnotation : additionalBuilderAnnotations) {
jw.emitAnnotation(builderAnnotation);
}
jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
if (!fragment.getBundlerVariableMap().isEmpty()) {
jw.emitEmptyLine();
for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) {
jw.emitField(e.getKey(), e.getValue(),
EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC),
"new " + e.getKey() + "()");
}
}
jw.emitEmptyLine();
jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL),
"new Bundle()");
jw.emitEmptyLine();
Set<ArgumentAnnotatedField> required = fragment.getRequiredFields();
String[] args = new String[required.size() * 2];
int index = 0;
for (ArgumentAnnotatedField arg : required) {
boolean annotate = supportAnnotations && !arg.isPrimitive();
args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType();
args[index++] = arg.getVariableName();
}
jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args);
for (ArgumentAnnotatedField arg : required) {
writePutArguments(jw, arg.getVariableName(), "mArguments", arg);
}
jw.endMethod();
if (!required.isEmpty()) {
jw.emitEmptyLine();
writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args);
}
Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields();
for (ArgumentAnnotatedField arg : optionalArguments) {
writeBuilderMethod(builder, jw, arg);
}
jw.emitEmptyLine();
writeBuildBundleMethod(jw);
jw.emitEmptyLine();
writeInjectMethod(jw, fragmentClass, fragment);
jw.emitEmptyLine();
writeBuildMethod(jw, fragmentClass);
jw.endType();
autoMapping.put(qualifiedFragmentName, qualifiedBuilderName);
} catch (IOException e) {
processingExceptions.add(
new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s",
fragmentClass, e.getMessage()));
} catch (ProcessingException e) {
processingExceptions.add(e);
if (jfo != null) {
jfo.delete();
}
} finally {
if (jw != null) {
try {
jw.close();
} catch (IOException e1) {
processingExceptions.add(new ProcessingException(fragmentClass,
"Unable to close javawriter while generating builder for type %s: %s",
fragmentClass, e1.getMessage()));
}
}
}
}
// Write the automapping class
if (origHelper != null && !isLibrary) {
try {
writeAutoMapping(autoMapping, origHelper);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Print errors
for (ProcessingException e : processingExceptions) {
error(e);
}
return true;
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) {
Types typeUtils = processingEnv.getTypeUtils();
Filer filer = processingEnv.getFiler();
//
// Processor options
//
boolean isLibrary = false;
String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY);
if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) {
isLibrary = true;
}
String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS);
if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) {
supportAnnotations = false;
}
String additionalBuilderAnnotations[] = {};
String builderAnnotationsStr =
processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS);
if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) {
additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter
}
String fragmentArgsLogWarnings = processingEnv.getOptions().get(OPTION_LOG_WARNINGS);
if(fragmentArgsLogWarnings != null && fragmentArgsLogWarnings.equalsIgnoreCase("false")) {
logWarnings = false;
}
String nonNullAnnotationImport = "";
String nullableAnnotationImport = "";
if(supportAnnotations) {
if (isClassAvailable("android.support.annotation.NonNull")) {
nonNullAnnotationImport = "android.support.annotation.NonNull";
nullableAnnotationImport = "android.support.annotation.Nullable";
} else if (isClassAvailable("androidx.annotation.NonNull")) {
nonNullAnnotationImport = "androidx.annotation.NonNull";
nullableAnnotationImport = "androidx.annotation.Nullable";
} else {
supportAnnotations = false;
warn(null,
"Support annotations have been disabled because neither " +
"'android.support.annotation.NonNull' nor " +
"'androidx.annotation.NonNull' could be found during processing"
);
}
}
List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>();
JavaWriter jw = null;
// REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set
Set<TypeElement> fragmentClasses = new HashSet<TypeElement>();
Element[] origHelper = null;
// Search for @Arg fields
for (Element element : env.getElementsAnnotatedWith(Arg.class)) {
try {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Check if its a fragment
if (!isFragmentClass(enclosingElement)) {
throw new ProcessingException(element,
"@Arg can only be used on fragment fields (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers().contains(Modifier.FINAL)) {
throw new ProcessingException(element,
"@Arg fields must not be final (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
if (element.getModifiers()
.contains(Modifier.STATIC)) {
throw new ProcessingException(element,
"@Arg fields must not be static (%s.%s)",
enclosingElement.getQualifiedName(), element);
}
// Skip abstract classes
if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) {
fragmentClasses.add(enclosingElement);
}
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Search for "just" @FragmentWithArgs
for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) {
try {
scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Store the key - value for the generated FragmentArtMap class
Map<String, String> autoMapping = new HashMap<String, String>();
for (TypeElement fragmentClass : fragmentClasses) {
JavaFileObject jfo = null;
try {
AnnotatedFragment fragment = collectArgumentsForType(fragmentClass);
String builder = fragment.getSimpleName() + "Builder";
List<Element> originating = new ArrayList<Element>(10);
originating.add(fragmentClass);
TypeMirror superClass = fragmentClass.getSuperclass();
while (superClass.getKind() != TypeKind.NONE) {
TypeElement element = (TypeElement) typeUtils.asElement(superClass);
if (element.getQualifiedName().toString().startsWith("android.")) {
break;
}
originating.add(element);
superClass = element.getSuperclass();
}
String qualifiedFragmentName = fragment.getQualifiedName();
String qualifiedBuilderName = qualifiedFragmentName + "Builder";
Element[] orig = originating.toArray(new Element[originating.size()]);
origHelper = orig;
jfo = filer.createSourceFile(qualifiedBuilderName, orig);
Writer writer = jfo.openWriter();
jw = new JavaWriter(writer);
writePackage(jw, fragmentClass);
jw.emitImports("android.os.Bundle");
if (supportAnnotations) {
jw.emitImports(nonNullAnnotationImport);
if (!fragment.getOptionalFields().isEmpty()) {
jw.emitImports(nullableAnnotationImport);
}
}
jw.emitEmptyLine();
// Additional builder annotations
for (String builderAnnotation : additionalBuilderAnnotations) {
jw.emitAnnotation(builderAnnotation);
}
jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
if (!fragment.getBundlerVariableMap().isEmpty()) {
jw.emitEmptyLine();
for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) {
jw.emitField(e.getKey(), e.getValue(),
EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC),
"new " + e.getKey() + "()");
}
}
jw.emitEmptyLine();
jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL),
"new Bundle()");
jw.emitEmptyLine();
Set<ArgumentAnnotatedField> required = fragment.getRequiredFields();
String[] args = new String[required.size() * 2];
int index = 0;
for (ArgumentAnnotatedField arg : required) {
boolean annotate = supportAnnotations && !arg.isPrimitive();
args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType();
args[index++] = arg.getVariableName();
}
jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args);
for (ArgumentAnnotatedField arg : required) {
writePutArguments(jw, arg.getVariableName(), "mArguments", arg);
}
jw.endMethod();
if (!required.isEmpty()) {
jw.emitEmptyLine();
writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args);
}
Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields();
for (ArgumentAnnotatedField arg : optionalArguments) {
writeBuilderMethod(builder, jw, arg);
}
jw.emitEmptyLine();
writeBuildBundleMethod(jw);
jw.emitEmptyLine();
writeInjectMethod(jw, fragmentClass, fragment);
jw.emitEmptyLine();
writeBuildMethod(jw, fragmentClass);
jw.endType();
autoMapping.put(qualifiedFragmentName, qualifiedBuilderName);
} catch (IOException e) {
processingExceptions.add(
new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s",
fragmentClass, e.getMessage()));
} catch (ProcessingException e) {
processingExceptions.add(e);
if (jfo != null) {
jfo.delete();
}
} finally {
if (jw != null) {
try {
jw.close();
} catch (IOException e1) {
processingExceptions.add(new ProcessingException(fragmentClass,
"Unable to close javawriter while generating builder for type %s: %s",
fragmentClass, e1.getMessage()));
}
}
}
}
// Write the automapping class
if (origHelper != null && !isLibrary) {
try {
writeAutoMapping(autoMapping, origHelper);
} catch (ProcessingException e) {
processingExceptions.add(e);
}
}
// Print errors
for (ProcessingException e : processingExceptions) {
error(e);
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMissingSlotMillis() throws IOException {
final String JOB_HISTORY_FILE_NAME =
"src/test/resources/job_1329348432999_0003-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist";
File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME);
byte[] contents = Files.toByteArray(jobHistoryfile);
final String JOB_CONF_FILE_NAME =
"src/test/resources/job_1329348432655_0001_conf.xml";
Configuration jobConf = new Configuration();
jobConf.addResource(new Path(JOB_CONF_FILE_NAME));
JobHistoryFileParser historyFileParser =
JobHistoryFileParserFactory.createJobHistoryFileParser(contents, jobConf);
assertNotNull(historyFileParser);
// confirm that we get back an object that can parse hadoop 2.0 files
assertTrue(historyFileParser instanceof JobHistoryFileParserHadoop2);
JobKey jobKey = new JobKey("cluster1", "user", "Sleep", 1, "job_1329348432655_0001");
historyFileParser.parse(contents, jobKey);
// this history file has only map slot millis no reduce millis
Long mbMillis = historyFileParser.getMegaByteMillis();
assertNotNull(mbMillis);
Long expValue = 10402816L;
assertEquals(expValue, mbMillis);
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMissingSlotMillis() throws IOException {
final String JOB_HISTORY_FILE_NAME =
"src/test/resources/job_1329348432999_0003-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist";
File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME);
byte[] contents = Files.toByteArray(jobHistoryfile);
final String JOB_CONF_FILE_NAME =
"src/test/resources/job_1329348432655_0001_conf.xml";
Configuration jobConf = new Configuration();
jobConf.addResource(new Path(JOB_CONF_FILE_NAME));
JobHistoryFileParserHadoop2 historyFileParser =
new JobHistoryFileParserHadoop2(jobConf);
assertNotNull(historyFileParser);
JobKey jobKey = new JobKey("cluster1", "user", "Sleep", 1, "job_1329348432655_0001");
historyFileParser.parse(contents, jobKey);
// this history file has only map slot millis no reduce millis
Long mapMbMillis = historyFileParser.getMapMbMillis();
assertNotNull(mapMbMillis);
assertEquals(mapMbMillis, new Long(178169856L));
Long reduceMbMillis = historyFileParser.getReduceMbMillis();
assertNotNull(reduceMbMillis);
assertEquals(reduceMbMillis, Constants.NOTFOUND_VALUE);
Long mbMillis = historyFileParser.getMegaByteMillis();
assertNotNull(mbMillis);
Long expValue = 188559872L;
assertEquals(expValue, mbMillis);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFlowQueueReadWrite() throws Exception {
FlowQueueService service = new FlowQueueService(UTIL.getConfiguration());
// add a couple of test flows
FlowQueueKey key1 = new FlowQueueKey(TEST_CLUSTER, Flow.Status.RUNNING,
System.currentTimeMillis(), "flow1");
Flow flow1 = new Flow(null);
flow1.setJobGraphJSON("{}");
flow1.setFlowName("flow1");
flow1.setUserName(TEST_USER);
flow1.setProgress(10);
service.updateFlow(key1, flow1);
FlowQueueKey key2 = new FlowQueueKey(TEST_CLUSTER, Flow.Status.RUNNING,
System.currentTimeMillis(), "flow2");
Flow flow2 = new Flow(null);
flow2.setJobGraphJSON("{}");
flow2.setFlowName("flow2");
flow2.setUserName(TEST_USER);
flow2.setProgress(20);
service.updateFlow(key2, flow2);
// read back one flow
Flow flow1Retrieved = service.getFlowFromQueue(key1.getCluster(), key1.getTimestamp(),
key1.getFlowId());
assertNotNull(flow1Retrieved);
assertFlowEquals(key1, flow1, flow1Retrieved);
// try reading both flows back
List<Flow> running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10);
assertNotNull(running);
assertEquals(2, running.size());
// results should be in reverse order by timestamp
Flow result1 = running.get(1);
assertFlowEquals(key1, flow1, result1);
Flow result2 = running.get(0);
assertFlowEquals(key2, flow2, result2);
// move both flows to successful status
FlowQueueKey newKey1 = new FlowQueueKey(key1.getCluster(), Flow.Status.SUCCEEDED,
key1.getTimestamp(), key1.getFlowId());
service.moveFlow(key1, newKey1);
FlowQueueKey newKey2 = new FlowQueueKey(key2.getCluster(), Flow.Status.SUCCEEDED,
key2.getTimestamp(), key2.getFlowId());
service.moveFlow(key2, newKey2);
List<Flow> succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10);
assertNotNull(succeeded);
assertEquals(2, succeeded.size());
// results should still be in reverse order by timestamp
result1 = succeeded.get(1);
assertFlowEquals(newKey1, flow1, result1);
result2 = succeeded.get(0);
assertFlowEquals(newKey2, flow2, result2);
}
#location 49
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testFlowQueueReadWrite() throws Exception {
FlowQueueService service = new FlowQueueService(UTIL.getConfiguration());
// add a couple of test flows
Flow flow1 = createFlow(service, TEST_USER, 1);
FlowQueueKey key1 = flow1.getQueueKey();
Flow flow2 = createFlow(service, TEST_USER, 2);
FlowQueueKey key2 = flow2.getQueueKey();
// read back one flow
Flow flow1Retrieved = service.getFlowFromQueue(key1.getCluster(), key1.getTimestamp(),
key1.getFlowId());
assertNotNull(flow1Retrieved);
assertFlowEquals(key1, flow1, flow1Retrieved);
// try reading both flows back
List<Flow> running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10);
assertNotNull(running);
assertEquals(2, running.size());
// results should be in reverse order by timestamp
Flow result1 = running.get(1);
assertFlowEquals(key1, flow1, result1);
Flow result2 = running.get(0);
assertFlowEquals(key2, flow2, result2);
// move both flows to successful status
FlowQueueKey newKey1 = new FlowQueueKey(key1.getCluster(), Flow.Status.SUCCEEDED,
key1.getTimestamp(), key1.getFlowId());
service.moveFlow(key1, newKey1);
FlowQueueKey newKey2 = new FlowQueueKey(key2.getCluster(), Flow.Status.SUCCEEDED,
key2.getTimestamp(), key2.getFlowId());
service.moveFlow(key2, newKey2);
List<Flow> succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10);
assertNotNull(succeeded);
assertEquals(2, succeeded.size());
// results should still be in reverse order by timestamp
result1 = succeeded.get(1);
assertFlowEquals(newKey1, flow1, result1);
result2 = succeeded.get(0);
assertFlowEquals(newKey2, flow2, result2);
// add flows from a second user
Flow flow3 = createFlow(service, TEST_USER2, 3);
FlowQueueKey key3 = flow3.getQueueKey();
// 3rd should be the only one running
running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10);
assertNotNull(running);
assertEquals(1, running.size());
assertFlowEquals(key3, flow3, running.get(0));
// move flow3 to succeeded
FlowQueueKey newKey3 = new FlowQueueKey(key3.getCluster(), Flow.Status.SUCCEEDED,
key3.getTimestamp(), key3.getFlowId());
service.moveFlow(key3, newKey3);
succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10);
assertNotNull(succeeded);
assertEquals(3, succeeded.size());
Flow result3 = succeeded.get(0);
assertFlowEquals(newKey3, flow3, result3);
// test filtering by user name
succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10,
TEST_USER2, null);
assertNotNull(succeeded);
assertEquals(1, succeeded.size());
assertFlowEquals(newKey3, flow3, succeeded.get(0));
// test pagination
PaginatedResult<Flow> page1 = service.getPaginatedFlowsForStatus(
TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, null);
List<Flow> pageValues = page1.getValues();
assertNotNull(pageValues);
assertNotNull(page1.getNextStartRow());
assertEquals(1, pageValues.size());
assertFlowEquals(newKey3, flow3, pageValues.get(0));
// page 2
PaginatedResult<Flow> page2 = service.getPaginatedFlowsForStatus(
TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, page1.getNextStartRow());
pageValues = page2.getValues();
assertNotNull(pageValues);
assertNotNull(page2.getNextStartRow());
assertEquals(1, pageValues.size());
assertFlowEquals(newKey2, flow2, pageValues.get(0));
// page 3
PaginatedResult<Flow> page3 = service.getPaginatedFlowsForStatus(
TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, page2.getNextStartRow());
pageValues = page3.getValues();
assertNotNull(pageValues);
assertNull(page3.getNextStartRow());
assertEquals(1, pageValues.size());
assertFlowEquals(newKey1, flow1, pageValues.get(0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.