output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别
int pc = folder.getFolderConstraint();
if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) {
try {
int ifc = Integer.parseInt(folderConstraint);
if (ifc > 0 && account == null) {
return UPLOADERROR;
}
if (ifc < pc) {
return UPLOADERROR;
}
} catch (Exception e) {
return UPLOADERROR;
}
} else {
folderConstraint = pc + "";
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
// 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
cifr.setResult("repeatFolder");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
|
#vulnerable code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
Folder testfolder = folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
// 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步
if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
// 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步
if (ConfigureReader.instance().accessFolder(testfolder, account)) {
cifr.setResult("coverOrBoth");
return gson.toJson(cifr);
}
}
// 如果上述条件不满足,则只能允许保留两者
cifr.setResult("onlyBoth");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response,
final MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String fileName = originalFileName;
final String repeType = request.getParameter("repeType");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
// 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。
boolean isUpload = false;
for (Cookie c : request.getCookies()) {
if (KIFTD_UPLOAD_KEY.equals(c.getName())) {
synchronized (keyMap) {
Integer i=keyMap.get(c.getValue());
if (i!=null) {// 比对钥匙有效性
isUpload = true;
i--;
if(i<=0) {
keyMap.remove(c.getValue());// 销毁这把钥匙
c.setMaxAge(0);
response.addCookie(c);
}
} else {
return UPLOADERROR;
}
}
}
}
if (!isUpload) {
return UPLOADERROR;
}
// 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。
final List<Node> files = this.fm.queryByParentFolderId(folderId);
if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) {
// 针对存在同名文件的操作
if (repeType != null) {
switch (repeType) {
// 跳过则忽略上传请求并直接返回上传成功(跳过不应上传)
case "skip":
return UPLOADSUCCESS;
// 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)
case "cover":
// 其中覆盖操作同时要求用户必须具备删除权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
return UPLOADERROR;
}
for (Node f : files) {
if (f.getFileName().equals(originalFileName)) {
File file2 = fbu.getFileFromBlocks(f);
try {
file.transferTo(file2);
f.setFileSize(fbu.getFileSize(file));
f.setFileCreationDate(ServerTimeUtil.accurateToDay());
if (account != null) {
f.setFileCreator(account);
} else {
f.setFileCreator("\u533f\u540d\u7528\u6237");
}
if (fm.update(f) > 0) {
this.lu.writeUploadFileEvent(request, f);
return UPLOADSUCCESS;
} else {
return UPLOADERROR;
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
return UPLOADERROR;
}
}
}
return UPLOADERROR;
// 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2
case "both":
// 设置新文件名为标号形式
fileName = FileNodeUtil.getNewNodeName(originalFileName, files);
break;
default:
// 其他声明,容错,暂无效果
return UPLOADERROR;
}
} else {
// 如果既有重复文件、同时又没声明如何操作,则直接上传失败。
return UPLOADERROR;
}
}
// 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。
final String path = this.fbu.saveToFileBlocks(file);
if (path.equals("ERROR")) {
return UPLOADERROR;
}
final String fsize = this.fbu.getFileSize(file);
final Node f2 = new Node();
f2.setFileId(UUID.randomUUID().toString());
if (account != null) {
f2.setFileCreator(account);
} else {
f2.setFileCreator("\u533f\u540d\u7528\u6237");
}
f2.setFileCreationDate(ServerTimeUtil.accurateToDay());
f2.setFileName(fileName);
f2.setFileParentFolder(folderId);
f2.setFilePath(path);
f2.setFileSize(fsize);
if (this.fm.insert(f2) > 0) {
this.lu.writeUploadFileEvent(request, f2);
return UPLOADSUCCESS;
}
return UPLOADERROR;
}
|
#vulnerable code
public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response,
final MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String fileName = originalFileName;
final String repeType = request.getParameter("repeType");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
// 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。
boolean isUpload = false;
for (Cookie c : request.getCookies()) {
if (KIFTD_UPLOAD_KEY.equals(c.getName())) {
synchronized (keyList) {
if (keyList.contains(c.getValue())) {// 比对钥匙有效性
isUpload = true;
keyList.remove(c.getValue());// 销毁这把钥匙
c.setMaxAge(0);
response.addCookie(c);
} else {
return UPLOADERROR;
}
}
}
}
if (!isUpload) {
return UPLOADERROR;
}
// 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。
final List<Node> files = this.fm.queryByParentFolderId(folderId);
if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) {
// 针对存在同名文件的操作
if (repeType != null) {
switch (repeType) {
// 跳过则忽略上传请求并直接返回上传成功(跳过不应上传)
case "skip":
return UPLOADSUCCESS;
// 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)
case "cover":
// 其中覆盖操作同时要求用户必须具备删除权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
return UPLOADERROR;
}
for (Node f : files) {
if (f.getFileName().equals(originalFileName)) {
File file2 = fbu.getFileFromBlocks(f);
try {
file.transferTo(file2);
f.setFileSize(fbu.getFileSize(file));
f.setFileCreationDate(ServerTimeUtil.accurateToDay());
if (account != null) {
f.setFileCreator(account);
} else {
f.setFileCreator("\u533f\u540d\u7528\u6237");
}
if (fm.update(f) > 0) {
this.lu.writeUploadFileEvent(request, f);
return UPLOADSUCCESS;
} else {
return UPLOADERROR;
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
return UPLOADERROR;
}
}
}
return UPLOADERROR;
// 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2
case "both":
// 设置新文件名为标号形式
fileName = FileNodeUtil.getNewNodeName(originalFileName, files);
break;
default:
// 其他声明,容错,暂无效果
return UPLOADERROR;
}
} else {
// 如果既有重复文件、同时又没声明如何操作,则直接上传失败。
return UPLOADERROR;
}
}
// 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。
final String path = this.fbu.saveToFileBlocks(file);
if (path.equals("ERROR")) {
return UPLOADERROR;
}
final String fsize = this.fbu.getFileSize(file);
final Node f2 = new Node();
f2.setFileId(UUID.randomUUID().toString());
if (account != null) {
f2.setFileCreator(account);
} else {
f2.setFileCreator("\u533f\u540d\u7528\u6237");
}
f2.setFileCreationDate(ServerTimeUtil.accurateToDay());
f2.setFileName(fileName);
f2.setFileParentFolder(folderId);
f2.setFilePath(path);
f2.setFileSize(fsize);
if (this.fm.insert(f2) > 0) {
this.lu.writeUploadFileEvent(request, f2);
return UPLOADSUCCESS;
}
return UPLOADERROR;
}
#location 44
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void createDefaultAccountPropertiesFile() {
Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")...");
final Properties dap = new Properties();
dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD);
dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH);
dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL);
try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) {
FileLock lock = accountSettingOut.getChannel().lock();
dap.store(accountSettingOut, "<This is the default kiftd account setting file. >");
lock.release();
Printer.instance.print("初始账户配置文件生成完毕。");
} catch (FileNotFoundException e) {
Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。");
} catch (IOException e2) {
Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。");
}
}
|
#vulnerable code
private void createDefaultAccountPropertiesFile() {
Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")...");
final Properties dap = new Properties();
dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD);
dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH);
dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL);
try {
dap.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE),
"<This is the default kiftd account setting file. >");
Printer.instance.print("初始账户配置文件生成完毕。");
} catch (FileNotFoundException e) {
Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。");
} catch (IOException e2) {
Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。");
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) {
final String fileId = request.getParameter("fileId");
if (fileId != null) {
final Node f = this.fm.queryById(fileId);
if (f != null) {
final String fileBlocks = ConfigureReader.instance().getFileBlockPath();
final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath());
downloadRangeFile(request, response, fo, f.getFileName());// 使用断点续传执行下载
this.lu.writeDownloadFileEvent(request, f);
}
}
}
}
|
#vulnerable code
public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) {
final String fileId = request.getParameter("fileId");
if (fileId != null) {
final Node f = this.fm.queryById(fileId);
if (f != null) {
final String fileBlocks = ConfigureReader.instance().getFileBlockPath();
final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath());
try {
final FileInputStream fis = new FileInputStream(fo);
response.setContentType("application/force-download");
response.setHeader("Content-Length", "" + fo.length());
response.addHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(f.getFileName(), "UTF-8"));
final int buffersize = ConfigureReader.instance().getBuffSize();
final byte[] buffer = new byte[buffersize];
final BufferedInputStream bis = new BufferedInputStream(fis);
final OutputStream os = (OutputStream) response.getOutputStream();
int index = 0;
while ((index = bis.read(buffer)) != -1) {
os.write(buffer, 0, index);
}
bis.close();
fis.close();
this.lu.writeDownloadFileEvent(request, f);
} catch (Exception ex) {
}
}
}
}
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public File getFileFromBlocks(Node f) {
// 检查该节点对应的文件块存放于哪个位置(主文件系统/扩展存储区)
try {
File file = null;
if (f.getFilePath().startsWith("file_")) {// 存放于主文件系统中
// 直接从主文件系统的文件块存放区获得对应的文件块
file = new File(ConfigureReader.instance().getFileBlockPath(), f.getFilePath());
} else {// 存放于扩展存储区
short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_')));
// 根据编号查到对应的扩展存储区路径,进而获取对应的文件块
file = new File(ConfigureReader.instance().getExtendStores().parallelStream()
.filter((e) -> e.getIndex() == index).findAny().get().getPath(), f.getFilePath());
}
if (file.isFile()) {
return file;
}
} catch (Exception e) {
lu.writeException(e);
Printer.instance.print("错误:文件数据读取失败。详细信息:" + e.getMessage());
}
return null;
}
|
#vulnerable code
public File getFileFromBlocks(Node f) {
// 检查该节点对应的文件块存放于哪个位置(主文件系统/扩展存储区)
try {
File file = null;
if (f.getFilePath().startsWith("file_")) {// 存放于主文件系统中
// 直接从主文件系统的文件块存放区获得对应的文件块
file = getBlockFromExtendPath(new File(ConfigureReader.instance().getFileBlockPath()), f.getFilePath());
} else {// 存放于扩展存储区
short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_')));
// 根据编号查到对应的扩展存储区路径,进而获取对应的文件块
file = getBlockFromExtendPath(ConfigureReader.instance().getExtendStores().parallelStream()
.filter((e) -> e.getIndex() == index).findAny().get().getPath(), f.getFilePath());
}
if (file.isFile()) {
return file;
}
} catch (Exception e) {
lu.writeException(e);
Printer.instance.print("错误:文件数据读取失败。详细信息:" + e.getMessage());
}
return null;
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean addAll(Collection<? extends T> collection) {
boolean success = true;
for (T element : collection) {
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
public boolean addAll(Collection<? extends T> collection) {
boolean success = true;
for (T element : collection) {
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
nest.hdel(entry.getKey());
}
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue()));
value.delete();
nest.hdel(entry.getKey());
}
nest.del();
refreshStorage(true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean addAll(Collection<? extends T> c) {
boolean success = true;
for (T element : c) {
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
public boolean addAll(Collection<? extends T> c) {
boolean success = true;
for (T element : c) {
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
nest.del();
refreshStorage(true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean add(T e) {
return internalAdd(e);
}
|
#vulnerable code
@Override
public boolean add(T e) {
return internalAdd(e, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int size() {
int repoSize = nest.llen();
return repoSize;
}
|
#vulnerable code
@Override
public int size() {
int repoSize = nest.llen();
if (repoSize != elements.size()) {
refreshStorage(true);
}
return repoSize;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean internalRemove(T element) {
boolean success = false;
if (element != null) {
success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.srem(JOhmUtils.getId(element).toString()) > 0;
unindexValue(element);
}
return success;
}
|
#vulnerable code
private boolean internalRemove(T element) {
boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.srem(JOhmUtils.getId(element).toString()) > 0;
unindexValue(element);
return success;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean internalAdd(T element) {
boolean success = false;
if (element != null) {
success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.sadd(JOhmUtils.getId(element).toString()) > 0;
indexValue(element);
}
return success;
}
|
#vulnerable code
private boolean internalAdd(T element) {
boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.sadd(JOhmUtils.getId(element).toString()) > 0;
indexValue(element);
return success;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean addAll(int index, Collection<? extends T> c) {
for (T element : c) {
internalIndexedAdd(index++, element);
}
return true;
}
|
#vulnerable code
@Override
public boolean addAll(int index, Collection<? extends T> c) {
for (T element : c) {
internalIndexedAdd(index++, element, false);
}
refreshStorage(true);
return true;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public T set(int index, T element) {
T previousElement = this.get(index);
internalIndexedAdd(index, element);
return previousElement;
}
|
#vulnerable code
@Override
public T set(int index, T element) {
T previousElement = this.get(index);
internalIndexedAdd(index, element, true);
return previousElement;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int size() {
int repoSize = nest.hlen();
return repoSize;
}
|
#vulnerable code
@Override
public int size() {
int repoSize = nest.hlen();
if (repoSize != backingMap.size()) {
refreshStorage(true);
}
return repoSize;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean internalRemove(T element) {
boolean success = false;
if (element != null) {
success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.srem(JOhmUtils.getId(element).toString()) > 0;
unindexValue(element);
}
return success;
}
|
#vulnerable code
private boolean internalRemove(T element) {
boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.srem(JOhmUtils.getId(element).toString()) > 0;
unindexValue(element);
return success;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
nest.hdel(entry.getKey());
}
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue()));
value.delete();
nest.hdel(entry.getKey());
}
nest.del();
refreshStorage(true);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@SuppressWarnings("unchecked")
public boolean removeAll(Collection<?> c) {
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element);
}
return success;
}
|
#vulnerable code
@Override
@SuppressWarnings("unchecked")
public boolean removeAll(Collection<?> c) {
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element, false);
}
refreshStorage(true);
return success;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public V remove(Object key) {
V value = get(key);
nest.hdel(key.toString());
return value;
}
|
#vulnerable code
@Override
public V remove(Object key) {
V value = get(key);
value.delete();
nest.hdel(key.toString());
return value;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public T remove(int index) {
return internalIndexedRemove(index);
}
|
#vulnerable code
@Override
public T remove(int index) {
return internalIndexedRemove(index, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldSetCollectionAutomatically() {
User user = new User();
assertNotNull(user.getLikes());
assertTrue(user.getLikes().getClass().equals(RedisList.class));
assertTrue(user.getPurchases().getClass().equals(RedisSet.class));
assertTrue(user.getFavoritePurchases().getClass()
.equals(RedisMap.class));
assertTrue(user.getOrderedPurchases().getClass().equals(
RedisSortedSet.class));
}
|
#vulnerable code
@Test
public void shouldSetCollectionAutomatically() {
User user = new User();
assertNotNull(user.getLikes());
assertTrue(user.getLikes().getClass().equals(RedisList.class));
assertTrue(user.getPurchases().getClass().equals(RedisSet.class));
assertTrue(user.getFavoritePurchases().getClass()
.equals(RedisMap.class));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean remove(Object o) {
return internalRemove(o);
}
|
#vulnerable code
@Override
public boolean remove(Object o) {
return internalRemove(o, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void internalIndexedAdd(int index, T element) {
if (element != null) {
nest.cat(JOhmUtils.getId(owner)).cat(field.getName()).lset(index,
JOhmUtils.getId(element).toString());
indexValue(element);
}
}
|
#vulnerable code
private void internalIndexedAdd(int index, T element) {
nest.cat(JOhmUtils.getId(owner)).cat(field.getName()).lset(index,
JOhmUtils.getId(element).toString());
indexValue(element);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public V remove(Object key) {
V value = get(key);
nest.hdel(key.toString());
return value;
}
|
#vulnerable code
@Override
public V remove(Object key) {
V value = get(key);
value.delete();
nest.hdel(key.toString());
return value;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean internalRemove(T element) {
boolean success = false;
if (element != null) {
Integer lrem = nest.cat(JOhmUtils.getId(owner))
.cat(field.getName()).lrem(1,
JOhmUtils.getId(element).toString());
unindexValue(element);
success = lrem > 0;
}
return success;
}
|
#vulnerable code
private boolean internalRemove(T element) {
Integer lrem = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.lrem(1, JOhmUtils.getId(element).toString());
unindexValue(element);
return lrem > 0;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
nest.del();
elements.clear();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean remove(Object o) {
return internalRemove(o);
}
|
#vulnerable code
@Override
public boolean remove(Object o) {
return internalRemove(o, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean add(T element) {
return internalAdd(element);
}
|
#vulnerable code
@Override
public boolean add(T element) {
return internalAdd(element, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void putAll(Map<? extends K, ? extends V> mapToCopyIn) {
for (Map.Entry<? extends K, ? extends V> entry : mapToCopyIn.entrySet()) {
internalPut(entry.getKey(), entry.getValue());
}
}
|
#vulnerable code
@Override
public void putAll(Map<? extends K, ? extends V> mapToCopyIn) {
for (Map.Entry<? extends K, ? extends V> entry : mapToCopyIn.entrySet()) {
internalPut(entry.getKey(), entry.getValue(), false);
}
refreshStorage(true);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
public boolean removeAll(Collection<?> c) {
boolean success = true;
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element);
}
return success;
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
public boolean removeAll(Collection<?> c) {
boolean success = true;
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element, false);
}
refreshStorage(true);
return success;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void checkModelSearch() {
User user1 = new User();
user1.setName("model1");
user1.setRoom("tworoom");
user1.setAge(88);
user1.setSalary(9999.99f);
user1.setInitial('m');
JOhm.save(user1);
Long id1 = user1.getId();
User user2 = new User();
user2.setName("zmodel2");
user2.setRoom("threeroom");
user2.setAge(8);
user2.setInitial('z');
user2 = JOhm.save(user2);
Long id2 = user2.getId();
assertNotNull(JOhm.get(User.class, id1));
assertNotNull(JOhm.get(User.class, id2));
List<User> users = JOhm.find(User.class, "age", 88);
assertEquals(1, users.size());
User user1Found = users.get(0);
assertEquals(user1Found.getAge(), user1.getAge());
assertEquals(user1Found.getName(), user1.getName());
assertNull(user1Found.getRoom());
assertEquals(user1Found.getSalary(), user1.getSalary(), 0D);
assertEquals(user1Found.getInitial(), user1.getInitial());
users = JOhm.find(User.class, "age", 8);
assertEquals(1, users.size());
User user2Found = users.get(0);
assertEquals(user2Found.getAge(), user2.getAge());
assertEquals(user2Found.getName(), user2.getName());
assertNull(user2Found.getRoom());
assertEquals(user2Found.getSalary(), user2.getSalary(), 0D);
assertEquals(user2Found.getInitial(), user2.getInitial());
users = JOhm.find(User.class, "name", "model1");
assertEquals(1, users.size());
User user3Found = users.get(0);
assertEquals(user3Found.getAge(), user1.getAge());
assertEquals(user3Found.getName(), user1.getName());
assertNull(user3Found.getRoom());
assertEquals(user3Found.getSalary(), user1.getSalary(), 0D);
assertEquals(user3Found.getInitial(), user1.getInitial());
users = JOhm.find(User.class, "name", "zmodel2");
assertEquals(1, users.size());
User user4Found = users.get(0);
assertEquals(user4Found.getAge(), user2.getAge());
assertEquals(user4Found.getName(), user2.getName());
assertNull(user4Found.getRoom());
assertEquals(user4Found.getSalary(), user2.getSalary(), 0D);
assertEquals(user4Found.getInitial(), user2.getInitial());
}
|
#vulnerable code
@Test
public void checkModelSearch() {
User user1 = new User();
user1.setName("model1");
user1.setRoom("tworoom");
user1.setAge(88);
user1.setSalary(9999.99f);
user1.setInitial('m');
JOhm.save(user1);
int id1 = user1.getId();
User user2 = new User();
user2.setName("zmodel2");
user2.setRoom("threeroom");
user2.setAge(8);
user2.setInitial('z');
user2 = JOhm.save(user2);
int id2 = user2.getId();
assertNotNull(JOhm.get(User.class, id1));
assertNotNull(JOhm.get(User.class, id2));
List<User> users = JOhm.find(User.class, "age", 88);
assertEquals(1, users.size());
User user1Found = users.get(0);
assertEquals(user1Found.getAge(), user1.getAge());
assertEquals(user1Found.getName(), user1.getName());
assertNull(user1Found.getRoom());
assertEquals(user1Found.getSalary(), user1.getSalary(), 0D);
assertEquals(user1Found.getInitial(), user1.getInitial());
users = JOhm.find(User.class, "age", 8);
assertEquals(1, users.size());
User user2Found = users.get(0);
assertEquals(user2Found.getAge(), user2.getAge());
assertEquals(user2Found.getName(), user2.getName());
assertNull(user2Found.getRoom());
assertEquals(user2Found.getSalary(), user2.getSalary(), 0D);
assertEquals(user2Found.getInitial(), user2.getInitial());
users = JOhm.find(User.class, "name", "model1");
assertEquals(1, users.size());
User user3Found = users.get(0);
assertEquals(user3Found.getAge(), user1.getAge());
assertEquals(user3Found.getName(), user1.getName());
assertNull(user3Found.getRoom());
assertEquals(user3Found.getSalary(), user1.getSalary(), 0D);
assertEquals(user3Found.getInitial(), user1.getInitial());
users = JOhm.find(User.class, "name", "zmodel2");
assertEquals(1, users.size());
User user4Found = users.get(0);
assertEquals(user4Found.getAge(), user2.getAge());
assertEquals(user4Found.getName(), user2.getName());
assertNull(user4Found.getRoom());
assertEquals(user4Found.getSalary(), user2.getSalary(), 0D);
assertEquals(user4Found.getInitial(), user2.getInitial());
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int size() {
int repoSize = nest.smembers().size();
return repoSize;
}
|
#vulnerable code
@Override
public int size() {
int repoSize = nest.smembers().size();
if (repoSize != elements.size()) {
refreshStorage(true);
}
return repoSize;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void add(int index, T element) {
internalIndexedAdd(index, element);
}
|
#vulnerable code
@Override
public void add(int index, T element) {
internalIndexedAdd(index, element, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean internalAdd(T element) {
boolean success = false;
if (element != null) {
success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.rpush(JOhmUtils.getId(element).toString()) > 0;
indexValue(element);
}
return success;
}
|
#vulnerable code
private boolean internalAdd(T element) {
boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName())
.rpush(JOhmUtils.getId(element).toString()) > 0;
indexValue(element);
return success;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void cannotSearchAfterDeletingIndexes() {
User user = new User();
user.setAge(88);
JOhm.save(user);
user.setAge(77); // younger
JOhm.save(user);
user.setAge(66); // younger still
JOhm.save(user);
Long id = user.getId();
assertNotNull(JOhm.get(User.class, id));
List<User> users = JOhm.find(User.class, "age", 88);
assertEquals(0, users.size()); // index already updated
users = JOhm.find(User.class, "age", 77);
assertEquals(0, users.size()); // index already updated
users = JOhm.find(User.class, "age", 66);
assertEquals(1, users.size());
JOhm.delete(User.class, id);
users = JOhm.find(User.class, "age", 88);
assertEquals(0, users.size());
users = JOhm.find(User.class, "age", 77);
assertEquals(0, users.size());
users = JOhm.find(User.class, "age", 66);
assertEquals(0, users.size());
assertNull(JOhm.get(User.class, id));
}
|
#vulnerable code
@Test
public void cannotSearchAfterDeletingIndexes() {
User user = new User();
user.setAge(88);
JOhm.save(user);
user.setAge(77); // younger
JOhm.save(user);
user.setAge(66); // younger still
JOhm.save(user);
int id = user.getId();
assertNotNull(JOhm.get(User.class, id));
List<User> users = JOhm.find(User.class, "age", 88);
assertEquals(0, users.size()); // index already updated
users = JOhm.find(User.class, "age", 77);
assertEquals(0, users.size()); // index already updated
users = JOhm.find(User.class, "age", 66);
assertEquals(1, users.size());
JOhm.delete(User.class, id);
users = JOhm.find(User.class, "age", 88);
assertEquals(0, users.size());
users = JOhm.find(User.class, "age", 77);
assertEquals(0, users.size());
users = JOhm.find(User.class, "age", 66);
assertEquals(0, users.size());
assertNull(JOhm.get(User.class, id));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean hasNext()
{
if(currentIteratorHasNext())
{
return true;
}
loadNextChunkIterator();
return currentIteratorHasNext();
}
|
#vulnerable code
@Override
public boolean hasNext()
{
return currentIteratorHasNext() || possibleChunksRemaining();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public FetchResponse fetch(RequestMeta meta) {
if (riak == null)
throw new IllegalStateException("Cannot fetch an object without a RiakClient");
FetchResponse r = riak.fetch(bucket, key, meta);
if (r.getObject() != null) {
RiakObject other = r.getObject();
shallowCopy(other);
r.setObject(this);
}
return r;
}
|
#vulnerable code
public FetchResponse fetch(RequestMeta meta) {
if (riak == null)
throw new IllegalStateException("Cannot fetch an object without a RiakClient");
FetchResponse r = riak.fetch(bucket, key, meta);
if (r.isSuccess()) {
this.copyData(r.getObject());
}
return r;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
RiakConnection getConnection() throws IOException {
return getConnection(true);
}
|
#vulnerable code
RiakConnection getConnection() throws IOException {
RiakConnection c = connections.get();
if (c == null || !c.endIdleAndCheckValid()) {
c = new RiakConnection(addr, port);
if (this.clientID != null) {
setClientID(clientID);
}
} else {
// we're fine! //
}
connections.set(null);
return c;
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public RawFetchResponse fetch(String bucket, String key) {
return doFetch(bucket, key, null, false);
}
|
#vulnerable code
public RawFetchResponse fetch(String bucket, String key) {
return fetch(bucket, key, null);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
void receive_code(int code) throws IOException, RiakError {
int len = din.readInt();
int get_code = din.read();
if (code == RiakClient.MSG_ErrorResp) {
RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din);
throw new RiakError(err);
}
if (len != 1 || code != get_code) {
throw new IOException("bad message code");
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean findNext() throws IOException {
if (currentPartStream != null) {
InputStream is = currentPartStream.branch();
try {
while (is.read() != -1) { /* nop */} // advance stream to end of next boundary
finishReadingLine(stream); // and consume the rest of the boundary line including the newline
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (stream.peek() != -1) {
currentPartStream = new BranchableInputStream(new OneTokenInputStream(stream.branch(), boundary));
return true;
}
return false;
}
|
#vulnerable code
private boolean findNext() throws IOException {
if (currentPartStream != null && !currentPartStream.done()) {
InputStream is = new OneTokenInputStream(stream, boundary);
try {
while (is.read() != -1) { /* nop */}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (stream.peek() != -1) {
currentPartStream = new OneTokenInputStream(stream.branch(), boundary);
return true;
}
return false;
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
byte[] receive(int code) throws IOException {
int len = din.readInt();
int get_code = din.read();
byte[] data = null;
if (len > 1) {
data = new byte[len - 1];
din.readFully(data);
}
if (get_code == RiakClient.MSG_ErrorResp) {
RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data);
throw new RiakError(err);
}
if (code != get_code) {
throw new IOException("bad message code. Expected: " + code + " actual: " + get_code);
}
return data;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WriteBucket enableForSearch() {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH);
addPrecommitHook(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK);
builder.search(true);
return this;
}
|
#vulnerable code
public WriteBucket enableForSearch() {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH);
builder.addPrecommitHook(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK).search(true);
return this;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
void close() {
if (isClosed())
return;
try {
sock.close();
din = null;
dout = null;
sock = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody()
throws ExecutionException, InterruptedException, UnknownHostException
{
final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true, false);
assertEquals(NUMBER_OF_TEST_VALUES, results.size());
verifyResults(results, true);
}
|
#vulnerable code
@Test
public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody()
throws ExecutionException, InterruptedException, UnknownHostException
{
final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true);
assertEquals(NUMBER_OF_TEST_VALUES, results.size());
for (int i=0; i<NUMBER_OF_TEST_VALUES; ++i)
{
final String key = "k"+i;
assertTrue(results.containsKey(key));
final RiakObject ro = results.get(key);
assertNotNull(ro);
assertEquals("plain/text", ro.getContentType());
assertFalse(ro.isDeleted());
assertEquals("v"+i, ro.getValue().toStringUtf8());
}
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void testListBucketsStreaming(Namespace namespace) throws InterruptedException, ExecutionException
{
ListBuckets listBucketsCommand = new ListBuckets.Builder(namespace.getBucketType()).build();
final RiakFuture<ListBuckets.StreamingResponse, BinaryValue> streamingFuture =
client.executeAsyncStreaming(listBucketsCommand, 500);
final ListBuckets.StreamingResponse streamResponse = streamingFuture.get();
final Iterator<Namespace> iterator = streamResponse.iterator();
assumeTrue(iterator.hasNext());
boolean found = false;
for (Namespace ns : streamResponse)
{
if(!found)
{
found = ns.getBucketName().toString().equals(bucketName);
}
}
streamingFuture.await(); // Wait for command to finish, even if we've found our data
assumeTrue(streamingFuture.isDone());
assertFalse(iterator.hasNext());
assertEquals(namespace.getBucketType(), streamingFuture.getQueryInfo());
assertTrue(found);
}
|
#vulnerable code
private void testListBucketsStreaming(Namespace namespace) throws InterruptedException, ExecutionException
{
ListBuckets listBucketsCommand = new ListBuckets.Builder(namespace.getBucketType()).build();
final RiakFuture<ListBuckets.StreamingResponse, BinaryValue> streamingFuture =
client.executeAsyncStreaming(listBucketsCommand, 500);
Iterator<Namespace> iterator = streamingFuture.get().iterator();
assumeTrue(iterator.hasNext());
boolean found = false;
while (iterator.hasNext())
{
final Namespace next = iterator.next();
found = next.getBucketName().toString().equals(bucketName);
}
streamingFuture.await(); // Wait for command to finish, even if we've found our data
assumeTrue(streamingFuture.isDone());
assertFalse(streamingFuture.get().iterator().hasNext());
assertEquals(namespace.getBucketType(), streamingFuture.getQueryInfo());
assertTrue(found);
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Bucket execute() throws RiakRetryFailedException {
final BucketProperties propsToStore = builder.precommitHooks(precommitHooks).postcommitHooks(postcommitHooks).build();
retrier.attempt(new Callable<Void>() {
public Void call() throws Exception {
client.updateBucket(name, propsToStore);
return null;
}
});
BucketProperties properties = retrier.attempt(new Callable<BucketProperties>() {
public BucketProperties call() throws Exception {
return client.fetchBucket(name);
}
});
return new DefaultBucket(name, properties, client, retrier);
}
|
#vulnerable code
public Bucket execute() throws RiakRetryFailedException {
final BucketProperties propsToStore = builder.build();
retrier.attempt(new Callable<Void>() {
public Void call() throws Exception {
client.updateBucket(name, propsToStore);
return null;
}
});
BucketProperties properties = retrier.attempt(new Callable<BucketProperties>() {
public BucketProperties call() throws Exception {
return client.fetchBucket(name);
}
});
return new DefaultBucket(name, properties, client, retrier);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void setClientID(ByteString id) throws IOException {
if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) {
id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH);
}
this.clientId = id.toByteArray();
}
|
#vulnerable code
public void setClientID(ByteString id) throws IOException {
if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) {
id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH);
}
RpbSetClientIdReq req = RPB.RpbSetClientIdReq.newBuilder().setClientId(
id).build();
RiakConnection c = getConnection(false);
try {
c.send(MSG_SetClientIdReq, req);
c.receive_code(MSG_SetClientIdResp);
} finally {
release(c);
}
this.clientID = id;
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected SecondaryIndexQueryOperation.Response convert(List<Object> rawResponse)
{
SecondaryIndexQueryOperation.Response.Builder responseBuilder =
new SecondaryIndexQueryOperation.Response.Builder();
final boolean isIndexBodyResp = rawResponse != null &&
!rawResponse.isEmpty() &&
objectIsIndexBodyResp(rawResponse.get(0));
for (Object o : rawResponse)
{
convertSingleResponse(responseBuilder, isIndexBodyResp, o);
}
return responseBuilder.build();
}
|
#vulnerable code
@Override
protected SecondaryIndexQueryOperation.Response convert(List<Object> rawResponse)
{
SecondaryIndexQueryOperation.Response.Builder responseBuilder =
new SecondaryIndexQueryOperation.Response.Builder();
for (Object o : rawResponse)
{
if (o instanceof RiakKvPB.RpbIndexBodyResp)
{
assert pbReq.getReturnBody();
final RiakKvPB.RpbIndexBodyResp bodyResp = (RiakKvPB.RpbIndexBodyResp)o;
convertBodies(responseBuilder, bodyResp);
if (bodyResp.hasContinuation())
{
responseBuilder.withContinuation(
BinaryValue.unsafeCreate(bodyResp.getContinuation().toByteArray()));
}
continue;
}
final RiakKvPB.RpbIndexResp pbEntry = (RiakKvPB.RpbIndexResp) o;
/**
* The 2i API is inconsistent on the Riak side. If it's not
* a range query, return_terms is ignored it only returns the
* list of object keys and you have to have
* preserved the index key if you want to return it to the user
* with the results.
*
* Also, the $key index queries just ignore return_terms altogether.
*/
if (pbReq.getReturnTerms() && !query.indexName.toString().equalsIgnoreCase(IndexNames.KEY))
{
convertTerms(responseBuilder, pbEntry);
}
else
{
convertKeys(responseBuilder, pbEntry);
}
if (pbEntry.hasContinuation())
{
responseBuilder.withContinuation(
BinaryValue.unsafeCreate(pbEntry.getContinuation().toByteArray()));
}
}
return responseBuilder.build();
}
#location 35
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
void close() {
if (isClosed())
return;
try {
sock.close();
din = null;
dout = null;
sock = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WriteBucket addPrecommitHook(NamedFunction preCommitHook) {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT);
if(preCommitHook != null) {
if(precommitHooks == null) {
precommitHooks = new ArrayList<NamedFunction>();
}
precommitHooks.add(preCommitHook);
}
return this;
}
|
#vulnerable code
public WriteBucket addPrecommitHook(NamedFunction preCommitHook) {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT);
builder.addPrecommitHook(preCommitHook);
return this;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
void send(int code) throws IOException {
dout.writeInt(1);
dout.write(code);
dout.flush();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
RiakConnection getConnection() throws IOException {
RiakConnection c = pool.getConnection(clientId);
return c;
}
|
#vulnerable code
RiakConnection getConnection(boolean setClientId) throws IOException {
RiakConnection c = connections.get();
if (c == null || !c.endIdleAndCheckValid()) {
c = new RiakConnection(addr, port, bufferSizeKb);
if (this.clientID != null && setClientId) {
connections.set(c);
setClientID(clientID);
}
}
connections.set(null);
return c;
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void warmUp() throws IOException {
for (int i = 0; i < this.initialSize; i++) {
RiakConnection c = getConnection();
c.beginIdle();
available.add(c);
}
}
|
#vulnerable code
private void warmUp() throws IOException {
if (permits.tryAcquire(initialSize)) {
for (int i = 0; i < this.initialSize; i++) {
RiakConnection c =
new RiakConnection(this.host, this.port,
this.bufferSizeKb, this,
TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS),
requestTimeoutMillis);
c.beginIdle();
available.add(c);
}
} else {
throw new RuntimeException("Unable to create initial connections");
}
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void send(int code, MessageLite req) throws IOException {
int len = req.getSerializedSize();
dout.writeInt(len + 1);
dout.write(code);
req.writeTo(dout);
dout.flush();
}
|
#vulnerable code
void close() {
if (isClosed())
return;
try {
sock.close();
din = null;
dout = null;
sock = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getClientID() throws IOException {
RiakConnection c = getConnection();
try {
c.send(MSG_GetClientIdReq);
byte[] data = c.receive(MSG_GetClientIdResp);
if (data == null)
return null;
RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data);
clientId = res.getClientId().toByteArray();
return CharsetUtils.asUTF8String(clientId);
} finally {
release(c);
}
}
|
#vulnerable code
public String getClientID() throws IOException {
RiakConnection c = getConnection();
try {
c.send(MSG_GetClientIdReq);
byte[] data = c.receive(MSG_GetClientIdResp);
if (data == null)
return null;
RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data);
clientID = res.getClientId();
return clientID.toStringUtf8();
} finally {
release(c);
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WriteBucket disableSearch() {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH);
if (precommitHooks != null) {
precommitHooks.remove(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK);
}
builder.search(false);
return this;
}
|
#vulnerable code
public WriteBucket disableSearch() {
httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH);
if (existingPrecommitHooks != null) {
synchronized (existingPrecommitHooks) {
existingPrecommitHooks.remove(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK);
for (NamedFunction f : existingPrecommitHooks) {
builder.addPrecommitHook(f);
}
}
}
builder.search(false);
return this;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testInterruptedExceptionDealtWith() throws InterruptedException
{
final Throwable[] ex = {null};
int timeout = 1000;
Thread testThread = new Thread(() ->
{
try
{
@SuppressWarnings("unchecked")
TransferQueue<FakeResponse> fakeQueue =
(TransferQueue<FakeResponse>) mock(TransferQueue.class);
when(fakeQueue.poll(timeout, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException("foo"));
@SuppressWarnings("unchecked")
PBStreamingFutureOperation<FakeResponse, Void, Void> coreFuture =
(PBStreamingFutureOperation<FakeResponse, Void, Void>) mock(PBStreamingFutureOperation.class);
when(coreFuture.getResultsQueue()).thenReturn(fakeQueue);
// ChunkedResponseIterator polls the response queue when created,
// so we'll use that to simulate a Thread interrupt.
new ChunkedResponseIterator<>(coreFuture,
timeout,
Long::new,
FakeResponse::iterator);
}
catch (RuntimeException rex)
{
ex[0] = rex;
}
catch (InterruptedException e)
{
// Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with
// If we actually catch one here we've failed at our jobs.
fail(e.getMessage());
}
assertTrue(Thread.currentThread().isInterrupted());
});
testThread.start();
testThread.join();
Throwable caughtException = ex[0];
assertNotNull(caughtException);
Throwable wrappedException = caughtException.getCause();
assertNotNull(caughtException.getMessage(), wrappedException);
assertEquals("foo", wrappedException.getMessage());
assertTrue(wrappedException instanceof InterruptedException);
}
|
#vulnerable code
@Test
public void testInterruptedExceptionDealtWith() throws InterruptedException
{
final boolean[] caught = {false};
final InterruptedException[] ie = {null};
int timeout = 1000;
Thread t = new Thread(() ->
{
try
{
@SuppressWarnings("unchecked") TransferQueue<FakeResponse> fakeQueue =
(TransferQueue<FakeResponse>) mock(TransferQueue.class);
when(fakeQueue.poll(timeout,
TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException(
"foo"));
@SuppressWarnings("unchecked") PBStreamingFutureOperation<FakeResponse, Void, Void>
coreFuture = (PBStreamingFutureOperation<FakeResponse, Void, Void>) mock(
PBStreamingFutureOperation.class);
when(coreFuture.getResultsQueue()).thenReturn(fakeQueue);
// ChunkedResponseIterator polls the response queue when created,
// so we'll use that to simulate a Thread interrupt.
new ChunkedResponseIterator<>(coreFuture,
timeout,
Long::new,
FakeResponse::iterator);
}
catch (RuntimeException ex)
{
caught[0] = true;
ie[0] = (InterruptedException) ex.getCause();
}
catch (InterruptedException e)
{
// Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with
// If we actually catch one here we've failed at our jobs.
caught[0] = false;
}
assertTrue(Thread.currentThread().isInterrupted());
});
t.start();
t.join();
assertTrue(caught[0]);
assertEquals("foo", ie[0].getMessage());
}
#location 50
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
if (destination.exists() && destination.isDirectory()) {
FileUtils.delete(destination.toPath());
}
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream fos = new FileOutputStream(file)) {
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
}
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
}
}
|
#vulnerable code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
removeDirectory(destination);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length = 0;
FileOutputStream fos = new FileOutputStream(file);
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
zipInputStream.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Map<String, Set<String>> readIndexFiles() {
// checking cache
if (entries != null) {
return entries;
}
entries = new HashMap<String, Set<String>>();
List<PluginWrapper> plugins = pluginManager.getPlugins();
for (PluginWrapper plugin : plugins) {
String pluginId = plugin.getDescriptor().getPluginId();
log.debug("Reading extensions index file for plugin '{}'", pluginId);
Set<String> entriesPerPlugin = new HashSet<String>();
try {
URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE);
log.debug("Read '{}'", url.getFile());
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
ExtensionsIndexer.readIndex(reader, entriesPerPlugin);
if (entriesPerPlugin.isEmpty()) {
log.debug("No extensions found");
} else {
log.debug("Found possible {} extensions:", entriesPerPlugin.size());
for (String entry : entriesPerPlugin) {
log.debug(" " + entry);
}
}
entries.put(pluginId, entriesPerPlugin);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return entries;
}
|
#vulnerable code
private Map<String, Set<String>> readIndexFiles() {
// checking cache
if (entries != null) {
return entries;
}
entries = new HashMap<String, Set<String>>();
List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins();
for (PluginWrapper plugin : startedPlugins) {
String pluginId = plugin.getDescriptor().getPluginId();
log.debug("Reading extensions index file for plugin '{}'", pluginId);
Set<String> entriesPerPlugin = new HashSet<String>();
try {
URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE);
log.debug("Read '{}'", url.getFile());
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
ExtensionsIndexer.readIndex(reader, entriesPerPlugin);
if (entriesPerPlugin.isEmpty()) {
log.debug("No extensions found");
} else {
log.debug("Found possible {} extensions:", entriesPerPlugin.size());
for (String entry : entriesPerPlugin) {
log.debug(" " + entry);
}
}
entries.put(pluginId, entriesPerPlugin);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return entries;
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void createDisabledFile() throws IOException {
List<String> plugins = new ArrayList<>();
plugins.add("plugin-2");
writeLines(plugins, "disabled.txt");
}
|
#vulnerable code
private void createDisabledFile() throws IOException {
File file = testFolder.newFile("disabled.txt");
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write("plugin-2\r\n");
}
file.createNewFile();
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void resolveDependencies() throws PluginException {
DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins);
resolvedPlugins = dependencyResolver.getSortedPlugins();
for (PluginWrapper pluginWrapper : resolvedPlugins) {
unresolvedPlugins.remove(pluginWrapper);
uberClassLoader.addLoader(pluginWrapper.getPluginClassLoader());
LOG.info("Plugin '" + pluginWrapper.getDescriptor().getPluginId() + "' resolved");
}
}
|
#vulnerable code
private void resolveDependencies() {
DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins);
resolvedPlugins = dependencyResolver.getSortedDependencies();
for (Plugin plugin : resolvedPlugins) {
unresolvedPlugins.remove(plugin);
uberClassLoader.addLoader(plugin.getWrapper().getPluginClassLoader());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
if (destination.exists() && destination.isDirectory()) {
FileUtils.delete(destination.toPath());
}
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream fos = new FileOutputStream(file)) {
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
}
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
}
}
|
#vulnerable code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
removeDirectory(destination);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length = 0;
FileOutputStream fos = new FileOutputStream(file);
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
zipInputStream.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Map<String, Set<String>> readIndexFiles() {
// checking cache
if (entries != null) {
return entries;
}
entries = new LinkedHashMap<String, Set<String>>();
readClasspathIndexFiles();
readPluginsIndexFiles();
return entries;
}
|
#vulnerable code
private Map<String, Set<String>> readIndexFiles() {
// checking cache
if (entries != null) {
return entries;
}
entries = new HashMap<String, Set<String>>();
List<PluginWrapper> plugins = pluginManager.getPlugins();
for (PluginWrapper plugin : plugins) {
String pluginId = plugin.getDescriptor().getPluginId();
log.debug("Reading extensions index file for plugin '{}'", pluginId);
Set<String> entriesPerPlugin = new HashSet<String>();
try {
URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE);
log.debug("Read '{}'", url.getFile());
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
ExtensionsIndexer.readIndex(reader, entriesPerPlugin);
if (entriesPerPlugin.isEmpty()) {
log.debug("No extensions found");
} else {
log.debug("Found possible {} extensions:", entriesPerPlugin.size());
for (String entry : entriesPerPlugin) {
log.debug(" " + entry);
}
}
entries.put(pluginId, entriesPerPlugin);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return entries;
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
if (destination.exists() && destination.isDirectory()) {
FileUtils.delete(destination.toPath());
}
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream fos = new FileOutputStream(file)) {
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
}
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
}
}
|
#vulnerable code
public void extract() throws IOException {
log.debug("Extract content of '{}' to '{}'", source, destination);
// delete destination file if exists
removeDirectory(destination);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
try {
File file = new File(destination, zipEntry.getName());
// create intermediary directories - sometimes zip don't add them
File dir = new File(file.getParent());
dir.mkdirs();
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte[] buffer = new byte[1024];
int length = 0;
FileOutputStream fos = new FileOutputStream(file);
while ((length = zipInputStream.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
} catch (FileNotFoundException e) {
log.error("File '{}' not found", zipEntry.getName());
}
}
zipInputStream.close();
}
#location 31
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Manifest readManifest(Path pluginPath) throws PluginException {
if (FileUtils.isJarFile(pluginPath)) {
try(JarFile jar = new JarFile(pluginPath.toFile())) {
Manifest manifest = jar.getManifest();
if (manifest != null) {
return manifest;
}
} catch (IOException e) {
throw new PluginException(e);
}
}
Path manifestPath = getManifestPath(pluginPath);
if (manifestPath == null) {
throw new PluginException("Cannot find the manifest path");
}
log.debug("Lookup plugin descriptor in '{}'", manifestPath);
if (Files.notExists(manifestPath)) {
throw new PluginException("Cannot find '{}' path", manifestPath);
}
try (InputStream input = Files.newInputStream(manifestPath)) {
return new Manifest(input);
} catch (IOException e) {
throw new PluginException(e);
}
}
|
#vulnerable code
protected Manifest readManifest(Path pluginPath) throws PluginException {
if (FileUtils.isJarFile(pluginPath)) {
try {
Manifest manifest = new JarFile(pluginPath.toFile()).getManifest();
if (manifest != null) {
return manifest;
}
} catch (IOException e) {
throw new PluginException(e);
}
}
Path manifestPath = getManifestPath(pluginPath);
if (manifestPath == null) {
throw new PluginException("Cannot find the manifest path");
}
log.debug("Lookup plugin descriptor in '{}'", manifestPath);
if (Files.notExists(manifestPath)) {
throw new PluginException("Cannot find '{}' path", manifestPath);
}
try (InputStream input = Files.newInputStream(manifestPath)) {
return new Manifest(input);
} catch (IOException e) {
throw new PluginException(e);
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) {
// check if @Extension is put on class and not on method or constructor
if (!(element instanceof TypeElement)) {
continue;
}
// check if class extends/implements an extension point
if (!isExtension(element.asType())) {
continue;
}
TypeElement extensionElement = (TypeElement) element;
// Extension annotation = element.getAnnotation(Extension.class);
List<TypeElement> extensionPointElements = findExtensionPoints(extensionElement);
if (extensionPointElements.isEmpty()) {
// TODO throw error ?
continue;
}
String extension = getBinaryName(extensionElement);
for (TypeElement extensionPointElement : extensionPointElements) {
String extensionPoint = getBinaryName(extensionPointElement);
Set<String> extensionPoints = extensions.get(extensionPoint);
if (extensionPoints == null) {
extensionPoints = new TreeSet<>();
extensions.put(extensionPoint, extensionPoints);
}
extensionPoints.add(extension);
}
}
/*
if (!roundEnv.processingOver()) {
return false;
}
*/
// read old extensions
oldExtensions = storage.read();
for (Map.Entry<String, Set<String>> entry : oldExtensions.entrySet()) {
String extensionPoint = entry.getKey();
if (extensions.containsKey(extensionPoint)) {
extensions.get(extensionPoint).addAll(entry.getValue());
} else {
extensions.put(extensionPoint, entry.getValue());
}
}
// write extensions
storage.write(extensions);
return false;
// return true; // no further processing of this annotation type
}
|
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) {
// check if @Extension is put on class and not on method or constructor
if (!(element instanceof TypeElement)) {
continue;
}
// check if class extends/implements an extension point
if (!isExtension(element.asType())) {
continue;
}
TypeElement extensionElement = (TypeElement) element;
// Extension annotation = element.getAnnotation(Extension.class);
List<TypeElement> extensionPointElements = findExtensionPoints(extensionElement);
if (extensionPointElements.isEmpty()) {
// TODO throw error ?
continue;
}
String extension = getBinaryName(extensionElement);
for (TypeElement extensionPointElement : extensionPointElements) {
String extensionPoint = getBinaryName(extensionPointElement);
Set<String> extensionPoints = extensions.get(extensionPoint);
if (extensionPoints == null) {
extensionPoints = new TreeSet<>();
extensions.put(extensionPoint, extensionPoints);
}
extensionPoints.add(extension);
}
}
/*
if (!roundEnv.processingOver()) {
return false;
}
*/
// read old extensions
oldExtensions = storage.read();
for (Map.Entry<String, Set<String>> entry : oldExtensions.entrySet()) {
String extensionPoint = entry.getKey();
if (extensions.containsKey(extensionPoint)) {
extensions.get(extensionPoint).addAll(entry.getValue());
} else {
extensions.put(extensionPoint, entry.getValue());
}
}
// write extensions
storage.write(extensions);
return false;
// return true; // no further processing of this annotation type
}
#location 56
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Map<String, Set<String>> readPluginsStorages() {
log.debug("Reading extensions storages from plugins");
Map<String, Set<String>> result = new LinkedHashMap<>();
List<PluginWrapper> plugins = pluginManager.getPlugins();
for (PluginWrapper plugin : plugins) {
String pluginId = plugin.getDescriptor().getPluginId();
log.debug("Reading extensions storage from plugin '{}'", pluginId);
Set<String> bucket = new HashSet<>();
try {
URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource());
if (url != null) {
log.debug("Read '{}'", url.getFile());
try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
LegacyExtensionStorage.read(reader, bucket);
}
} else {
log.debug("Cannot find '{}'", getExtensionsResource());
}
debugExtensions(bucket);
result.put(pluginId, bucket);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return result;
}
|
#vulnerable code
@Override
public Map<String, Set<String>> readPluginsStorages() {
log.debug("Reading extensions storages from plugins");
Map<String, Set<String>> result = new LinkedHashMap<>();
List<PluginWrapper> plugins = pluginManager.getPlugins();
for (PluginWrapper plugin : plugins) {
String pluginId = plugin.getDescriptor().getPluginId();
log.debug("Reading extensions storage from plugin '{}'", pluginId);
Set<String> bucket = new HashSet<>();
try {
URL url = ((PluginClassLoader) plugin.getPluginClassLoader()).findResource(getExtensionsResource());
if (url != null) {
log.debug("Read '{}'", url.getFile());
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
LegacyExtensionStorage.read(reader, bucket);
} else {
log.debug("Cannot find '{}'", getExtensionsResource());
}
debugExtensions(bucket);
result.put(pluginId, bucket);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
return result;
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Map<String, Set<String>> readClasspathStorages() {
log.debug("Reading extensions storages from classpath");
Map<String, Set<String>> result = new LinkedHashMap<>();
Set<String> bucket = new HashSet<>();
try {
Enumeration<URL> urls = getClass().getClassLoader().getResources(getExtensionsResource());
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
log.debug("Read '{}'", url.getFile());
try (Reader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
LegacyExtensionStorage.read(reader, bucket);
}
}
debugExtensions(bucket);
result.put(null, bucket);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return result;
}
|
#vulnerable code
@Override
public Map<String, Set<String>> readClasspathStorages() {
log.debug("Reading extensions storages from classpath");
Map<String, Set<String>> result = new LinkedHashMap<>();
Set<String> bucket = new HashSet<>();
try {
Enumeration<URL> urls = getClass().getClassLoader().getResources(getExtensionsResource());
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
log.debug("Read '{}'", url.getFile());
Reader reader = new InputStreamReader(url.openStream(), "UTF-8");
LegacyExtensionStorage.read(reader, bucket);
}
debugExtensions(bucket);
result.put(null, bucket);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return result;
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String loadPlugin(File pluginArchiveFile) {
if (pluginArchiveFile == null || !pluginArchiveFile.exists()) {
throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginArchiveFile));
}
File pluginDirectory = null;
try {
pluginDirectory = expandPluginArchive(pluginArchiveFile);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
if (pluginDirectory == null || !pluginDirectory.exists()) {
throw new IllegalArgumentException(String.format("Failed to expand %s", pluginArchiveFile));
}
try {
PluginWrapper pluginWrapper = loadPluginDirectory(pluginDirectory);
// TODO uninstalled plugin dependencies?
unresolvedPlugins.remove(pluginWrapper);
resolvedPlugins.add(pluginWrapper);
extensionFinder.reset();
return pluginWrapper.getDescriptor().getPluginId();
} catch (PluginException e) {
log.error(e.getMessage(), e);
}
return null;
}
|
#vulnerable code
@Override
public String loadPlugin(File pluginArchiveFile) {
if (pluginArchiveFile == null || !pluginArchiveFile.exists()) {
throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginArchiveFile));
}
File pluginDirectory = null;
try {
pluginDirectory = expandPluginArchive(pluginArchiveFile);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
if (pluginDirectory == null || !pluginDirectory.exists()) {
throw new IllegalArgumentException(String.format("Failed to expand %s", pluginArchiveFile));
}
try {
PluginWrapper pluginWrapper = loadPluginDirectory(pluginDirectory);
// TODO uninstalled plugin dependencies?
unresolvedPlugins.remove(pluginWrapper);
resolvedPlugins.add(pluginWrapper);
compoundClassLoader.addLoader(pluginWrapper.getPluginClassLoader());
extensionFinder.reset();
return pluginWrapper.getDescriptor().getPluginId();
} catch (PluginException e) {
log.error(e.getMessage(), e);
}
return null;
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getTitle() {
return title;
}
|
#vulnerable code
public String getTitle() throws IOException, ParseException {
if (title != null) {
return title;
}
if (url == null)
throw new IOException("URL needs to be present");
return info(url).get("title").toString();
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isMod() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("is_mod").toString());
}
|
#vulnerable code
public boolean isMod() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("is_mod").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public double created() throws IOException, ParseException {
return Double.parseDouble(getUserInformation().get("created").toString());
}
|
#vulnerable code
public double created() throws IOException, ParseException {
return Double.parseDouble(info().get("created").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public double createdUTC() throws IOException, ParseException {
return Double.parseDouble(getUserInformation().get("created_utc").toString());
}
|
#vulnerable code
public double createdUTC() throws IOException, ParseException {
return Double.parseDouble(info().get("created_utc").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean hasMail() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("has_mail").toString());
}
|
#vulnerable code
public boolean hasMail() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("has_mail").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public double created() throws IOException, ParseException {
return Double.parseDouble(getUserInformation().get("created").toString());
}
|
#vulnerable code
public double created() throws IOException, ParseException {
return Double.parseDouble(info().get("created").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isGold() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("is_gold").toString());
}
|
#vulnerable code
public boolean isGold() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("is_gold").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String id() throws IOException, ParseException {
return getUserInformation().get("id").toString();
}
|
#vulnerable code
public String id() throws IOException, ParseException {
return info().get("id").toString();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void parseRecursive(List<Comment> comments, JSONObject object) throws RetrievalFailedException, RedditError {
assert comments != null : "List of comments must be instantiated.";
assert object != null : "JSON Object must be instantiated.";
// Get the comments in an array
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
// Iterate over the submission results
JSONObject data;
Comment comment;
for (Object anArray : array) {
data = (JSONObject) anArray;
// Make sure it is of the correct kind
String kind = safeJsonToString(data.get("kind"));
if (kind != null) {
if (kind.equals(Kind.COMMENT.value())) {
// Contents of the comment
data = ((JSONObject) data.get("data"));
// Create and add the new comment
comment = new Comment(data);
comments.add(comment);
Object o = data.get("replies");
if (o instanceof JSONObject) {
// Dig towards the replies
JSONObject replies = (JSONObject) o;
parseRecursive(comment.getReplies(), replies);
}
} else if (kind.equals(Kind.MORE.value())) {
//data = (JSONObject) data.get("data");
//JSONArray children = (JSONArray) data.get("children");
//System.out.println("\t+ More children: " + children);
}
}
}
}
|
#vulnerable code
protected void parseRecursive(List<Comment> comments, JSONObject object) throws RetrievalFailedException, RedditError {
assert comments != null : "List of comments must be instantiated.";
assert object != null : "JSON Object must be instantiated.";
// Get the comments in an array
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
// Iterate over the submission results
JSONObject data;
Comment comment;
for (Object anArray : array) {
data = (JSONObject) anArray;
// Make sure it is of the correct kind
String kind = safeJsonToString(data.get("kind"));
if (kind.equals(Kind.COMMENT.value())) {
// Contents of the comment
data = ((JSONObject) data.get("data"));
// Create and add the new comment
comment = new Comment(data);
comments.add(comment);
Object o = data.get("replies");
if (o instanceof JSONObject) {
// Dig towards the replies
JSONObject replies = (JSONObject) o;
parseRecursive(comment.getReplies(), replies);
}
} else if (kind.equals(Kind.MORE.value())) {
//data = (JSONObject) data.get("data");
//JSONArray children = (JSONArray) data.get("children");
//System.out.println("\t+ More children: " + children);
}
}
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getSubreddit() {
return subreddit;
}
|
#vulnerable code
public String getSubreddit() throws IOException, ParseException {
if (subreddit != null) {
return subreddit;
}
if (url == null)
throw new IOException("URL needs to be present");
return info(url).get("subreddit").toString();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean hasModMail() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("has_mod_mail").toString());
}
|
#vulnerable code
public boolean hasModMail() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("has_mod_mail").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int linkKarma() throws IOException, ParseException {
return Integer.parseInt(Utils.toString(getUserInformation().get("link_karma")));
}
|
#vulnerable code
public int linkKarma() throws IOException, ParseException {
return Integer.parseInt(Utils.toString(info().get("link_karma")));
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public List<Subreddit> parse(String url) throws RetrievalFailedException, RedditError {
// Determine cookie
String cookie = (user == null) ? null : user.getCookie();
// List of subreddits
List<Subreddit> subreddits = new LinkedList<Subreddit>();
// Send request to reddit server via REST client
Object response = restClient.get(url, cookie).getResponseObject();
if (response instanceof JSONObject) {
JSONObject object = (JSONObject) response;
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
// Iterate over the subreddit results
JSONObject data;
for (Object anArray : array) {
data = (JSONObject) anArray;
// Make sure it is of the correct kind
String kind = safeJsonToString(data.get("kind"));
if (kind != null) {
if (kind.equals(Kind.SUBREDDIT.value())) {
// Create and add subreddit
data = ((JSONObject) data.get("data"));
subreddits.add(new Subreddit(data));
}
}
}
} else {
System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'");
}
// Finally return list of subreddits
return subreddits;
}
|
#vulnerable code
public List<Subreddit> parse(String url) throws RetrievalFailedException, RedditError {
// Determine cookie
String cookie = (user == null) ? null : user.getCookie();
// List of subreddits
List<Subreddit> subreddits = new LinkedList<Subreddit>();
// Send request to reddit server via REST client
Object response = restClient.get(url, cookie).getResponseObject();
if (response instanceof JSONObject) {
JSONObject object = (JSONObject) response;
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
// Iterate over the subreddit results
JSONObject data;
for (Object anArray : array) {
data = (JSONObject) anArray;
// Make sure it is of the correct kind
String kind = safeJsonToString(data.get("kind"));
if (kind.equals(Kind.SUBREDDIT.value())) {
// Create and add subreddit
data = ((JSONObject) data.get("data"));
subreddits.add(new Subreddit(data));
}
}
} else {
System.err.println("Cannot cast to JSON Object: '" + response.toString() + "'");
}
// Finally return list of subreddits
return subreddits;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getAuthor() {
return author;
}
|
#vulnerable code
public String getAuthor() throws IOException, ParseException {
if (author != null) {
return author;
}
if (url == null)
throw new IOException("URL needs to be present");
return info(url).get("author").toString();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String id() throws IOException, ParseException {
return getUserInformation().get("id").toString();
}
|
#vulnerable code
public String id() throws IOException, ParseException {
return info().get("id").toString();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static LinkedList<Submission> getSubmissions(String redditName,
Popularity type, Page frontpage, User user) throws IOException, ParseException {
LinkedList<Submission> submissions = new LinkedList<Submission>();
String urlString = "/r/" + redditName;
RestClient restClient = new HttpRestClient();
switch (type) {
case NEW:
urlString += "/new";
break;
default:
break;
}
//TODO Implement Pages
urlString += ".json";
JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie());
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
JSONObject data;
for (int i = 0; i < array.size(); i++) {
data = (JSONObject) array.get(i);
data = ((JSONObject) data.get("data"));
submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString())));
}
return submissions;
}
|
#vulnerable code
public static LinkedList<Submission> getSubmissions(String redditName,
Popularity type, Page frontpage, User user) throws IOException, ParseException {
LinkedList<Submission> submissions = new LinkedList<Submission>();
String urlString = "/r/" + redditName;
RestClient restClient = new Utils();
switch (type) {
case NEW:
urlString += "/new";
break;
default:
break;
}
//TODO Implement Pages
urlString += ".json";
JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie());
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
JSONObject data;
for (int i = 0; i < array.size(); i++) {
data = (JSONObject) array.get(i);
data = ((JSONObject) data.get("data"));
submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString())));
}
return submissions;
}
#location 27
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isGold() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("is_gold").toString());
}
|
#vulnerable code
public boolean isGold() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("is_gold").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public double createdUTC() throws IOException, ParseException {
return Double.parseDouble(getUserInformation().get("created_utc").toString());
}
|
#vulnerable code
public double createdUTC() throws IOException, ParseException {
return Double.parseDouble(info().get("created_utc").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public LinkedList<Submission> getSubmissions(String redditName,
Popularity type, Page frontpage, User user) throws IOException, ParseException {
LinkedList<Submission> submissions = new LinkedList<Submission>();
String urlString = "/r/" + redditName;
switch (type) {
case NEW:
urlString += "/new";
break;
default:
break;
}
//TODO Implement Pages
urlString += ".json";
JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject();
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
JSONObject data;
Submission submission;
for (Object anArray : array) {
data = (JSONObject) anArray;
data = ((JSONObject) data.get("data"));
submission = new Submission(data);
submission.setUser(user);
submissions.add(submission);
}
return submissions;
}
|
#vulnerable code
public LinkedList<Submission> getSubmissions(String redditName,
Popularity type, Page frontpage, User user) throws IOException, ParseException {
LinkedList<Submission> submissions = new LinkedList<Submission>();
String urlString = "/r/" + redditName;
switch (type) {
case NEW:
urlString += "/new";
break;
default:
break;
}
//TODO Implement Pages
urlString += ".json";
JSONObject object = (JSONObject) restClient.get(urlString, user.getCookie()).getResponseObject();
JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get("children");
JSONObject data;
for (Object anArray : array) {
data = (JSONObject) anArray;
data = ((JSONObject) data.get("data"));
submissions.add(new Submission(user, data.get("id").toString(), (data.get("permalink").toString())));
}
return submissions;
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean hasModMail() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("has_mod_mail").toString());
}
|
#vulnerable code
public boolean hasModMail() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("has_mod_mail").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int commentKarma() throws IOException, ParseException {
return Integer.parseInt(Utils.toString(getUserInformation().get("comment_karma")));
}
|
#vulnerable code
public int commentKarma() throws IOException, ParseException {
return Integer.parseInt(Utils.toString(info().get("comment_karma")));
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public double getCreatedUTC() {
return createdUTC;
}
|
#vulnerable code
public double getCreatedUTC() throws IOException, ParseException {
createdUTC = Double.parseDouble(info(url).get("created_utc").toString());
return createdUTC;
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean hasMail() throws IOException, ParseException {
return Boolean.parseBoolean(getUserInformation().get("has_mail").toString());
}
|
#vulnerable code
public boolean hasMail() throws IOException, ParseException {
return Boolean.parseBoolean(info().get("has_mail").toString());
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
}
|
#vulnerable code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
deleteWithCheck(fileHandle);
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void processEvents(int readyCount) throws IOReactorException {
processSessionRequests();
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
long currentTime = System.currentTimeMillis();
if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) {
this.lastTimeoutCheck = currentTime;
Set<SelectionKey> keys = this.selector.keys();
processTimeouts(keys);
}
}
|
#vulnerable code
@Override
protected void processEvents(int readyCount) throws IOReactorException {
processSessionRequests();
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
long currentTime = System.currentTimeMillis();
if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) {
this.lastTimeoutCheck = currentTime;
Set<SelectionKey> keys = this.selector.keys();
synchronized (keys) {
processTimeouts(keys);
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testInvalidInput() throws Exception {
String s = "stuff";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 3);
try {
decoder.read(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
|
#vulnerable code
@Test
public void testInvalidInput() throws Exception {
String s = "stuff";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 3);
try {
decoder.read(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
#location 14
#vulnerability type RESOURCE_LEAK
|
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.