output stringlengths 64 73.2k | input stringlengths 208 73.3k | instruction stringclasses 1
value |
|---|---|---|
#fixed code
public void testMultipleRetrieveCache() {
String randomApiString = this.getRandomString();
this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", ""));
for(int i=0; i < 500; i++) {
Optional<ApiResult> apiByPublicKey = this.a... | #vulnerable code
public void testMultipleRetrieveCache() {
String randomApiString = this.getRandomString();
this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", ""));
for(int i=0; i < 500; i++) {
ApiResult apiResult = this.api.getApi... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
List<String> fileLines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessC... | #vulnerable code
public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException {
BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath))));
List<... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getCurrentRevision(String repoLocations, String repoName) {
String currentRevision = "";
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml");
processBuilder.directory(new File(repoLocations + repoName)... | #vulnerable code
public String getCurrentRevision(String repoLocations, String repoName) {
String currentRevision = "";
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml");
processBuilder.directory(new File(repoLocations + rep... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testExecuteNothingInQueue() throws JobExecutionException {
IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob();
IndexGitRepoJob spy = spy(indexGitRepoJob);
when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue());
JobEx... | #vulnerable code
public void testExecuteNothingInQueue() throws JobExecutionException {
IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob();
IndexGitRepoJob spy = spy(indexGitRepoJob);
when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue());
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public synchronized void deleteRepoByName(String repositoryName) {
ConnStmtRs connStmtRs = new ConnStmtRs();
try {
connStmtRs.conn = this.dbConfig.getConnection();
connStmtRs.stmt = connStmtRs.conn.prepareStatement("delete from repo wh... | #vulnerable code
public synchronized void deleteRepoByName(String repositoryName) {
Connection connection;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
p... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) {
// svn diff -r 4000:HEAD --summarize --xml
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
... | #vulnerable code
public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) {
// svn diff -r 4000:HEAD --summarize --xml
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private String runCommand(String directory, String... command) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File(directory));
Process process = processBuilder.start();
InputStr... | #vulnerable code
private String runCommand(String directory, String... command) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.directory(new File(directory));
Process process = processBuilder.start();
In... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/server/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
List<String... | #vulnerable code
public void getGitChangeSets() throws IOException, GitAPIException {
Repository localRepository = new FileRepository(new File("./repo/.timelord/test/.git"));
Git git = new Git(localRepository);
Iterable<RevCommit> logs = git.log().call();
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) {
Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument);
ConnStmtRs connStmtRs = new ConnStmtRs();
try {
connStmtRs.conn = this.dbConfig.getConn... | #vulnerable code
public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) {
Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument);
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = thi... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void configWriter(String content, Path filePath) {
if(Files.exists(filePath) && !Files.isWritable(filePath)){
log.error("Error file is not writable: " + filePath);
return;
}
if(Files.notExists(filePath.getParent())) {
try {
Files.createDirectories(f... | #vulnerable code
private void configWriter(String content, Path filePath) {
if(Files.exists(filePath) && !Files.isWritable(filePath)){
log.error("Error file is not writable: " + filePath);
return;
}
if(Files.notExists(filePath.getParent())) {
try {
Files.createDirecto... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getCategor... | #vulnerable code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getC... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity,
Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) {
Socket dataSendSocket = null;
log.debug("executing HUE api request to TCP: "... | #vulnerable code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity,
Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) {
log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsS... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Home createHome(BridgeSettings bridgeSettings) {
fhemMap = null;
validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidFhem();
log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured."));
if(validFhem) {
fhemMap = new HashMa... | #vulnerable code
@Override
public Home createHome(BridgeSettings bridgeSettings) {
fhemMap = null;
validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidOpenhab();
log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured."));
if(validFhem) {
fhemMap = n... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) {
String validUser = null;
boolean found = false;
if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null")
&& !aUser.equalsIgnoreCase("")) ... | #vulnerable code
public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) {
String validUser = null;
boolean found = false;
if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null")
&& !aUser.equalsIgnoreCase... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.getIte... | #vulnerable code
@Override
public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) {
log.debug("Exec Request called with url: " + anItem.... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(HABridge.class);
DeviceResource theResources;
HomeManager homeManager;
HueMulator theHueMulator;
UDPDatagramSender udpSender;
UpnpSettingsResource the... | #vulnerable code
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger(HABridge.class);
DeviceResource theResources;
HomeManager homeManager;
HueMulator theHueMulator;
UDPDatagramSender udpSender;
UpnpSettingsResour... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getCategor... | #vulnerable code
private void denormalizeSdata(Sdata theSdata) {
Map<String,Room> roomMap = new HashMap<String,Room>();
for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i);
Map<String,Categorie> categoryMap = new HashMap<String,Categorie>();
for (Categorie i : theSdata.getC... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\',... | #vulnerable code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF8_OV... | #vulnerable code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
load(new FileInputStream(file));
}
#location 4
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return loadPlugin(file, false);
} | #vulnerable code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
JavaPlugin result = null;
PluginDescriptionFile description = null;
if (!file.exists()) {
throw new InvalidP... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
... | #vulnerable code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void recalculatePermissions() {
clearPermissions();
Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp());
Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent);
for (Perm... | #vulnerable code
public void recalculatePermissions() {
dirtyPermissions = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConsumerNormalOps() throws InterruptedException, ExecutionException {
// Tests create instance, read, and delete
final List<ConsumerRecord> referenceRecords = Arrays.asList(
new ConsumerRecord("k1".getBytes(), "v1".get... | #vulnerable code
@Test
public void testConsumerNormalOps() throws InterruptedException, ExecutionException {
// Tests create instance, read, and delete
final List<ConsumerRecord> referenceRecords = Arrays.asList(
new ConsumerRecord("k1".getBytes(), "v... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void test() {
JedisPoolConfig config = new JedisPoolConfig();
// 设置空间连接
config.setMaxIdle(20);
config.setMaxWaitMillis(1000);
// JedisPool pool = new JedisPool(config, "27.126.180.210", 6379);
// System.out.pri... | #vulnerable code
@Test
public void test() {
JedisPoolConfig config = new JedisPoolConfig();
// 设置空间连接
config.setMaxIdle(20);
config.setMaxWaitMillis(1000);
JedisPool pool = new JedisPool(config, "27.126.180.210", 6379);
System.out.p... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public File saveAs(String path) throws IOException, InterruptedException {
byte[] pdf = this.getPDF();
File file = new File(path);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
bufferedOutputStr... | #vulnerable code
public File saveAs(String path) throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
String command = this.commandWithParameters() + Symbol.separator + path;
Process proc = rt.exec(command);
if(htmlFromString) {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] getPDF() throws IOException, InterruptedException {
return getPDF(STDOUT);
} | #vulnerable code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
if(htmlFromString && !this.params.contains(new Param("-"))) {
this.addParam(new Param("-"));
}
String command = this.com... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public File saveAs(String path) throws IOException, InterruptedException {
byte[] pdf = this.getPDF();
File file = new File(path);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
bufferedOutputStr... | #vulnerable code
public File saveAs(String path) throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
String command = this.commandWithParameters() + Symbol.separator + path;
Process proc = rt.exec(command);
if(htmlFromString) {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] getPDF() throws IOException, InterruptedException {
return getPDF(STDOUT);
} | #vulnerable code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
if(htmlFromString && !this.params.contains(new Param("-"))) {
this.addParam(new Param("-"));
}
String command = this.com... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(getCommandAsArray());
StreamEater outputStreamEater = new StreamEater(process.getInputStream());
outputStr... | #vulnerable code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(getCommandAsArray());
for (Page page : pages) {
if (page.getType().equals(PageType.htmlAsString)... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public File saveAs(String path) throws IOException, InterruptedException {
byte[] pdf = this.getPDF();
File file = new File(path);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
bufferedOutputStr... | #vulnerable code
public File saveAs(String path) throws IOException, InterruptedException {
Runtime rt = Runtime.getRuntime();
String command = this.commandWithParameters() + Symbol.separator + path;
Process proc = rt.exec(command);
if(htmlFromString) {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFieldPopulator()
{
Album funeral = DataGenerator.funeral();
ResultTraverser traverser = new ResultTraverser();
populatorRegistry.register( new AlbumFieldPopulator() );
YogaRequestContext requestContext = new YogaR... | #vulnerable code
@Test
public void testFieldPopulator()
{
Album funeral = DataGenerator.funeral();
ResultTraverser traverser = new ResultTraverser();
populatorRegistry.register( new AlbumFieldPopulator() );
YogaRequestContext requestContext = new... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSelectUnsupportedField()
{
Album chasingProphecy = DataGenerator.chasingProphecy();
ResultTraverser traverser = new ResultTraverser();
populatorRegistry.register( new AlbumFieldPopulator() );
Map<String,Object> ob... | #vulnerable code
@Test
public void testSelectUnsupportedField()
{
Album chasingProphecy = DataGenerator.chasingProphecy();
ResultTraverser traverser = new ResultTraverser();
populatorRegistry.register( new AlbumFieldPopulator() );
Map<String,Obje... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testComplexCoreFields()
{
User carter = DataGenerator.carter();
carter.getFavoriteArtists().add( DataGenerator.neutralMilkHotel() );
carter.getFavoriteArtists().add( DataGenerator.arcadeFire() );
ResultTraverser traver... | #vulnerable code
@Test
public void testComplexCoreFields()
{
User carter = DataGenerator.carter();
carter.getFavoriteArtists().add( DataGenerator.neutralMilkHotel() );
carter.getFavoriteArtists().add( DataGenerator.arcadeFire() );
ResultTraverser ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
@Test
// Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata
// for the album object.
public void testMetadataHref()
{
String prefixUrl = "/metadata/";
String f... | #vulnerable code
@SuppressWarnings("unchecked")
@Test
// Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata
// for the album object.
public void testMetadataHref()
{
String prefixUrl = "/metadata/";
St... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init()
{
try
{
init( Thread.currentThread().getContextClassLoader().getResourceAsStream( "sampledb.sql" ) );
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
// this do... | #vulnerable code
public void init() throws IOException
{
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( "sampledb.sql" );
BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
String line = null;
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAnnotatedModel()
{
User solomon = DataGenerator.solomon();
ResultTraverser traverser = new ResultTraverser();
YogaRequestContext requestContext = new YogaRequestContext( "test", new GDataSelectorParser(),
... | #vulnerable code
@Test
public void testAnnotatedModel()
{
User solomon = DataGenerator.solomon();
ResultTraverser traverser = new ResultTraverser();
YogaRequestContext requestContext = new YogaRequestContext( "test",
new DummyHttpServletR... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testView() throws IOException {
store.setAttribute("owner:owner", createUserPrincipal("user"));
PosixFileAttributeView view = provider.getView(attributeStoreSupplier());
assertNotNull(view);
ASSERT.that(view.name()).is("posix");
ASSERT.... | #vulnerable code
@Test
public void testView() throws IOException {
PosixFileAttributeView view = service.getFileAttributeView(
fileSupplier(), PosixFileAttributeView.class);
assertNotNull(view);
ASSERT.that(view.name()).is("posix");
ASSERT.that(view.getOwner()).... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testView() throws IOException {
AclFileAttributeView view = provider.getView(attributeStoreSupplier());
assertNotNull(view);
ASSERT.that(view.name()).is("acl");
ASSERT.that(view.getAcl()).is(defaultAcl);
view.setAcl(ImmutableList.<AclE... | #vulnerable code
@Test
public void testView() throws IOException {
AclFileAttributeView view =
service.getFileAttributeView(fileSupplier(), AclFileAttributeView.class);
assertNotNull(view);
ASSERT.that(view.name()).is("acl");
ASSERT.that(view.getAcl()).is(defau... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testClosedChannel() throws Throwable {
RegularFile file = regularFile(15);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
JimfsAsynchronousFileChannel channel = channel(file, executor, READ, WRITE);
channel.clo... | #vulnerable code
@Test
public void testClosedChannel() throws IOException, InterruptedException {
RegularFile file = regularFile(15);
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
JimfsAsynchronousFileChannel channel = channel(file, executor, R... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testView() throws IOException {
UserDefinedFileAttributeView view = provider.getView(attributeStoreSupplier());
assertNotNull(view);
ASSERT.that(view.name()).is("user");
ASSERT.that(view.list()).isEmpty();
byte[] b1 = {0, 1, 2};
byt... | #vulnerable code
@Test
public void testView() throws IOException {
UserDefinedFileAttributeView view =
service.getFileAttributeView(fileSupplier(), UserDefinedFileAttributeView.class);
assertNotNull(view);
ASSERT.that(view.name()).is("user");
ASSERT.that(view.li... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static FileSystem newFileSystem(String name) {
return newFileSystem(name, Configuration.forCurrentPlatform());
} | #vulnerable code
public static FileSystem newFileSystem(String name) {
String os = System.getProperty("os.name");
Configuration config;
if (os.contains("Windows")) {
config = Configuration.windows();
} else if (os.contains("OS X")) {
config = Configuration.osX... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAsynchronousClose() throws Exception {
RegularFile file = regularFile(10);
final FileChannel channel = channel(file, READ, WRITE);
file.writeLock().lock(); // ensure all operations on the channel will block
ExecutorService executor = Ex... | #vulnerable code
@Test
public void testAsynchronousClose() throws IOException, InterruptedException {
RegularFile file = regularFile(10);
final FileChannel channel = channel(file, READ, WRITE);
file.writeLock().lock(); // ensure all operations on the channel will block
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public WatchService newWatchService() throws IOException {
return watchServiceConfig.newWatchService(defaultView, pathService);
} | #vulnerable code
@Override
public WatchService newWatchService() throws IOException {
return new PollingWatchService(defaultView, pathService, fileStore.state());
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public JimfsPath toRealPath(
JimfsPath path, PathService pathService, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
store.readLock().lock();
try {
DirectoryEntry entry = lookUp(path, options)
... | #vulnerable code
public JimfsPath toRealPath(
JimfsPath path, PathService pathService, Set<? super LinkOption> options) throws IOException {
checkNotNull(path);
checkNotNull(options);
store.readLock().lock();
try {
DirectoryEntry entry = lookUp(path, options)
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testCloseByInterrupt() throws Exception {
RegularFile file = regularFile(10);
final FileChannel channel = channel(file, READ, WRITE);
file.writeLock().lock(); // ensure all operations on the channel will block
ExecutorService executor = Exe... | #vulnerable code
@Test
public void testCloseByInterrupt() throws IOException, InterruptedException {
RegularFile file = regularFile(10);
final FileChannel channel = channel(file, READ, WRITE);
file.writeLock().lock(); // ensure all operations on the channel will block
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testView() throws IOException {
DosFileAttributeView view = provider.getView(attributeStoreSupplier());
assertNotNull(view);
ASSERT.that(view.name()).is("dos");
DosFileAttributes attrs = view.readAttributes();
ASSERT.that(attrs.isHidden... | #vulnerable code
@Test
public void testView() throws IOException {
DosFileAttributeView view =
service.getFileAttributeView(fileSupplier(), DosFileAttributeView.class);
assertNotNull(view);
ASSERT.that(view.name()).is("dos");
DosFileAttributes attrs = view.read... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) {
loadProperties();
int concurrents = Integer.parseInt(properties.getProperty("concurrents"));
int runtime = Integer.parseInt(properties.getProperty("runtime"));
String classname = properties.getProperty("... | #vulnerable code
public static void main(String[] args) {
int concurrents = Integer.parseInt(properties.getProperty("concurrents"));
int runtime = Integer.parseInt(properties.getProperty("runtime"));
String classname = properties.getProperty("classname");
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void register(List<URL> registryUrls, URL serviceUrl) {
for (URL url : registryUrls) {
// 根据check参数的设置,register失败可能会抛异常,上层应该知晓
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtension(url... | #vulnerable code
private void register(List<URL> registryUrls, URL serviceUrl) {
for (URL url : registryUrls) {
// 根据check参数的设置,register失败可能会抛异常,上层应该知晓
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getExtensio... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Before
public void setup() throws DBException {
orientDBClient = new OrientDBClient();
Properties p = new Properties();
// TODO: Extract the property names into final variables in OrientDBClient
p.setProperty("orientdb.url", TEST_DB_URL);
orientDBClient... | #vulnerable code
@Before
public void setup() throws DBException {
orientDBClient = new OrientDBClient();
Properties p = new Properties();
// TODO: Extract the property names into final variables in OrientDBClient
p.setProperty("orientdb.url", TEST_DB_URL);
orientDB... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void cleanup() throws DBException
{
// Get the measurements instance as this is the only client that should
// count clean up time like an update since autoflush is off.
Measurements _measurements = Measurements.getMeasurements();
tr... | #vulnerable code
public void cleanup() throws DBException
{
// Get the measurements instance as this is the only client that should
// count clean up time like an update since autoflush is off.
Measurements _measurements = Measurements.getMeasurements();
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int read(String table, String key, Set<String> fields,
HashMap<String, ByteIterator> result) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document query = ne... | #vulnerable code
@Override
public int read(String table, String key, Set<String> fields,
HashMap<String, ByteIterator> result) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document quer... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static RemoteCacheManager getInstance(Properties props){
RemoteCacheManager result = cacheManager;
if(result == null){
synchronized (RemoteCacheManagerHolder.class) {
result = cacheManager;
if (result == null) {
cacheManager = result = new RemoteCacheM... | #vulnerable code
public static RemoteCacheManager getInstance(Properties props){
if(cacheManager == null){
synchronized (RemoteCacheManager.class) {
cacheManager = new RemoteCacheManager(props);
}
}
return cacheManager;
}
#location 7
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() throws DBException
{
if ( (getProperties().getProperty("debug")!=null) &&
(getProperties().getProperty("debug").compareTo("true")==0) )
{
_debug=true;
}
if (getProperties().containsKey("client... | #vulnerable code
public void init() throws DBException
{
if ( (getProperties().getProperty("debug")!=null) &&
(getProperties().getProperty("debug").compareTo("true")==0) )
{
_debug=true;
}
if (getProperties().containsKey("... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
try {
PreparedStatement stmt = (fields == null) ? scanAllStmt.get() : scanStmts.get(fields);
// Prepare sta... | #vulnerable code
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
try {
Statement stmt;
Select.Builder selectBuilder;
if (fields == null) {
selectBuilder... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
PreparedStatement stmt = (fields == null) ? readAllStmt.get() : readStmts.get(fields);
// Prepare statement on demand
if (stmt == ... | #vulnerable code
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Statement stmt;
Select.Builder selectBuilder;
if (fields == null) {
selectBuilder = QueryBuilder.select().all();
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
MongoCursor<Document> cursor = null;
try {
MongoCollection<Document> collection = database... | #vulnerable code
@Override
public int scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
MongoCursor<Document> cursor = null;
try {
MongoCollection<Document> collection = da... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init() throws DBException {
Properties props = getProperties();
String url = props.getProperty(URL_PROPERTY);
String user = props.getProperty(USER_PROPERTY, USER_PROPERTY_DEFAULT);
String password = props.getProperty(PASSWORD_PROPERTY, P... | #vulnerable code
@Override
public void init() throws DBException {
Properties props = getProperties();
String url = props.getProperty(URL_PROPERTY);
String user = props.getProperty(USER_PROPERTY, USER_PROPERTY_DEFAULT);
String password = props.getProperty(PASSWORD_PROPE... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status delete(String table, String key) {
try {
PreparedStatement stmt = deleteStmt.get();
// Prepare statement on demand
if (stmt == null) {
stmt = session.prepare(QueryBuilder.delete().from(table)
... | #vulnerable code
@Override
public Status delete(String table, String key) {
try {
Statement stmt;
stmt = QueryBuilder.delete().from(table)
.where(QueryBuilder.eq(YCSB_KEY, key));
stmt.setConsistencyLevel(writeConsistencyLevel);
if (debug) {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Before
public void setUp() throws Exception {
session = cassandraUnit.getSession();
Properties p = new Properties();
p.setProperty("hosts", HOST);
p.setProperty("port", Integer.toString(PORT));
p.setProperty("table", TABLE);
Measurements.setProperti... | #vulnerable code
@Before
public void setUp() throws Exception {
// check that this is Java 8+
int javaVersion = Integer.parseInt(System.getProperty("java.version").split("\\.")[1]);
Assume.assumeTrue(javaVersion >= 8);
session = cassandraUnit.getSession();
Properti... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected net.spy.memcached.MemcachedClient createMemcachedClient()
throws Exception {
ConnectionFactoryBuilder connectionFactoryBuilder =
new ConnectionFactoryBuilder();
connectionFactoryBuilder.setReadBufferSize(Integer.parseInt(
getProperties()... | #vulnerable code
protected net.spy.memcached.MemcachedClient createMemcachedClient()
throws Exception {
ConnectionFactoryBuilder connectionFactoryBuilder =
new ConnectionFactoryBuilder();
connectionFactoryBuilder.setReadBufferSize(Integer.parseInt(
getProper... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean doTransaction(DB db, Object threadstate) {
String operation = operationchooser.nextString();
if (operation == null) {
return false;
}
switch (operation) {
case "UPDATE":
doTransactionUpdate(db);
break;
case "... | #vulnerable code
@Override
public boolean doTransaction(DB db, Object threadstate) {
switch (operationchooser.nextString()) {
case "UPDATE":
doTransactionUpdate(db);
break;
case "INSERT":
doTransactionInsert(db);
break;
case "DELETE":
doTran... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void cleanup() throws DBException {
// Get the measurements instance as this is the only client that should
// count clean up time like an update if client-side buffering is
// enabled.
Measurements measurements = Measurements.getMeasurements(... | #vulnerable code
@Override
public void cleanup() throws DBException {
// Get the measurements instance as this is the only client that should
// count clean up time like an update if client-side buffering is
// enabled.
Measurements measurements = Measurements.getMeasure... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Map<String, byte[]> convertToBytearrayMap(Map<String,ByteIterator> values) {
Map<String, byte[]> retVal = new HashMap<String, byte[]>();
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
retVal.put(entry.getKey(), entry.getValue().toArray()... | #vulnerable code
private Map<String, byte[]> convertToBytearrayMap(Map<String,ByteIterator> values) {
Map<String, byte[]> retVal = new HashMap<String, byte[]>();
for (String key : values.keySet()) {
retVal.put(key, values.get(key).toArray());
}
return retVal;
}
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status delete(String table, String key) {
if (debug) {
System.out.println("Doing delete for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder()
.setRowKey(ByteStr... | #vulnerable code
@Override
public Status delete(String table, String key) {
if (debug) {
System.out.println("Doing delete for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder()
.setRowKey(B... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void cleanup() throws DBException {
if (asyncExecutor != null) {
try {
asyncExecutor.flush();
} catch (IOException e) {
throw new DBException(e);
}
}
synchronized (CONFIG) {
--threadCount;
if (threadCo... | #vulnerable code
@Override
public void cleanup() throws DBException {
if (asyncExecutor != null) {
try {
asyncExecutor.flush();
} catch (IOException e) {
throw new DBException(e);
}
}
synchronized (threadCount) {
--threadCount;
i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init() throws DBException {
if ("true"
.equals(getProperties().getProperty("clientbuffering", "false"))) {
this.clientSideBuffering = true;
}
if (getProperties().containsKey("writebuffersize")) {
writeBufferSize =
... | #vulnerable code
@Override
public void init() throws DBException {
if ("true"
.equals(getProperties().getProperty("clientbuffering", "false"))) {
this.clientSideBuffering = true;
}
if (getProperties().containsKey("writebuffersize")) {
writeBufferSize =
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new BufferedMutatorParams(tName);
p.writ... | #vulnerable code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
synchronized (CONNECTION_LOCK) {
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() throws DBException {
Properties props = getProperties();
String url = props.getProperty(URL_PROPERTY);
String user = props.getProperty(USER_PROPERTY, USER_PROPERTY_DEFAULT);
String password = props.getProperty(PASSWORD_PROPERTY, PASSWORD_PROP... | #vulnerable code
public void init() throws DBException {
// initialize OrientDB driver
Properties props = getProperties();
String url;
if (System.getProperty("os.name").toLowerCase().contains("win"))
url = props.getProperty("orientdb.url", "plocal:C:/temp/databases/... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status update(String table, String key,
HashMap<String, ByteIterator> values) {
if (debug) {
System.out.println("Setting up put for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = MutateRowR... | #vulnerable code
@Override
public Status update(String table, String key,
HashMap<String, ByteIterator> values) {
if (debug) {
System.out.println("Setting up put for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = Muta... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void acknowledge(int value)
{
// read volatile variable to see other threads' changes
limit = limit;
if (value > limit + WINDOW_SIZE) {
throw new RuntimeException("Too many unacknowledged insertion keys.");
}
window[value % WINDOW_SIZE] = true;
if (lock... | #vulnerable code
public void acknowledge(int value)
{
if (value > limit + WINDOW_SIZE) {
throw new RuntimeException("This should be a different exception.");
}
window[value % WINDOW_SIZE] = true;
if (lock.tryLock()) {
// move a contiguous sequence from the window
// ove... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init() throws DBException {
Properties props = getProperties();
// Defaults the user can override if needed
CONFIG.set("google.bigtable.auth.service.account.enable", "true");
// make it easy on ourselves by copying all CLI prope... | #vulnerable code
@Override
public void init() throws DBException {
Properties props = getProperties();
// Defaults the user can override if needed
CONFIG.set("google.bigtable.auth.service.account.enable", "true");
// make it easy on ourselves by copying all CLI... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init() throws DBException {
if ("true"
.equals(getProperties().getProperty("clientbuffering", "false"))) {
this.clientSideBuffering = true;
}
if (getProperties().containsKey("writebuffersize")) {
writeBufferSize =
... | #vulnerable code
@Override
public void init() throws DBException {
if ("true"
.equals(getProperties().getProperty("clientbuffering", "false"))) {
this.clientSideBuffering = true;
}
if (getProperties().containsKey("writebuffersize")) {
writeBufferSize =
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Before
public void setup() throws DBException {
orientDBClient = new OrientDBClient();
Properties p = new Properties();
// TODO: Extract the property names into final variables in OrientDBClient
p.setProperty("orientdb.url", TEST_DB_URL);
orientDBClient... | #vulnerable code
@Before
public void setup() throws DBException {
orientDBClient = new OrientDBClient();
Properties p = new Properties();
// TODO: Extract the property names into final variables in OrientDBClient
p.setProperty("orientdb.url", TEST_DB_URL);
orientDB... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
// Azure Cosmos does not have patch support. Until then we need to read
// the document, update in place, and then write back.
// This could actually be made more efficie... | #vulnerable code
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
String documentLink = getDocumentLink(this.databaseName, table, key);
Document document = getDocumentDefinition(key, values);
RequestOptions reqOptions = getRequest... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
synchronized (CONNECTION_LOCK) {
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new... | #vulnerable code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
this.currentTable = this.connection.getTable(tName);
// suggestions from
// http://ryantwopointoh.blogspot.com/2009/01/
// performance-of-hbase-i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean doTransaction(DB db, Object threadstate) {
String operation = operationchooser.nextString();
if(operation == null) {
return false;
}
switch (operation) {
case "READ":
doTransactionRead(db);
break;
case "UPDAT... | #vulnerable code
@Override
public boolean doTransaction(DB db, Object threadstate) {
switch (operationchooser.nextString()) {
case "READ":
doTransactionRead(db);
break;
case "UPDATE":
doTransactionUpdate(db);
break;
case "INSERT":
doTransact... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int insert(String table, String key,
HashMap<String, ByteIterator> values) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document toInsert = new Document("_id... | #vulnerable code
@Override
public int insert(String table, String key,
HashMap<String, ByteIterator> values) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document toInsert = new Documen... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new BufferedMutatorParams(tName);
p.writ... | #vulnerable code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
synchronized (CONNECTION_LOCK) {
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
List<Document> documents;
FeedResponse<Document> feedResponse = null;
try {
FeedOptions feed... | #vulnerable code
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
List<Document> documents;
FeedResponse<Document> feedResponse = null;
try {
feedRespon... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void writeTo( Writer writer, WriterConfig config ) throws IOException {
if( writer == null ) {
throw new NullPointerException( "writer is null" );
}
if( config == null ) {
throw new NullPointerException( "config is null" );
}
WritingBuffer... | #vulnerable code
public void writeTo( Writer writer, WriterConfig config ) throws IOException {
WritingBuffer buffer = new WritingBuffer( writer, 128 );
write( config == null ? new JsonWriter( buffer ) : config.createWriter( buffer ) );
buffer.flush();
}
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public long query(int end) {
end--;
final int blockIndex = end / sqrt;
final int freq[] = new int[powers.length];
final int queue[] = new int[sqrt];
int count = 0;
final int endIndex = end % sqrt;
for (int i = 0; i <= en... | #vulnerable code
public long query(int end) {
end--;
final int blockIndex = end / sqrt;
final Map<Integer, Integer> map = new HashMap<>();
final int[][] elements = new int[sqrt][2];
int count = 0;
final int endIndex = end % sqrt;
f... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException {
final InputReader in = new InputReader(System.in);
V = in.readInt();
final int Q = in.readInt();
final Query queries[] = new Query[MAX];
final Update updates[] = new Update[MAX... | #vulnerable code
public static void main(String[] args) throws IOException {
final InputReader in = new InputReader(System.in);
int qSZ = 0, uSZ = 0;
V = in.readInt();
int Q = in.readInt();
int E = V - 1;
Query queries[] = new Query[MAX];
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@CacheEvict(value={"metaCaches","metaCache"},allEntries=true,beforeInvocation=true)
public void saveMeta(String type, String name, Integer mid) {
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(name)){
MetaCond metaCond = new M... | #vulnerable code
@Override
@CacheEvict(value={"metaCaches","metaCache"},allEntries=true,beforeInvocation=true)
public void saveMeta(String type, String name, Integer mid) {
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(name)){
MetaCond metaCond =... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
/**
* @todo should we use solrDocIdentifierDataset or
* IndexableObject.IndexableTypes.DATASET.getName() + "_" ?
*/
// String so... | #vulnerable code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
/**
* @todo should we use solrDocIdentifierDataset or
* IndexableObject.IndexableTypes.DATASET.getName() + "_" ?
*/
// Str... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String save() {
Command<Dataverse> cmd = null;
//TODO change to Create - for now the page is expecting INFO instead.
if (dataverse.getId() == null){
dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId... | #vulnerable code
public String save() {
Command<Dataverse> cmd = null;
if ( editMode == EditMode.INFO ) {
dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null);
cmd = new CreateDataverseCommand(dataverse, session.getUser());
}... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() {
if (dataset.getId() != null) { // view mode for a dataset
dataset = datasetService.find(dataset.getId());
editVersion = dataset.getLatestVersion();
editVersion.setDatasetFieldValues(editVersion.initDa... | #vulnerable code
public void init() {
if (dataset.getId() != null) { // view mode for a dataset
dataset = datasetService.find(dataset.getId());
editVersion = dataset.getLatestVersion();
editValues = editVersion.getDatasetFieldValues... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void writeTo(DownloadInstance di, Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outstream) throws IOException, WebApplicationException {
if (di.getDownloadInfo() ... | #vulnerable code
@Override
public void writeTo(DownloadInstance di, Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outstream) throws IOException, WebApplicationException {
if (di.getDownloadI... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
Collection<SolrInputDocument> docs = new ArrayList<>();
List<String> dataversePathSegmentsAccumulator = new ArrayList<>();
List<String> dataverseS... | #vulnerable code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
Collection<SolrInputDocument> docs = new ArrayList<>();
List<String> dataversePathSegmentsAccumulator = new ArrayList<>();
// List<String> da... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String releaseDraft() {
if (releaseRadio == 1) {
return releaseDataset(false);
} else {
return releaseDataset(true);
}
} | #vulnerable code
public String releaseDraft() {
if (releaseRadio == 1) {
dataset.getEditVersion().setVersionNumber(new Long(dataset.getReleasedVersion().getVersionNumber().intValue() + 1));
dataset.getEditVersion().setMinorVersionNumber(new Long(0));
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String releaseDraft() {
if (releaseRadio == 1) {
return releaseDataset(false);
} else {
return releaseDataset(true);
}
} | #vulnerable code
public String releaseDraft() {
if (releaseRadio == 1) {
dataset.getEditVersion().setVersionNumber(new Long(dataset.getReleasedVersion().getVersionNumber().intValue() + 1));
dataset.getEditVersion().setMinorVersionNumber(new Long(0));
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void deleteContainer(String uri, AuthCredentials authCredentials, SwordConfiguration sc) throws SwordError, SwordServerException, SwordAuthException {
// swordConfiguration = (SwordConfigurationImpl) sc;
DataverseUser vdcUser = swordAuth.au... | #vulnerable code
@Override
public void deleteContainer(String uri, AuthCredentials authCredentials, SwordConfiguration sc) throws SwordError, SwordServerException, SwordAuthException {
// swordConfiguration = (SwordConfigurationImpl) sc;
DataverseUser vdcUser = swordA... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
String solrIdDraftStudy = "dataset_" + dataset.getId() + "_draft";
String solrIdPublishedStudy = "dataset_" + dataset.getId();
StringBuilder sb = ... | #vulnerable code
public String indexDataset(Dataset dataset) {
logger.info("indexing dataset " + dataset.getId());
Collection<SolrInputDocument> docs = new ArrayList<>();
List<String> dataversePathSegmentsAccumulator = new ArrayList<>();
List<String> data... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public synchronized String CalculateMD5 (String datafile) {
FileInputStream fis = null;
try {
fis = new FileInputStream(datafile);
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
... | #vulnerable code
public synchronized String CalculateMD5 (String datafile) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
Fil... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String save() {
// Validate
boolean dontSave = false;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
for (DatasetField dsf : editVersion.getFlatDatasetFields()... | #vulnerable code
public String save() {
dataset.setOwner(dataverseService.find(ownerId));
//TODO get real application-wide protocol/authority
dataset.setProtocol("doi");
dataset.setAuthority("10.5072/FK2");
dataset.setIdentifier("5555");
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() {
if (dataset.getId() != null) { // view mode for a dataset
dataset = datasetService.find(dataset.getId());
editVersion = dataset.getLatestVersion();
ownerId = dataset.getOwner().getId();
e... | #vulnerable code
public void init() {
if (dataset.getId() != null) { // view mode for a dataset
dataset = datasetService.find(dataset.getId());
editVersion = dataset.getLatestVersion();
ownerId = dataset.getOwner().getId();
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void handleDropBoxUpload(ActionEvent e) {
// Read JSON object from the output of the DropBox Chooser:
JsonReader dbJsonReader = Json.createReader(new StringReader(dropBoxSelection));
JsonArray dbArray = dbJsonReader.readArray();
dbJsonR... | #vulnerable code
public void handleDropBoxUpload(ActionEvent e) {
// Read JSON object from the output of the DropBox Chooser:
JsonReader dbJsonReader = Json.createReader(new StringReader(dropBoxSelection));
JsonArray dbArray = dbJsonReader.readArray();
d... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String save() {
dataset.setOwner(dataverseService.find(ownerId));
//TODO get real application-wide protocol/authority
dataset.setProtocol("doi");
dataset.setAuthority("10.5072/FK2");
dataset.setIdentifier("5555");
//TODO ... | #vulnerable code
public String save() {
dataset.setOwner(dataverseService.find(ownerId));
//TODO get real application-wide protocol/authority
dataset.setProtocol("doi");
dataset.setAuthority("10.5072/FK2");
dataset.setIdentifier("5555");
/... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Path("dsPreview/{datasetId}")
@GET
@Produces({ "image/png" })
public InputStream dsPreview(@PathParam("datasetId") Long datasetId, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) /*throws NotFoundException, ServiceUn... | #vulnerable code
@Path("dsPreview/{datasetId}")
@GET
@Produces({ "image/png" })
public InputStream dsPreview(@PathParam("datasetId") Long datasetId, @Context UriInfo uriInfo, @Context HttpHeaders headers, @Context HttpServletResponse response) /*throws NotFoundException, Ser... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Statement getStatement(String editUri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
this.swordConfiguration = (SwordConfigurationImpl... | #vulnerable code
@Override
public Statement getStatement(String editUri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
this.swordConfiguration = (SwordConfigurati... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String save() {
dataset.setOwner(dataverseService.find(ownerId));
//TODO get real application-wide protocol/authority
dataset.setProtocol("doi");
dataset.setAuthority("10.5072/FK2");
dataset.setIdentifier("5555");
/*
... | #vulnerable code
public String save() {
dataset.setOwner(dataverseService.find(ownerId));
//TODO get real application-wide protocol/authority
dataset.setProtocol("doi");
dataset.setAuthority("10.5072/FK2");
dataset.setIdentifier("5555");
/... | 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.