output stringlengths 64 73.2k | input stringlengths 208 73.3k | instruction stringclasses 1
value |
|---|---|---|
#fixed code
public Key<?> exists(final Object entityOrKey) {
final Query<?> query = buildExistsQuery(entityOrKey);
return query.getKey();
} | #vulnerable code
public Key<?> exists(final Object entityOrKey) {
final Object unwrapped = ProxyHelper.unwrap(entityOrKey);
final Key<?> key = mapper.getKey(unwrapped);
final Object id = key.getId();
if (id == null) {
throw new MappingException("Could not get id for ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) {
//TODO: Do this without creating another iterator
DBCollection dbColl = getCollection(entities.iterator().next());
return insert(dbColl, entities, wc);
} | #vulnerable code
public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) {
ArrayList<DBObject> ents = entities instanceof List ? new ArrayList<DBObject>(((List<T>)entities).size()) : new ArrayList<DBObject>();
Map<Object, DBObject> involvedObjects = new LinkedHashMap... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getCollectionName(Object object) {
if (object == null) throw new IllegalArgumentException();
MappedClass mc = getMappedClass(object);
return mc.getCollectionName();
} | #vulnerable code
public String getCollectionName(Object object) {
MappedClass mc = getMappedClass(object);
return mc.getCollectionName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new Linked... | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = null;
if(cfg !=... | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = cfg.getPlugins();
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void load() throws ConfigurationException {
Collection<PluginConfig> plugins = configuration.getPlugins();
PluginConfig plugin = null;
Collection<File> jarsToLoad = new LinkedList<File>();
ConfigurationException ce = null;
try {
if (plugins != null... | #vulnerable code
@Override
public void load() throws ConfigurationException {
Collection<PluginConfig> plugins = configuration.getPlugins();
PluginConfig plugin = null;
Collection<File> jarsToLoad = new LinkedList<File>();
try {
if (plugins != null) {
Iterator<PluginConfig>... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new Linked... | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void write(Object n, VisitorContext vc) throws Exception {
File out = null;
boolean createdEmptyFile = false;
if (vc != null) {
out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY);
}
if (out == null) {
log.debug("Creating the target source file. This is... | #vulnerable code
public void write(Object n, VisitorContext vc) throws Exception {
File out = null;
boolean createdEmptyFile = false;
if (vc != null) {
out = (File) vc.get(AbstractWalker.ORIGINAL_FILE_KEY);
}
if (out == null) {
log.debug("Creating the target source file. T... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static List<File> findFiles(final File parent, boolean recurse) {
final List<File> result = new ArrayList<File>();
if (parent.isDirectory()) {
File[] files = parent.listFiles();
files = (files != null ? files : new File[0]);
... | #vulnerable code
private static List<File> findFiles(final File parent, boolean recurse) {
final List<File> result = new ArrayList<File>();
if (parent.isDirectory()) {
File[] files = parent.listFiles();
for (File child : files) {
i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception {
Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME);
Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME);
if (r... | #vulnerable code
private Object parseIterable(final StartElement iterableEvent, final SerIterable iterable) throws Exception {
Attribute rowsAttr = iterableEvent.getAttributeByName(ROWS_QNAME);
Attribute columnsAttr = iterableEvent.getAttributeByName(COLS_QNAME);
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static BeanCodeGen createFromArgs(String[] args) {
if (args == null) {
throw new IllegalArgumentException("Arguments must not be null");
}
String indent = " ";
String prefix = "";
boolean recurse = false;
i... | #vulnerable code
public static BeanCodeGen createFromArgs(String[] args) {
if (args == null) {
throw new IllegalArgumentException("Arguments must not be null");
}
String indent = " ";
String prefix = "";
boolean recurse = false;
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void writeElements(final String currentIndent, final SerIterator itemIterator) {
// find converter once for performance, and before checking if key is bean
StringConverter<Object> keyConverter = null;
StringConverter<Object> rowConverter = null... | #vulnerable code
private void writeElements(final String currentIndent, final SerIterator itemIterator) {
// find converter once for performance, and before checking if key is bean
StringConverter<Object> keyConverter = null;
StringConverter<Object> rowConverter ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_global.txt");
gcResource.getLogger().addHandler(... | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
DataReader dataReader = null;
long nextPos = 0;
String chunkOfLastLine = null;
int attemptCo... | #vulnerable code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
in.mark(FOUR_KB);
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.res... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseLong(getAttribut... | #vulnerable code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttr... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException, InterruptedException {
IntData performanceData = new IntData();
for (int i=0; i<10; i++) {
long start = System.currentTimeMillis();
DataReader dataReader = new DataReaderFactory... | #vulnerable code
public static void main(String[] args) throws IOException, InterruptedException {
IntData performanceData = new IntData();
for (int i=0; i<50; i++) {
long start = System.currentTimeMillis();
DataReader dataReader = new DataReaderS... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt");
gcResource.getLogg... | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
In... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException {
event.setType(Type.lookup(getAttributeValue(startElement, "type")));
if (event.getExtendedType() == null) {
LOG.warning("co... | #vulnerable code
private void handleGcStart(XMLEventReader eventReader, StartElement startElement, GCEvent event) throws XMLStreamException {
event.setType(Type.lookup(getAttributeValue(startElement, "type")));
if (event.getExtendedType() == null) {
LOG.warni... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R27_SR1_full_header.txt");
gcResource.getLogg... | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
In... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R28_full_header.txt");
gcResource.getLogger()... | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
In... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean isParseablePhaseEvent(String line) {
Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null;
if (phaseStringMatcher != null && phaseStringMatcher.find()) {
String phaseType = phaseStringMatche... | #vulnerable code
private boolean isParseablePhaseEvent(String line) {
Matcher phaseStringMatcher = line != null ? PATTERN_INCLUDE_STRINGS_PHASE.matcher(line) : null;
if (phaseStringMatcher.find()) {
String phaseType = phaseStringMatcher.group(GROUP_DECORATORS... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_full_header.txt");
gcResource.getLo... | #vulnerable code
@Test
public void testFullHeaderWithAfGcs() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
In... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_global.txt");
gcResource.getLogger().addHandle... | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free"))));
} | #vulnerable code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free"))));
}
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R28_global.txt");
gcResource.getLogger().addHandler(hand... | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
GCResource gcResource = new GCResource("SampleIBMJ9_R26_GAFP1_global.txt");
gcResource.getLogger().addHandle... | #vulnerable code
@Test
public void testSystemGc() throws Exception {
TestLogHandler handler = new TestLogHandler();
handler.setLevel(Level.WARNING);
IMP_LOGGER.addHandler(handler);
DATA_READER_FACTORY_LOGGER.addHandler(handler);
InputStream i... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
DataReader dataReader = null;
long nextPos = 0;
String chunkOfLastLine = null;
int attemptCo... | #vulnerable code
public DataReader getDataReader(InputStream inStream) throws IOException {
BufferedInputStream in = new BufferedInputStream(inStream, FOUR_KB);
in.mark(FOUR_KB);
byte[] buf = new byte[ONE_KB * 3];
int length = in.read(buf);
in.res... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) {
return createListBoxModel(credentialsId);
} | #vulnerable code
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String credentialsId) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
re... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static SonarQubeWebHook get() {
return Jenkins.get().getExtensionList(RootAction.class).get(SonarQubeWebHook.class);
} | #vulnerable code
public static SonarQubeWebHook get() {
return Jenkins.getInstance().getExtensionList(RootAction.class).get(SonarQubeWebHook.class);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
if (!SonarInstallation.isValid(getInstallationName(), listener)) {
return false;
}
ArgumentListBuilder args... | #vulnerable code
private boolean performInternal(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
if (!SonarInstallation.isValid(getInstallationName(), listener)) {
return false;
}
ArgumentListBuilde... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unused")
public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {
return createListBoxModel(webhookSecretId);
} | #vulnerable code
@SuppressWarnings("unused")
public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return new StandardListBoxModel().includeCurrentValue(webhookSecretId);
}
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String getIconFileName() {
PluginWrapper wrapper = Jenkins.getInstanceOrNull().getPluginManager()
.getPlugin(SonarPlugin.class);
return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png";
} | #vulnerable code
@Override
public String getIconFileName() {
PluginWrapper wrapper = Jenkins.getInstance().getPluginManager()
.getPlugin(SonarPlugin.class);
return "/plugin/" + wrapper.getShortName() + "/images/waves_48x48.png";
}
#location 3... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
... | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.ge... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
if (l == null)
return;
t... | #vulnerable code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
this.isKnobTouched[index] = isTouched;... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
... | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.ge... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void sendDisplayData ()
{
if (this.hidDevice == null)
return;
synchronized (this.busySendingDisplay)
{
final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer ();
for (int row = 0; row < 3; r... | #vulnerable code
public void sendDisplayData ()
{
if (this.usbEndpointDisplay == null)
return;
synchronized (this.busySendingDisplay)
{
final ByteBuffer displayBuffer = this.displayBlock.createByteBuffer ();
displayBuffer.... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void execute (final ButtonEvent event)
{
if (event != ButtonEvent.DOWN)
return;
final ViewManager viewManager = this.surface.getViewManager ();
final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank ();
... | #vulnerable code
@Override
public void execute (final ButtonEvent event)
{
if (event != ButtonEvent.DOWN)
return;
final ViewManager viewManager = this.surface.getViewManager ();
final AbstractTrackBankProxy tb = this.model.getCurrentTrackBank... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onGridNote (final int note, final int velocity)
{
if (velocity == 0)
return;
final ICursorDevice cursorDevice = this.model.getCursorDevice ();
final int n = this.surface.getPadGrid ().translateToController (no... | #vulnerable code
@Override
public void onGridNote (final int note, final int velocity)
{
if (velocity == 0)
return;
final ICursorDevice cursorDevice = this.model.getCursorDevice ();
switch (this.surface.getPadGrid ().translateToController (no... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void moveUp ()
{
// There is no device on the track move upwards to the track view
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final View activeView = this.surface.getViewManager ().getActiveView ();
if (!cd.hasSel... | #vulnerable code
protected void moveUp ()
{
// There is no device on the track move upwards to the track view
final CursorDeviceProxy cd = this.model.getCursorDevice ();
if (!cd.hasSelectedDevice ())
{
this.surface.getViewManager ().getAct... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
if (l == null)
return;
t... | #vulnerable code
@Override
public void onValueKnobTouch (final int index, final boolean isTouched)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ChannelData l = cd.getSelectedLayerOrDrumPad ();
this.isKnobTouched[index] = isTouched;... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
if (event == ButtonEvent.UP)
{
final CursorDeviceProxy cd = this.model.getCursorDevice ();
... | #vulnerable code
@Override
public void onFirstRow (final int index, final ButtonEvent event)
{
if (event == ButtonEvent.DOWN)
return;
final CursorDeviceProxy cd = this.model.getCursorDevice ();
final ModeManager modeManager = this.surface.ge... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Artifact chooseBinaryBits() throws MojoExecutionException {
String plat;
String os = System.getProperty("os.name");
getLog().debug("OS = " + os);
// See here for possible values of os.name:
// http://lopica.sourceforge.net/os.h... | #vulnerable code
private Artifact chooseBinaryBits() throws MojoExecutionException {
String plat;
String os = System.getProperty("os.name");
getLog().debug("OS = " + os);
// See here for possible values of os.name:
// http://lopica.sourceforge.ne... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
try {
new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor();
new ProcessBuilder("chmod", "755", work... | #vulnerable code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
Runtime r = Runtime.getRuntime();
try {
r.exec("chmod 755 " + workdir + "/bin/ld").waitFor();
r.exec("... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
try {
new ProcessBuilder("chmod", "755", workdir + "/bin/ld").start().waitFor();
new ProcessBuilder("chmod", "755", work... | #vulnerable code
private void setPermissions(File workdir) {
if (!System.getProperty("os.name").startsWith("Windows")) {
Runtime r = Runtime.getRuntime();
try {
r.exec("chmod 755 " + workdir + "/bin/ld").waitFor();
r.exec("... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static Set<Annotation> parameterAnnotations(Member member) {
Annotation[][] annotations =
member instanceof Method ? ((Method) member).getParameterAnnotations() :
member instanceof Constructor ? ((Constructor) member).getParamet... | #vulnerable code
private static Set<Annotation> parameterAnnotations(Member member) {
Set<Annotation> result = new HashSet<>();
Annotation[][] annotations =
member instanceof Method ? ((Method) member).getParameterAnnotations() :
member in... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxExc... | #vulnerable code
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyn... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded()... | #vulnerable code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUplo... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public long getDownloaded() {
return myTorrentStatistic.getDownloadedBytes();
} | #vulnerable code
public long getDownloaded() {
return this.downloaded;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to {}...", peer);
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) ... | #vulnerable code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to " + peer + "...");
try {
socket.connect(address, 3*1000);
} catch (IOExcep... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
long start = System.nanoTime();
long hashTime = 0L;
MessageDigest md = MessageDigest.getInstance("SHA-1");
InputStream is = new BufferedInputStream(new FileInputStream(source)... | #vulnerable code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
FileInputStream fis = new FileInputStream(source);
StringBuffer pieces = new StringBuffer();
byte[] data = new byte... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) {
checkHashingResultIsNotSet();
filesPaths.add(path);
dataSources.add(new StreamBasedHolderImpl(dataSource, closeAfterBuild));
return this;
} | #vulnerable code
public MetadataBuilder addDataSource(@NotNull InputStream dataSource, String path, boolean closeAfterBuild) {
sources.add(new Source(dataSource, path, closeAfterBuild));
return this;
}
#location 2
#vulner... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(ClientState... | #vulnerable code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(Clien... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded()... | #vulnerable code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUplo... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final Atomic... | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
... | #vulnerable code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final Atomic... | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public long getUploaded() {
return myTorrentStatistic.getUploadedBytes();
} | #vulnerable code
public long getUploaded() {
return this.uploaded;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);... | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(1... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher,
TorrentStatisticProvider torrentStatisticProvider)
throws IOException, NoSuchAlgorithmException {
byte[]... | #vulnerable code
public static SharedTorrent fromFile(File source, File parent, boolean multiThreadHash, boolean seeder, boolean leecher,
TorrentStatisticProvider torrentStatisticProvider)
throws IOException, NoSuchAlgorithmException {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to {}...", peer);
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) ... | #vulnerable code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to " + peer + "...");
try {
socket.connect(address, 3*1000);
} catch (IOExcep... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Torrent load(File torrent, File parent, boolean seeder)
throws IOException, NoSuchAlgorithmException {
FileInputStream fis = null;
try {
fis = new FileInputStream(torrent);
byte[] data = new byte[(int)torrent.length()];
fis.read(data);
return new ... | #vulnerable code
public static Torrent load(File torrent, File parent, boolean seeder)
throws IOException {
FileInputStream fis = new FileInputStream(torrent);
byte[] data = new byte[(int)torrent.length()];
fis.read(data);
fis.close();
return new Torrent(data, parent, seeder);
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}.... | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final Atomic... | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)openConnectionCheckRedirects(url);
in = conn.getInputStream();
} catch (IOExceptio... | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(1... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break;
... | #vulnerable code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
if (this.seeder) {
logger.trace("Skipping validation of {} (seeder mode).", this);
this.valid = true;
return true;
}
logger.trace("Validating {}...", this);
this.vali... | #vulnerable code
public synchronized boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
if (this.seeder) {
logger.trace("Skipping validation of {} (seeder mode).", this);
this.valid = true;
return true;
}
logger.trace("Validating {}...", this);
thi... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start(final InetAddress... bindAddresses) throws IOException {
start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null, new SelectorFactoryImpl());
} | #vulnerable code
public void start(final InetAddress... bindAddresses) throws IOException {
start(bindAddresses, Constants.DEFAULT_ANNOUNCE_INTERVAL_SEC, null);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeder... | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int num... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}.... | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BitSet getCompletedPieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
} | #vulnerable code
public BitSet getCompletedPieces() {
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void run() {
try {
init();
Peer self = peersStorageFactory.getPeersStorage().getSelf();
logger.info("BitTorrent client [{}] started and " +
"listening at {}:{}...",
new Object[]{
... | #vulnerable code
@Override
public void run() {
try {
init();
Peer self = client.peersStorage.getSelf();
logger.info("BitTorrent client [{}] started and " +
"listening at {}:{}...",
new Object[]{
self.getSho... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
... | #vulnerable code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
URL target = null;
try {
HTTPAnnounceRequestMessage request ... | #vulnerable code
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, TorrentInfo torrentInfo) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
URL target = null;
try {
HTTPAnnounceRequestMessage re... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeder... | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int num... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MetadataBuilder addFile(@NotNull File source) {
return addFile(source, source.getName());
} | #vulnerable code
public MetadataBuilder addFile(@NotNull File source) {
sources.add(new Source(source));
return this;
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}.... | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final Atomic... | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final ... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash;
synchronized (torrent) {
torrentHash = torrent.getHexInfoHash();
i... | #vulnerable code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
synchronized (torrent) {
if (piece.isValid()) {
// Make sure the piece is marked as comp... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash = torrent.getHexInfoHash();
if (piece.isValid()) {
// Send a HAVE message... | #vulnerable code
@Override
public void handlePieceCompleted(final SharingPeer peer, Piece piece)
throws IOException {
final SharedTorrent torrent = peer.getTorrent();
final String torrentHash = torrent.getHexInfoHash();
if (piece.isValid()) {
// Send a HAVE m... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException {
if (!torrentContainsManyFiles) {
final BEValue md5Sum = infoTable.get(MD5_SUM);
return Collections.singletonLis... | #vulnerable code
private List<TorrentFile> parseFiles(Map<String, BEValue> infoTable, boolean torrentContainsManyFiles, String name) throws InvalidBEncodingException {
if (!torrentContainsManyFiles) {
final BEValue md5Sum = infoTable.get(MD5_SUM);
return Collections.single... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}.... | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void save(File output) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(output);
fos.write(this.getEncoded());
logger.info("Wrote torrent file {}.", output.getAbsolutePath());
} finally {
if (fos != null) {
fos.close... | #vulnerable code
public void save(File output) throws IOException {
FileOutputStream fos = new FileOutputStream(output);
fos.write(this.getEncoded());
fos.close();
logger.info("Wrote torrent file {}.", output.getAbsolutePath());
}
#location 6
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int numSeeder... | #vulnerable code
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage
final int num... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void cleanUp() {
// temporary ignore until I figure out how to handle this in more robust way.
/*
for (PeerMessage.RequestMessage request : myRequests) {
if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){
send... | #vulnerable code
@Override
public void cleanUp() {
for (PeerMessage.RequestMessage request : myRequests) {
if (System.currentTimeMillis() - request.getSendTime() > MAX_REQUEST_TIMEOUT){
send(request);
request.renew();
}
}
}
... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);... | #vulnerable code
private HTTPTrackerMessage sendAnnounce(final URL url) throws AnnounceException {
HttpURLConnection conn = null;
InputStream in = null;
try {
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(1... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BitSet getAvailablePieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (pi... | #vulnerable code
public BitSet getAvailablePieces() {
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availableP... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void open() throws IOException {
try {
myLock.writeLock().lock();
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}.... | #vulnerable code
public void open() throws IOException {
this.partial = new File(this.target.getAbsolutePath() +
TorrentByteStorage.PARTIAL_FILE_NAME_SUFFIX);
if (this.partial.exists()) {
logger.debug("Partial download found at {}. Continuing...",
this.partial... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, InterruptedException, IOException {
ExecutorService executor = Executors.newFixedThreadPool(
getHashingThreadsCount());
List<Future<String>> results = new LinkedList<Future<String>>();
byt... | #vulnerable code
private static String hashPieces(File source)
throws NoSuchAlgorithmException, IOException {
long start = System.nanoTime();
long hashTime = 0L;
MessageDigest md = MessageDigest.getInstance("SHA-1");
InputStream is = new BufferedInputStream(new FileInputStream(s... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException {
Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent"));
assertEquals("http://localhost:6969/announce", t.getAnnounceList().get(... | #vulnerable code
public void load_torrent_created_by_utorrent() throws IOException, NoSuchAlgorithmException, URISyntaxException {
Torrent t = Torrent.load(new File("src/test/resources/torrents/file1.jar.torrent"));
assertEquals(new URI("http://localhost:6969/announce"), t.getAnno... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir ... | #vulnerable code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downlo... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void process(final String uri, final String hostAddress, RequestHandler requestHandler)
throws IOException {
// Prepare the response headers.
/**
* Parse the query parameters into an announce request message.
*
* We need to rely on our own query pa... | #vulnerable code
public void process(final String uri, final String hostAddress, RequestHandler requestHandler)
throws IOException {
// Prepare the response headers.
/**
* Parse the query parameters into an announce request message.
*
* We need to rely on our own qu... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void removeTorrent(TorrentHash torrentHash) {
logger.info("Stopping seeding " + torrentHash.getHexInfoHash());
final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash());
SharedTorrent torrent = torrent... | #vulnerable code
public void removeTorrent(TorrentHash torrentHash) {
logger.info("Stopping seeding " + torrentHash.getHexInfoHash());
final TorrentsPair torrentsPair = torrentsStorage.removeActiveAndAnnounceableTorrent(torrentHash.getHexInfoHash());
SharedTorrent torrent = t... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initAndRunWorker() throws IOException {
myServerSocketChannel = selector.provider().openServerSocketChannel();
myServerSocketChannel.configureBlocking(false);
for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) {
try {
InetSoc... | #vulnerable code
public void initAndRunWorker() throws IOException {
myServerSocketChannel = selector.provider().openServerSocketChannel();
myServerSocketChannel.configureBlocking(false);
for (int port = PORT_RANGE_START; port < PORT_RANGE_END; port++) {
try {
I... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void handlePeerDisconnected(SharingPeer peer) {
final SharedTorrent peerTorrent = peer.getTorrent();
Peer p = new Peer(peer.getIp(), peer.getPort());
p.setPeerId(peer.getPeerId());
p.setTorrentHash(peer.getHexInfoHash());
PeerUID peerUID =... | #vulnerable code
@Override
public void handlePeerDisconnected(SharingPeer peer) {
final SharedTorrent peerTorrent = peer.getTorrent();
Peer p = new Peer(peer.getIp(), peer.getPort());
p.setPeerId(peer.getPeerId());
p.setTorrentHash(peer.getHexInfoHash());
PeerUID pee... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int read(ByteBuffer buffer, long offset) throws IOException {
try {
myLock.readLock().lock();
int requested = buffer.remaining();
if (offset + requested > this.size) {
throw new IllegalArgumentException("Invalid storage read request!");
... | #vulnerable code
@Override
public int read(ByteBuffer buffer, long offset) throws IOException {
int requested = buffer.remaining();
if (offset + requested > this.size) {
throw new IllegalArgumentException("Invalid storage read request!");
}
int bytes = this.channel.read(buffe... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void unbind(boolean force) {
if (!force) {
// Cancel all outgoing requests, and send a NOT_INTERESTED message to
// the peer.
this.cancelPendingRequests();
this.send(PeerMessage.NotInterestedMessage.craft());
}
PeerExchange exchangeCo... | #vulnerable code
public void unbind(boolean force) {
if (!force) {
// Cancel all outgoing requests, and send a NOT_INTERESTED message to
// the peer.
this.cancelPendingRequests();
this.send(PeerMessage.NotInterestedMessage.craft());
}
PeerExchange exch... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void accept() throws IOException, SocketTimeoutException {
Socket socket = this.socket.accept();
try {
logger.debug("New incoming connection ...");
Handshake hs = this.validateHandshake(socket, null);
this.sendHandshake(socket);
this.fireNewPeerConnectio... | #vulnerable code
private void accept() throws IOException, SocketTimeoutException {
Socket socket = this.socket.accept();
try {
logger.debug("New incoming connection ...");
Handshake hs = this.validateHandshake(socket, null);
this.sendHandshake(socket);
this.fireNewPeerCon... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException {
if (pstrLength == -1) {
ByteBuffer len = ByteBuffer.allocate(1);
int readBytes = -1;
try {
readBytes = socketChannel.read(len);
} catch (IOExce... | #vulnerable code
@Override
public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException {
if (pstrLength == -1) {
ByteBuffer len = ByteBuffer.allocate(1);
int readBytes = -1;
try {
readBytes = socketChannel.read(len);
} catch (... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
connectionManager.offerWrite(new WriteTask... | #vulnerable code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
boolean writeTaskAdded = connectionM... | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void init(String fileName) throws IOException {
List<WxImgCreateTemplateCell> list = new CopyOnWriteArrayList<>();
BufferedReader reader = FileReadUtil.createLineRead(fileName);
String line = reader.readLine();
String[] temps;
w... | #vulnerable code
private void init(String fileName) throws IOException {
cellList.clear();
BufferedReader reader = FileReadUtil.createLineRead(fileName);
String line = reader.readLine();
String[] temps;
while (line != null) {
temps = S... | 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.