output stringlengths 79 30.1k | instruction stringclasses 1
value | input stringlengths 216 28.9k |
|---|---|---|
#fixed code
public ClassLoader compile() {
// 获得classPath
final List<File> classPath = getClassPath();
final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0]));
final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader);
if (sourceCodeMap.isEmpty... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public ClassLoader compile() {
// 获得classPath
final List<File> classPath = getClassPath();
final URL[] urLs = URLUtil.getURLs(classPath.toArray(new File[0]));
final URLClassLoader ucl = URLClassLoader.newInstance(urLs, this.parentClassLoader);
if (sourceCodeMap.i... |
#fixed code
DccManager(PircBotX bot) {
_bot = bot;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
boolean processRequest(String nick, String login, String hostname, String request) {
StringTokenizer tokenizer = new StringTokenizer(request);
tokenizer.nextToken();
String type = tokenizer.nextToken();
String filename = tokenizer.nextToken();
if (type.equals("S... |
#fixed code
protected void handleLine(String line) throws Throwable {
try {
log(line);
// Check for server pings.
if (line.startsWith("PING ")) {
// Respond to the ping and return immediately.
onServerPing(line.substring(5));
return;
}
String sourceNick = "";
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void handleLine(String line) throws Throwable {
try {
log(line);
// Check for server pings.
if (line.startsWith("PING ")) {
// Respond to the ping and return immediately.
onServerPing(line.substring(5));
return;
}
String sourceNick ... |
#fixed code
@Test
public void testStart_WFData() throws Exception {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("process.label", "test");
swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map);
Map<String, Map<String, Object... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testStart_WFData() throws Exception {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("process.label", "test");
swr.bindWorkflowProcesses(new WFDataWorkflowProcess(), map);
Map<String, Map<String, ... |
#fixed code
@Override
public final void clearCache() {
this.cache.clear();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public final void clearCache() {
synchronized (this.cache) {
this.cache.clear();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void testCreateRuntime_Injection() {
BQRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime();
assertArrayEquals(new String[]{"-x"}, runtime.getArgs());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testCreateRuntime_Injection() {
BQTestRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime();
assertArrayEquals(new String[]{"-x"}, runtime.getRuntime().getArgs());
}
#location 4
... |
#fixed code
protected MetricData getRollupByGranularity(
String tenantId,
String metricName,
long from,
long to,
Granularity g) {
final Timer.Context ctx = metricsFetchTimer.time();
final Locator locator = Locat... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected MetricData getRollupByGranularity(
String tenantId,
String metricName,
long from,
long to,
Granularity g) {
final Timer.Context ctx = metricsFetchTimer.time();
final Locator locator =... |
#fixed code
public static void main(String[] args) {
if (args.length != 5){
System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE");
System.exit(1);
}
St... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) {
if (args.length != 5){
System.err.println("Usage: java " + AFLRedundancyDriver.class + " TEST_CLASS TEST_METHOD TEST_INPUT_FILE AFL_TO_JAVA_PIPE JAVA_TO_AFL_PIPE");
System.exit(1);
}
... |
#fixed code
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) msg;
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new Default... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) msg;
if (HttpUtil.is100ContinueExpected(req)) {
ctx.write(new D... |
#fixed code
public Object intercept(Invocation invocation) throws Throwable {
if (autoRuntimeDialect) {
SqlUtil sqlUtil = getSqlUtil(invocation);
return sqlUtil.processPage(invocation);
} else {
if (autoDialect) {
initSq... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Object intercept(Invocation invocation) throws Throwable {
SqlUtil sqlUtil;
if (autoRuntimeDialect) {
sqlUtil = getSqlUtil(invocation);
} else {
if (autoDialect) {
initSqlUtil(invocation);
... |
#fixed code
private Long getRequestStartTime() {
final RequestContext ctx = RequestContext.getCurrentContext();
final HttpServletRequest request = ctx.getRequest();
return (Long) request.getAttribute(REQUEST_START_TIME);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Long getRequestStartTime() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return (Long) requestAttributes.getAttribute(REQUEST_START_TIME, SCOPE_REQUEST);
}
#location 3
... |
#fixed code
DictionaryBuilder() {
buffer = ByteBuffer.allocate(BUFFER_SIZE);
buffer.order(ByteOrder.LITTLE_ENDIAN);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
void buildLexicon(String filename, FileInputStream lexiconInput) throws IOException {
int lineno = -1;
try (InputStreamReader isr = new InputStreamReader(lexiconInput);
LineNumberReader reader = new LineNumberReader(isr)) {
fo... |
#fixed code
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel
selector.wakeup();
try {
if( removeConnection( conn ) ) {
onClose( conn, code,... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel
selector.wakeup();
try {
synchronized ( connections ) {
if( this.connect... |
#fixed code
public int getConnectionLostTimeout() {
synchronized (syncConnectionLost) {
return connectionLostTimeout;
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public int getConnectionLostTimeout() {
return connectionLostTimeout;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catc... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onEr... |
#fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
retu... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
... |
#fixed code
@Test
public void testFindFontFor() {
assertNotNull(findFontFor("ทดสอบ")); // thai
assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek
assertNotNull(findFontFor("വീട്")); // malayalam
assertNotNull(findFontFor("मानक")); // hindi
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testFindFontFor() {
assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName());
assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName());
assertNull(findFontFor(new PDDocum... |
#fixed code
@Test
public void testCanDisplayThai() {
assertThat(findFontFor("นี่คือการทดสอบ"), is(notNullValue()));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testCanDisplayThai() {
PDFont noto = FontUtils.loadFont(new PDDocument(), UnicodeType0Font.NOTO_SANS_THAI_REGULAR);
assertThat(FontUtils.canDisplay("นี่คือการทดสอบ", noto), is(true));
}
#location 3
... |
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but ... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
if (Lizzie.leelaz.isKataGo) {... |
#fixed code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
try
{
// add SGF header
StringBuilder builde... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Li... |
#fixed code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true));
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true));
}
... |
#fixed code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClus... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: ... |
#fixed code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
ZookeeperRegistryCenter shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfigu... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZ... |
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("... |
#fixed code
@Test
public void testConnectResolve() throws IOException
{
int port = Utils.findOpenPort();
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of s... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testConnectResolve()
{
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of socket, each with high watermark of 2. Thus the total
... |
#fixed code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 20;
ExecutorService service = Executors.new... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 10;
ExecutorService service = Executo... |
#fixed code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (InputStreamReader in = new InputStreamReader(new FileInputStream(file))) {
Map<... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
... |
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Obj... |
#fixed code
protected void beginTransaction() {
transactionalListener.beginTransaction();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void beginTransaction() {
if (listener != null) {
listener.beginTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + server... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + ... |
#fixed code
protected void endTransaction() {
transactionalListener.endTransaction();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void endTransaction() {
if (listener != null) {
listener.endTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
VariableDeclarationFragment tempFrag = (VariableDeclara... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
FieldDeclaration internal = (FieldDeclaration) te... |
#fixed code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
int read;
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, "UTF-8");
int read;
do
... |
#fixed code
public static void beginRequest(HttpServletRequest request) {
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void beginRequest(HttpServletRequest request) {
ManagerImpl manager = (ManagerImpl) JNDI.lookup("manager");
SessionContext sessionContext = (SessionContext) manager.getContext(SessionScoped.class);
BeanMap sessionBeans = (BeanMap) request.... |
#fixed code
private View getViewOnListLine(AbsListView absListView, int lineIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = absListView.getChildAt(lineIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMillis() ... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private View getViewOnListLine(AbsListView absListView, int lineIndex){
final long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
View view = absListView.getChildAt(lineIndex);
while(view == null){
final boolean timedOut = SystemClock.uptimeMil... |
#fixed code
private static void init() {
try {
LOGGER.info("Load "+PATH_FILE);
InputStream input=GoKeyRule.class.getResourceAsStream(PATH_FILE);
if(input==null){
throw new FileNotFoundException(PATH_FILE);
}
prop.load(input);
} catch (IOException e)... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private static void init() {
try {
prop.load(new FileInputStream(new File(PATH_FILE)));
} catch (FileNotFoundException e) {
LOGGER.error("Unable to load the config file", e);
} catch (IOException e) {
LOGGER.error("Unable to load the config file", e);
}
}... |
#fixed code
@Override
public RulesProfile createProfile(ValidationMessages validation) {
LOGGER.info("Golint Quality profile");
RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY);
profile.setDefaultProfile(Boolean.TRUE);
Properties prop=new Properties(... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public RulesProfile createProfile(ValidationMessages validation) {
LOGGER.info("Golint Quality profile");
RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY);
profile.setDefaultProfile(Boolean.TRUE);
Properties prop=new Prope... |
#fixed code
@Test
public void testByte() throws Exception {
assertArrayEquals(new byte[]{-34}, BeginBin().Byte(-34).End().toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testByte() throws Exception {
assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(1, 3, 0, 7).End().toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testBitArrayAsInts() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray());
}
... |
#fixed code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
this.byt... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
re... |
#fixed code
@Test
public void testComplexWriting_1() throws Exception {
final byte [] array =
BeginBin().
Bit(1, 2, 3, 0).
Bit(true, false, true).
Align().
Byte(5).
Short(1, 2, 3, 4, 5).
Bool(true, fal... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testComplexWriting_1() throws Exception {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384);
final JBBPOut begin = new JBBPOut(buffer);
begin.
Bit(1, 2, 3, 0).
Bit(true, false, true).
... |
#fixed code
@Test
public void testAlign() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align().Byte(0xFF).End().toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testAlign() throws Exception {
assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).End().toByteArray());
}
#location 3
... |
#fixed code
@Test
public void testLong_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).End().toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testLong_BigEndian() throws Exception {
assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray());
}
#lo... |
#fixed code
public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException {
return _readArray(items, bitNumber);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException {
int pos = 0;
if (items < 0) {
byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE];
// till end
while (true) {
final int next = readBits(bitNu... |
#fixed code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(true, true, false, false, false, true, true, true).End().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(true, true, false... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testBitArrayAsBooleans() throws Exception {
assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray());
assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true,... |
#fixed code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
this.byt... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException {
int result;
final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber();
if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) {
result = this.readByteFromStream();
re... |
#fixed code
@Test
public void testShortArray_AsIntegers() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, BeginBin().Short(0x0102,0x0304).End().toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testShortArray_AsIntegers() throws Exception {
assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray());
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
public void debugHeader() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.printl... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void debugHeader() {
if (!traceDebugEnabled) {
return;
}
System.out.println("---------------- Trace Information ---------------");
String traceId = getTraceId();
String spanId = getSpanId();
System.out.... |
#fixed code
@Before
@SuppressWarnings({ "unchecked", "deprecation" })
public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{
driver = new MockJDBCDriver(new MockJDBCAnswer() {
p... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Before
@SuppressWarnings({ "unchecked", "deprecation" })
public void before() throws IllegalArgumentException, IllegalAccessException, SQLException, SecurityException, NoSuchFieldException, CloneNotSupportedException{
mockConfig = EasyMock.createNiceMock(BoneCPConfig.... |
#fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocum... |
#fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) ... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : r... |
#fixed code
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false)
public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer,
final ClassLoader loader) throws IllegalClassFormatException, IOExcepti... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false)
public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer,
final ClassLoader loader) throws IllegalClassFormatException, IOE... |
#fixed code
public static void configureLog(Properties properties) {
for (String property : properties.stringPropertyNames()) {
if (property.startsWith(LOGGER_PREFIX)) {
String classPrefix = getClassPrefix(property);
AgentLogger.Level l... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void configureLog(Properties properties) {
for (String property : properties.stringPropertyNames()) {
if (property.startsWith(LOGGER_PREFIX)) {
String classPrefix = getClassPrefix(property);
AgentLogger.L... |
#fixed code
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
try {
Class entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.En... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
EntityManagerFactoryRegistry.INSTANCE.removeEntityManagerFactory(persistenceUnitName, currentI... |
#fixed code
public void handleError(Session s, Throwable exception) {
doSaveExecution(s, session -> {
members.unregister(session.getId());
eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage()));
}
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void handleError(Session s, Throwable exception) {
doSaveExecution(new SessionWrapper(s), session -> {
members.unregister(session.getId());
eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage()... |
#fixed code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSess... |
#fixed code
private void parseProperties(Properties properties) {
for (Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
String value = (String) entry.getValue();
String[] strs = StringUtils.split(value, ',');
switch (strs.length) ... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void parseProperties(Properties properties) {
for (Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
String value = (String) entry.getValue();
// System.out.println(name + "|" + value);
String[] strs = Strin... |
#fixed code
@Test
public void testWindowUpdate() throws Throwable {
MockSession clientSession = new MockSession();
MockSession serverSession = new MockSession();
SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true));
SpdySessionA... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testWindowUpdate() throws Throwable {
MockSession clientSession = new MockSession();
MockSession serverSession = new MockSession();
SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true));
SpdySe... |
#fixed code
@Test
public void testNestedClass() throws Exception {
Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef);
FieldGenericTypeBind barMaps = map.get("maps");
ParameterizedType parameterizedType = (ParameterizedType) bar... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testNestedClass() throws Exception {
Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(
new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() {
... |
#fixed code
public static void main(String[] args) throws Throwable{
Certificate[] certificates = getCertificates("fireflySSLkeys.jks", "fireflySSLkeys");
for(Certificate certificate : certificates) {
System.out.println(certificate);
}
certificates = getCertificates("fireflykeys"... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) throws Throwable {
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(new File("/Users/qiupengtao", "fireflykeys"));
out = new ByteArrayOutputStream();
byte[] buf = new byte[... |
#fixed code
public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder)
throws IOException {
try (FileInputStream fis = new FileInputStream(file);) {
final FileChannel channel = fis.getChannel();
final long oneGB = 1024 * 1024 * 1024;
MappedByteBuffer buffer... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static Word2VecModel fromBinFile(File file, ByteOrder byteOrder)
throws IOException {
try (FileInputStream fis = new FileInputStream(file);) {
DataInput in = (byteOrder == ByteOrder.BIG_ENDIAN) ?
new DataInputStream(fis) : new SwappedData... |
#fixed code
@Override
public Flux<Payload> requestStream(Payload payload) {
RSocket service = findRSocket(payload);
return service.requestStream(payload);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Flux<Payload> requestStream(Payload payload) {
List<String> metadata = getRoutingMetadata(payload);
RSocket service = findRSocket(metadata);
if (service != null) {
return service.requestStream(payload);
}
MonoProcessor<RSocket> processor = ... |
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
// Clear array content
directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0);
primitiveArray = (A) directMemoryService.getObject(arrayStartAddress);
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset... |
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset... |
#fixed code
@Test
public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() {
ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool =
offHeapService.createOffHeapPool(
new DefaultExtendableObjectOffHeapPoolCreateParamete... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() {
ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool =
offHeapService.createOffHeapPool(
new DefaultExtendableObjectOffHeapPoolCreatePa... |
#fixed code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
// Allocated objects must start aligned as address size from start address of allocated address
long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
i... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
objectsEndAddress = allocationEndAddress;
currentAddress = allocationStartAddress - objectSize;
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySi... |
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemo... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, dire... |
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(c... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexS... |
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType);
// All index in object pool array head... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayB... |
#fixed code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentSegmentIndex = INDEX_NOT_YET_USED;
currentSegmentBlockIndex = INDEX_NOT_YET_USED;
directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0);
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentIndex = INDEX_NOT_YET_USED;
currentBlockIndex = INDEX_NOT_YET_USED;
directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0);
}
... |
#fixed code
private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException {
Block bestBlock = this.blockService.getBestBlock();
List<Transaction> allTxList = txCacheManager.getTxList();
allTxList.sort(TxTimeComparator.get... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException {
Block bestBlock = this.blockService.getBestBlock();
List<Transaction> allTxList = txCacheManager.getTxList();
allTxList.sort(TxTimeComparat... |
#fixed code
public boolean createQueue(String queueName, long maxSize, int latelySecond) {
try {
NulsFQueue queue = new NulsFQueue(queueName, maxSize);
QueueManager.initQueue(queueName, queue, latelySecond);
return true;
} catch (Except... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean createQueue(String queueName, long maxSize, int latelySecond) {
try {
InchainFQueue queue = new InchainFQueue(queueName, maxSize);
QueueManager.initQueue(queueName, queue, latelySecond);
return true;
} c... |
#fixed code
@Test
public void getMemoryTxs() throws Exception {
assertNotNull(service);
Transaction tx = new TestTransaction();
tx.setTime(0l);
assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void getMemoryTxs() throws Exception {
assertNotNull(service);
Transaction tx = new TestTransaction();
tx.setTime(0l);
assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c... |
#fixed code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\nchain:... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\n... |
#fixed code
boolean verifyPublicKey(){
//verify the public-KEY-hashes are the same
byte[] publicKey = scriptSig.getPublicKey();
byte[] reedmAccount = Utils.sha256hash160(Utils.sha256hash160(publicKey));
if(Arrays.equals(reedmAccount,script.getPublicKeyDig... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
boolean verifyPublicKey(){
//verify the public-KEY-hashes are the same
byte[] publicKey = scriptSig.getPublicKey();
NulsDigestData digestData = NulsDigestData.calcDigestData(publicKey,NulsDigestData.DIGEST_ALG_SHA160);
if(Arrays.equals(d... |
#fixed code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
Li... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
... |
#fixed code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayLi... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new A... |
#fixed code
public PocMeetingRound getCurrentRound() {
return currentRound;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public PocMeetingRound getCurrentRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound round = ROUND_MAP.get(currentRou... |
#fixed code
public void reset() {
lock.lock();try{
this.needReSet = true;
ROUND_MAP.clear();
this.init();}finally {
lock.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void reset() {
this.needReSet = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public Result saveLocalTx(Transaction tx) {
if (tx == null) {
return Result.getFailed(KernelErrorCode.NULL_PARAMETER);
}
byte[] txHashBytes = new byte[0];
try {
txHashBytes = tx.getHash().serialize();
} catch (IO... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Result saveLocalTx(Transaction tx) {
if (tx == null) {
return Result.getFailed(KernelErrorCode.NULL_PARAMETER);
}
byte[] txHashBytes = new byte[0];
try {
txHashBytes = tx.getHash().serialize();
} cat... |
#fixed code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("The ad... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("... |
#fixed code
@Override
public Result<Balance> getBalance(byte[] address) throws NulsException {
if (address == null || address.length != AddressTool.HASH_LENGTH) {
return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR);
}
if (!isLocalAccou... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Result<Balance> getBalance(byte[] address) throws NulsException {
if (address == null || address.length != AddressTool.HASH_LENGTH) {
return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR);
}
if (!isLoca... |
#fixed code
@Override
public void init() {
cacheService = LedgerCacheService.getInstance();
registerService();
ledgerService = NulsContext.getServiceBean(LedgerService.class);
coinManager = UtxoCoinManager.getInstance();
UtxoOutputDataService o... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void init() {
cacheService = LedgerCacheService.getInstance();
registerService();
ledgerService = NulsContext.getServiceBean(LedgerService.class);
coinManager = UtxoCoinManager.getInstance();
UtxoOutputDataSer... |
#fixed code
@Override
public void init(Map<String, String> initParams) {
String databaseType = null;
if(initParams.get("databaseType") != null) {
databaseType = initParams.get("databaseType");
}
if (!StringUtils.isEmpty(databaseType) && has... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void init(Map<String, String> initParams) {
String dataBaseType = null;
if(initParams.get("dataBaseType") != null) {
dataBaseType = initParams.get("dataBaseType");
}
if (!StringUtils.isEmpty(dataBaseType) ... |
#fixed code
public void forcedLog(String fqcn, Priority level, Object message, Throwable t) {
org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString());
Message msg = message instanceof Message ? (ObjectMessage) message : new ObjectMess... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void forcedLog(String fqcn, Priority level, Object message, Throwable t) {
org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString());
logger.log(null, fqcn, lvl, new ObjectMessage(message), t);
}
... |
#fixed code
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: refactor PluginManager.decode() into this module?
pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>();
final Enumeration<URL> resources = Pl... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: refactor PluginManager.decode() into this module?
pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>();
final Enumeration<URL> resource... |
#fixed code
static void reportResult(final String file, final String name, final Histogram histogram)
throws IOException {
final String result = createSamplingReport(name, histogram);
println(result);
if (file != null) {
final FileWriter w... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
static void reportResult(final String file, final String name, final Histogram histogram)
throws IOException {
final String result = createSamplingReport(name, histogram);
println(result);
if (file != null) {
final FileWr... |
#fixed code
@Override
protected void releaseSub() {
if (rpcClient != null) {
try {
rpcClient.close();
} catch (final Exception ex) {
LOGGER.error("Attempt to close RPC client failed", ex);
}
}
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void releaseSub() {
if (transceiver != null) {
try {
transceiver.close();
} catch (final IOException ioe) {
LOGGER.error("Attempt to clean up Avro transceiver failed", ioe);
... |
#fixed code
public byte[] toByteArray(final LogEvent event) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new PrivateObjectOutputStream(baos);
try {
oos.writeObject(event);
} ... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public byte[] toByteArray(final LogEvent event) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new PrivateObjectOutputStream(baos);
oos.writeObject(event);
} catch (IOException i... |
#fixed code
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
final long timestamp = event.getTimeMillis();
toAppendTo.append(timestamp - startTime);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
final long timestamp = event.getTimeMillis();
synchronized (this) {
if (timestamp != lastTimestamp) {
lastTimestamp = timestamp;
... |
#fixed code
protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) {
try {
final URL url = new URL(config);
return new ConfigurationSource(url.openStream(), FileUtils.fileFromUri(url.toURI()));
} catch (fina... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) {
try {
final URL url = new URL(config);
return new ConfigurationSource(url.openStream(), FileUtils.fileFromURI(url.toURI()));
} catch... |
#fixed code
@Test
public void testTcpAppenderDeadlock() throws Exception {
// @formatter:off
final SocketAppender appender = SocketAppender.newBuilder()
.withHost("localhost")
.withPort(DYN_PORT)
.withReconnectDelayMill... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testTcpAppenderDeadlock() throws Exception {
// @formatter:off
final SocketAppender appender = SocketAppender.newBuilder()
.withHost("localhost")
.withPort(DYN_PORT)
.withReconnectDel... |
#fixed code
@Test
public void testAppender() throws Exception {
final Logger logger = ctx.getLogger();
// Trigger the rollover
for (int i = 0; i < 10; ++i) {
// 30 chars per message: each message triggers a rollover
logger.debug("This i... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testAppender() throws Exception {
final Logger logger = ctx.getLogger();
// Trigger the rollover
for (int i = 0; i < 10; ++i) {
// 30 chars per message: each message triggers a rollover
logger.debug("... |
#fixed code
@Override
public void format(final LogEvent event, final StringBuilder output) {
final long timestamp = event.getMillis();
synchronized (this) {
if (timestamp != lastTimestamp) {
lastTimestamp = timestamp;
cache... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void format(final LogEvent event, final StringBuilder output) {
final long timestamp = event.getMillis();
synchronized (this) {
if (timestamp != lastTimestamp) {
lastTimestamp = timestamp;
... |
#fixed code
public static String[] readFile(String file) {
List<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static String[] readFile(String file) {
List<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileIn... |
#fixed code
public static String[] readFile(String file) {
List<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static String[] readFile(String file) {
List<String> result = new ArrayList<String>();
System.out.println("readFile(" + file + ")");
try {
BufferedReader inr = new BufferedReader(new InputStreamReader(new FileIn... |
#fixed code
private void commonInitialization(IntVar[] list, int[] weights, int sum) {
queueIndex = 4;
assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom";
numberArgs = (short) (list.length + 1);
numberId = idNu... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void commonInitialization(IntVar[] list, int[] weights, int sum) {
queueIndex = 4;
assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom";
numberArgs = (short) (list.length + 1);
numberId ... |
#fixed code
@Test
public void testLocking() {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000 * 1000;
new Thread(new Runnable() {
@Override
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testLocking() throws Exception {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000000;
Thread t = new Thread(new Runnable() {... |
#fixed code
@Test
public void testLocking() throws Exception {
// a page
long start = System.nanoTime();
final DirectStore store1 = DirectStore.allocate(1 << 12);
final int lockCount = 20 * 1000000;
Thread t = new Thread(new Runnable() {
... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testLocking() throws Exception {
// a page
final DirectStore store1 = DirectStore.allocate(1 << 12);
final DirectStore store2 = DirectStore.allocate(1 << 12);
final int lockCount = 10 * 1000000;
Thread t = n... |
#fixed code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.bytes();
slice.po... | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testAllocate() throws Exception {
long size = 1L << 24; // 31; don't overload cloud-bees
DirectStore store = DirectStore.allocate(size);
assertEquals(size, store.size());
DirectBytes slice = store.createSlice();
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.