output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public static void main(String[] args) {
log.info("Starting DragonProxy...");
// Check the java version
if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) {
log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version"));
return;
}
// Define command-line options
OptionParser optionParser = new OptionParser();
optionParser.accepts("version", "Displays the proxy version");
OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg();
OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg();
optionParser.accepts("help", "Display help/usage information").forHelp();
// Handle command-line options
OptionSet options = optionParser.parse(args);
if (options.has("version")) {
log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion());
return;
}
int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
DragonProxy proxy = new DragonProxy(bedrockPort, javaPort);
Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread"));
} | #vulnerable code
public static void main(String[] args) {
log.info("Starting DragonProxy...");
// Check the java version
if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) {
log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version"));
return;
}
// Define command-line options
OptionParser optionParser = new OptionParser();
optionParser.accepts("version", "Displays the proxy version");
OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg();
OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg();
optionParser.accepts("help", "Display help/usage information").forHelp();
// Handle command-line options
OptionSet options = optionParser.parse(args);
if (options.has("version")) {
log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion());
return;
}
int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
long startTime = System.currentTimeMillis();
DragonProxy proxy = new DragonProxy(bedrockPort, javaPort);
Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread"));
double bootTime = (System.currentTimeMillis() - startTime) / 1000d;
log.info("Done ({}s)!", new DecimalFormat("#.##").format(bootTime));
proxy.getConsole().start();
}
#location 35
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void initialize() throws Exception {
if(!RELEASE) {
logger.warn("This is a development build. It may contain bugs. Do not use in production.");
}
// Create injector, provide elements from the environment and register providers
// TODO: Remove
injector = new InjectorBuilder()
.addDefaultHandlers("org.dragonet.proxy")
.create();
injector.register(DragonProxy.class, this);
injector.register(Logger.class, logger);
injector.provide(ProxyFolder.class, getFolder());
// Initiate console
console = injector.getSingleton(DragonConsole.class);
// Load configuration
try {
if(!Files.exists(Paths.get("config.yml"))) {
Files.copy(getClass().getResourceAsStream("/config.yml"), Paths.get("config.yml"), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
logger.error("Failed to copy config file: " + ex.getMessage());
}
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
configuration = mapper.readValue(new FileInputStream("config.yml"), DragonConfiguration.class);
generalThreadPool = Executors.newScheduledThreadPool(configuration.getThreadPoolSize());
paletteManager = new PaletteManager();
pingPassthroughThread = new PingPassthroughThread(this);
if(configuration.isPingPassthrough()) {
generalThreadPool.scheduleAtFixedRate(pingPassthroughThread, 1, 1, TimeUnit.SECONDS);
logger.info("Ping passthrough enabled");
}
BedrockServer server = new BedrockServer(new InetSocketAddress(configuration.getBindAddress(), configuration.getBindPort()));
server.setHandler(new ProxyServerEventListener(this));
server.bind().whenComplete((aVoid, throwable) -> {
if (throwable == null) {
logger.info("RakNet server started on {}", configuration.getBindAddress());
} else {
logger.error("RakNet server failed to bind to {}, {}", configuration.getBindAddress(), throwable.getMessage());
}
}).join();
} | #vulnerable code
private void initialize() throws Exception {
if(!RELEASE) {
logger.warn("This is a development build. It may contain bugs. Do not use in production.");
}
// Create injector, provide elements from the environment and register providers
// TODO: Remove
injector = new InjectorBuilder()
.addDefaultHandlers("org.dragonet.proxy")
.create();
injector.register(DragonProxy.class, this);
injector.register(Logger.class, logger);
injector.provide(ProxyFolder.class, getFolder());
// Initiate console
console = injector.getSingleton(DragonConsole.class);
// Load configuration
// TODO: Tidy this up
File fileConfig = new File("config.yml");
if (!fileConfig.exists()) {
// Create default config
FileOutputStream fos = new FileOutputStream(fileConfig);
InputStream ins = DragonProxy.class.getResourceAsStream("/config.yml");
int data;
while ((data = ins.read()) != -1) {
fos.write(data);
}
ins.close();
fos.close();
}
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
configuration = mapper.readValue(new FileInputStream(fileConfig), DragonConfiguration.class);
generalThreadPool = Executors.newScheduledThreadPool(configuration.getThreadPoolSize());
paletteManager = new PaletteManager();
pingPassthroughThread = new PingPassthroughThread(this);
if(configuration.isPingPassthrough()) {
generalThreadPool.scheduleAtFixedRate(pingPassthroughThread, 1, 1, TimeUnit.SECONDS);
logger.info("Ping passthrough enabled");
}
BedrockServer server = new BedrockServer(new InetSocketAddress(configuration.getBindAddress(), configuration.getBindPort()));
server.setHandler(new ProxyServerEventListener(this));
server.bind().whenComplete((aVoid, throwable) -> {
if (throwable == null) {
logger.info("RakNet server started on {}", configuration.getBindAddress());
} else {
logger.error("RakNet server failed to bind to {}, {}", configuration.getBindAddress(), throwable.getMessage());
}
}).join();
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String... args) throws InterruptedException {
// Manually grok the command argument in order to conditionally apply different options.
if (args.length < 1) {
System.err.println("Missing command argument.");
printCmdUsage(System.err);
System.exit(1);
}
Config.Command command = null;
try {
command = Config.Command.valueOf(args[0].toUpperCase());
}
catch (IllegalArgumentException ex) {
System.err.println("Unknown command: " + args[0]);
printCmdUsage(System.err);
System.exit(1);
}
Config config;
Dispatcher dispatcher;
switch (command) {
case INSERT:
config = new InsertConfig();
parseArguments(config, args);
dispatcher = new InsertDispatcher((InsertConfig) config);
break;
case SELECT:
config = new SelectConfig();
parseArguments(config, args);
dispatcher = new SelectDispatcher((SelectConfig) config);
break;
default:
throw new RuntimeException("Unknown command enum; Report as bug!!");
}
dispatcher.go();
dispatcher.printReport();
System.exit(0);
} | #vulnerable code
public static void main(String... args) throws InterruptedException {
Config config = getConfig(args);
Dispatcher dispatcher;
switch (config.getCommand()) {
case INSERT:
dispatcher = new InsertDispatcher(config);
break;
case SELECT:
dispatcher = new SelectDispatcher(config);
break;
default:
throw new RuntimeException("Unknown command enum; Report as bug!!");
}
dispatcher.go();
dispatcher.printReport();
System.exit(0);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Row<Measurement> next() {
if (!hasNext()) throw new NoSuchElementException();
Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource);
while (m_current != null) {
accumulate(m_current, output.getTimestamp());
if (m_current.getTimestamp().gte(output.getTimestamp())) {
break;
}
if (m_input.hasNext()) {
m_current = m_input.next();
}
else m_current = null;
}
// Go time; We've accumulated enough to produce the output row
for (String name : m_metrics) {
Accumulation accumulation = m_accumulation.get(name);
// Add sample with accumulated value to output row
output.addElement(new Measurement(
output.getTimestamp(),
output.getResource(),
name,
accumulation.average()));
// If input is greater than row, accumulate remainder for next row
if (m_current != null) {
accumulation.reset();
Sample sample = m_current.getElement(name);
if (sample == null) {
continue;
}
if (m_current.getTimestamp().gt(output.getTimestamp())) {
Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp());
if (elapsed.lt(getHeartbeat(name))) {
accumulation.known = elapsed.asMillis();
accumulation.value = sample.getValue().times(elapsed.asMillis());
}
else {
accumulation.unknown = elapsed.asMillis();
}
}
}
}
return output;
} | #vulnerable code
@Override
public Row<Measurement> next() {
if (!hasNext()) throw new NoSuchElementException();
Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource);
while (m_current != null) {
accumulate(m_current, output.getTimestamp());
if (m_current.getTimestamp().gte(output.getTimestamp())) {
break;
}
if (m_input.hasNext()) {
m_current = m_input.next();
}
else m_current = null;
}
// Go time; We've accumulated enough to produce the output row
for (String name : m_metrics) {
Accumulation accumulation = m_accumulation.get(name);
// Add sample with accumulated value to output row
output.addElement(new Measurement(
output.getTimestamp(),
output.getResource(),
name,
accumulation.average().doubleValue()));
// If input is greater than row, accumulate remainder for next row
if (m_current != null) {
accumulation.reset();
Sample sample = m_current.getElement(name);
if (sample == null) {
continue;
}
if (m_current.getTimestamp().gt(output.getTimestamp())) {
Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp());
if (elapsed.lt(getHeartbeat(name))) {
accumulation.known = elapsed.asMillis();
accumulation.value = sample.getValue().times(elapsed.asMillis());
}
else {
accumulation.unknown = elapsed.asMillis();
}
}
}
}
return output;
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private int go(String[] args) {
m_parser.setUsageWidth(80);
try {
m_parser.parseArgument(args);
}
catch (CmdLineException e) {
System.err.println(e.getMessage());
printUsage(System.err);
return 1;
}
if (m_needsHelp) {
printUsage(System.out);
return 0;
}
if (m_resource == null || m_metric == null) {
System.err.println("Missing required argument(s)");
printUsage(System.err);
return 1;
}
System.out.printf("timestamp,%s%n", m_metric);
for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) {
System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue().doubleValue());
}
return 0;
} | #vulnerable code
private int go(String[] args) {
m_parser.setUsageWidth(80);
try {
m_parser.parseArgument(args);
}
catch (CmdLineException e) {
System.err.println(e.getMessage());
printUsage(System.err);
return 1;
}
if (m_needsHelp) {
printUsage(System.out);
return 0;
}
if (m_resource == null || m_metric == null) {
System.err.println("Missing required argument(s)");
printUsage(System.err);
return 1;
}
System.out.printf("timestamp,%s%n", m_metric);
for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) {
System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue());
}
return 0;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object doGenerate(final Class<?> type) {
PojoClass pojoClass = PojoClassFactory.getPojoClass(type);
Enum<?>[] values = getValues(pojoClass);
if (values == null) {
throw RandomGeneratorException.getInstance(MessageFormatter.format("Failed to enumerate possible values of Enum [{0}]", type));
}
return values[RANDOM.nextInt(values.length)];
} | #vulnerable code
public Object doGenerate(final Class<?> type) {
PojoClass pojoClass = PojoClassFactory.getPojoClass(type);
PojoMethod valuesPojoMethod = null;
for (PojoMethod pojoMethod : pojoClass.getPojoMethods()) {
if (pojoMethod.getName().equals("values")) {
valuesPojoMethod = pojoMethod;
break;
}
}
Enum<?>[] values = (Enum<?>[]) valuesPojoMethod.invoke(null, (Object[]) null);
return values[RANDOM.nextInt(values.length)];
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object doGenerate(Parameterizable parameterizedType) {
return CollectionHelper.buildCollections((Collection) doGenerate(parameterizedType.getType()), parameterizedType.getParameterTypes()
.get(0));
} | #vulnerable code
public Object doGenerate(Parameterizable parameterizedType) {
List returnedList = (List) RandomFactory.getRandomValue(parameterizedType.getType());
returnedList.clear();
CollectionHelper.buildCollections(returnedList, parameterizedType.getParameterTypes().get(0));
return returnedList;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<PojoPackage> getPojoSubPackages() {
List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>();
List<File> paths = PackageHelper.getPackageDirectories(packageName);
for (File path : paths) {
for (File entry : path.listFiles()) {
if (entry.isDirectory()) {
String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName();
pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName));
}
}
}
return pojoPackageSubPackages;
} | #vulnerable code
public List<PojoPackage> getPojoSubPackages() {
List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>();
File directory = PackageHelper.getPackageAsDirectory(packageName);
for (File entry : directory.listFiles()) {
if (entry.isDirectory()) {
String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName();
pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName));
}
}
return pojoPackageSubPackages;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(expected = ReflectionException.class)
public void shouldFailSetter() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType()));
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailSetter() {
PojoField pojoField = getPrivateStringField();
pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType()));
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object doGenerate(Parameterizable parameterizedType) {
Queue returnedQueue = (Queue) RandomFactory.getRandomValue(parameterizedType.getType());
CollectionHelper.buildCollections(returnedQueue, parameterizedType.getParameterTypes().get(0));
return returnedQueue;
} | #vulnerable code
public Object doGenerate(Parameterizable parameterizedType) {
Queue returnedQueue = (Queue) RandomFactory.getRandomValue(parameterizedType.getType());
returnedQueue.clear();
CollectionHelper.buildCollections(returnedQueue, parameterizedType.getParameterTypes().get(0));
return returnedQueue;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run(final PojoClass pojoClass) {
Object instance1 = ValidationHelper.getMostCompleteInstance(pojoClass);
Object instance2 = ValidationHelper.getMostCompleteInstance(pojoClass);
IdentityHandlerStub identityHandlerStub = new IdentityHandlerStub(instance1, instance2);
IdentityFactory.registerIdentityHandler(identityHandlerStub);
// check one way
identityHandlerStub.areEqualReturn = RandomFactory.getRandomValue(Boolean.class);
checkEquality(instance1, instance2, identityHandlerStub);
identityHandlerStub.areEqualReturn = !identityHandlerStub.areEqualReturn;
checkEquality(instance1, instance2, identityHandlerStub);
identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class);
checkHashCode(instance1, identityHandlerStub);
identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class);
checkHashCode(instance1, identityHandlerStub);
IdentityFactory.unregisterIdentityHandler(identityHandlerStub);
} | #vulnerable code
public void run(final PojoClass pojoClass) {
IdentityFactory.registerIdentityHandler(identityHandlerStub);
firstPojoClassInstance = ValidationHelper.getMostCompleteInstance(pojoClass);
secondPojoClassInstance = ValidationHelper.getMostCompleteInstance(pojoClass);
// check one way
identityHandlerStub.areEqualReturn = RandomFactory.getRandomValue(Boolean.class);
checkEquality();
identityHandlerStub.areEqualReturn = !identityHandlerStub.areEqualReturn;
checkEquality();
identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class);
checkHashCode();
identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class);
checkHashCode();
IdentityFactory.unregisterIdentityHandler(identityHandlerStub);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randomByte = new byte[1];
RANDOM.nextBytes(randomByte);
return randomByte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RANDOM.nextLong());
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RANDOM.nextLong());
return calendar;
}
return null;
} | #vulnerable code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randombyte = new byte[1];
RANDOM.nextBytes(randombyte);
return randombyte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RandomFactory.getRandomValue(Long.class));
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class));
return calendar;
}
return null;
}
#location 60
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(expected = ReflectionException.class)
public void shouldFailSet() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType()));
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailSet() {
PojoField pojoField = getPrivateStringField();
pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType()));
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randomByte = new byte[1];
RANDOM.nextBytes(randomByte);
return randomByte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RANDOM.nextLong());
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RANDOM.nextLong());
return calendar;
}
return null;
} | #vulnerable code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randombyte = new byte[1];
RANDOM.nextBytes(randombyte);
return randombyte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RandomFactory.getRandomValue(Long.class));
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class));
return calendar;
}
return null;
}
#location 55
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void defaultRandomGeneratorServicePrePopulated() {
reportDifferences();
Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size());
} | #vulnerable code
@Test
public void defaultRandomGeneratorServicePrePopulated() {
// JDK 5 only supports 42 of the 44 possible types. (java.util.ArrayDeque does not exist in JDK5).
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.6") || javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) {
System.out.println("Found that many types: " + expectedDefaultTypes.size());
for (Class<?> expectedEntry : expectedDefaultTypes) {
boolean found = false;
for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) {
if (expectedEntry == foundEntry) found = true;
}
if (!found) System.out.println("\"" + expectedEntry.getName() + "\"");
}
System.out.println("Registered and not in the expected list!!");
for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) {
boolean found = false;
for (Class<?> expectedEntry : expectedDefaultTypes) {
if (expectedEntry == foundEntry) found = true;
}
if (!found) System.out.println("\"" + foundEntry.getName() + "\"");
}
Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size());
} else {
if (javaVersion.startsWith("1.5")) {
Affirm.affirmEquals("Types added / removed?", expectedTypes - 1, // (java.util.ArrayDeque does not exist
// in JDK5),
randomGeneratorService.getRegisteredTypes().size());
} else {
Affirm.fail("Unknown java version found " + System.getProperty("java.version") + " please check the " +
"correct number of expected registered classes and register type here - (found " + randomGeneratorService
.getRegisteredTypes().size() + ")");
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
List<File> paths = getPackageDirectories(packageName);
for (File path : paths) {
for (File entry : path.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
}
return classes;
} | #vulnerable code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
File directory = getPackageAsDirectory(packageName);
for (File entry : directory.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
return classes;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int find(int[] numbers, int position) {
validateInput(numbers, position);
Integer result = null;
Map<Integer, Integer> counter = new LinkedHashMap<Integer, Integer>();
for (int i : numbers) {
if (counter.get(i) == null) {
counter.put(i, 1);
} else {
counter.put(i, counter.get(i) + 1);
}
}
for (Integer candidate : counter.keySet()) {
if (counter.get(candidate) == position) {
result = candidate;
break;
}
}
validateResult(result);
return result;
} | #vulnerable code
public int find(int[] numbers, int position) {
validateInput(numbers, position);
Integer result = null;
Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
for (int i : numbers) {
if (counter.get(i) == null) {
counter.put(i, 1);
} else {
counter.put(i, counter.get(i) + 1);
}
}
for (Integer candidate : counter.keySet()) {
if (counter.get(candidate) == position) {
result = candidate;
break;
}
}
validateResult(result);
return result;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public static void parse(String content, Object data) {
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else if (map != null) {
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
} | #vulnerable code
@SuppressWarnings("unchecked")
public static void parse(String content, Object data) {
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else {
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
}
#location 43
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void parse(String content, Object data) {
if (content == null) {
return;
}
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else if (map != null) {
@SuppressWarnings("unchecked")
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
} | #vulnerable code
public static void parse(String content, Object data) {
if (content == null) {
return;
}
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else {
@SuppressWarnings("unchecked")
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
}
#location 47
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static byte[] loadBytes(String filename) {
InputStream input = null;
try {
input = classLoader().getResourceAsStream(filename);
if (input == null) {
File file = new File(filename);
if (file.exists()) {
try {
input = new FileInputStream(filename);
} catch (FileNotFoundException e) {
throw U.rte(e);
}
}
}
return input != null ? loadBytes(input) : null;
} finally {
close(input, true);
}
} | #vulnerable code
public static byte[] loadBytes(String filename) {
InputStream input = classLoader().getResourceAsStream(filename);
if (input == null) {
File file = new File(filename);
if (file.exists()) {
try {
input = new FileInputStream(filename);
} catch (FileNotFoundException e) {
throw U.rte(e);
}
}
}
return input != null ? loadBytes(input) : null;
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object handle(HttpExchange x) throws Exception {
String code = x.param("code");
String state = x.param("state");
U.debug("Received OAuth code", "code", code, "state", state);
if (code != null && state != null) {
U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!");
String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath);
TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUrl).setCode(code);
OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token(request, oAuthClient);
String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken);
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
accessToken).buildQueryMessage();
OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);
U.must(res.getResponseCode() == 200, "OAuth response error!");
Map<String, Object> auth = JSON.parseMap(res.getBody());
String firstName = (String) U.or(auth.get("firstName"),
U.or(auth.get("first_name"), auth.get("given_name")));
String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
UserInfo user = new UserInfo();
user.name = U.or((String) auth.get("name"), firstName + " " + lastName);
user.oauthProvider = provider.getName();
user.email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
user.username = user.email;
user.oauthId = String.valueOf(auth.get("id"));
x.sessionSet("_user", user);
U.must(x.user() == user);
return x.redirect("/");
} else {
String error = x.param("error");
if (error != null) {
U.warn("OAuth error", "error", error);
throw U.rte("OAuth error!");
}
}
throw U.rte("OAuth error!");
} | #vulnerable code
@Override
public Object handle(HttpExchange x) throws Exception {
String code = x.param("code");
String state = x.param("state");
U.debug("Received OAuth code", "code", code, "state", state);
if (code != null && state != null) {
U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!");
String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath);
TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUrl).setCode(code);
OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token(request, oAuthClient);
String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken);
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
accessToken).buildQueryMessage();
OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);
U.must(res.getResponseCode() == 200, "OAuth response error!");
Map<String, Object> auth = JSON.parseMap(res.getBody());
String firstName = (String) U.or(auth.get("firstName"),
U.or(auth.get("first_name"), auth.get("given_name")));
String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
UserInfo user = new UserInfo();
user.name = U.or((String) auth.get("name"), firstName + " " + lastName);
user.oauthProvider = provider.getName();
user.email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
user.username = user.email;
user.oauthId = String.valueOf(auth.get("id"));
user.display = user.email.substring(0, user.email.indexOf('@'));
x.sessionSet("_user", user);
U.must(x.user() == user);
return x.redirect("/");
} else {
String error = x.param("error");
if (error != null) {
U.warn("OAuth error", "error", error);
throw U.rte("OAuth error!");
}
}
throw U.rte("OAuth error!");
}
#location 46
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
resetResponse();
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception {
return Customization.of(req).objectMapper().convertValue(properties, paramType);
} | #vulnerable code
@Override
public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception {
return Customization.of(req).jackson().convertValue(properties, paramType);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
startedResponse = false;
responseCode = -1;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Db db() {
assert U.must(db != null, "Database not initialized!");
return db;
} | #vulnerable code
public static Db db() {
assert U.must(defaultDb != null, "Database not initialized!");
return defaultDb;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Set<String> userRoles(Req req, String username) {
if (username != null) {
try {
return Customization.of(req).rolesProvider().getRolesForUser(req, username);
} catch (Exception e) {
throw U.rte(e);
}
} else {
return Collections.emptySet();
}
} | #vulnerable code
private Set<String> userRoles(Req req, String username) {
if (username != null) {
try {
return req.routes().custom().rolesProvider().getRolesForUser(req, username);
} catch (Exception e) {
throw U.rte(e);
}
} else {
return Collections.emptySet();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + Arrays.hashCode(classpath);
result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0);
return result;
} | #vulnerable code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
return result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void renderJson(Req req, Object value, OutputStream out) throws Exception {
Customization.of(req).jackson().writeValue(out, value);
} | #vulnerable code
@Override
public void renderJson(Req req, Object value, OutputStream out) throws Exception {
req.custom().jackson().writeValue(out, value);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(timeout = 30000)
public void testJDBCWithTextConfig() {
Conf.JDBC.set("driver", "org.h2.Driver");
Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
Conf.JDBC.set("username", "sa");
Conf.C3P0.set("maxPoolSize", "123");
JdbcClient jdbc = JDBC.defaultApi();
eq(jdbc.driver(), "org.h2.Driver");
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().init().pool();
ComboPooledDataSource c3p0 = pool.pool();
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getMaxPoolSize(), 123);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
} | #vulnerable code
@Test(timeout = 30000)
public void testJDBCWithTextConfig() {
Conf.JDBC.set("driver", "org.h2.Driver");
Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
Conf.JDBC.set("username", "sa");
Conf.C3P0.set("maxPoolSize", "123");
JDBC.defaultApi().pooled();
JdbcClient jdbc = JDBC.defaultApi();
eq(jdbc.driver(), "org.h2.Driver");
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().pool();
ComboPooledDataSource c3p0 = pool.pool();
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getMaxPoolSize(), 123);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result);
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
} | #vulnerable code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result, Customization.of(req).errorHandler());
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
resetResponse();
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Object emit(HttpExchange x) {
int event = U.num(x.data("event"));
TagContext ctx = x.session(SESSION_CTX, null);
// if the context has been lost, reload the page
if (ctx == null) {
return changes(x, PAGE_RELOAD);
}
Cmd cmd = ctx.getEventCmd(event);
if (cmd != null) {
Map<Integer, Object> inp = Pages.inputs(x);
ctx.emitValues(inp);
} else {
U.warn("Invalid event!", "event", event);
}
Object page = U.newInstance(currentPage(x));
Pages.load(x, page);
if (cmd != null) {
callCmdHandler(x, page, cmd);
}
ctx = Tags.context();
x.sessionSet(Pages.SESSION_CTX, ctx);
Object content = Pages.contentOf(x, page);
if (content == null || content instanceof HttpExchange) {
return content;
}
String html = PageRenderer.get().toHTML(ctx, content, x);
Pages.store(x, page);
return changes(x, html);
} | #vulnerable code
public static Object emit(HttpExchange x) {
int event = U.num(x.data("event"));
TagContext ctx = x.session(SESSION_CTX, null);
// if the context has been lost, reload the page
if (ctx == null) {
return changes(x, PAGE_RELOAD);
}
Cmd cmd = ctx.getEventCmd(event);
if (cmd != null) {
Map<Integer, Object> inp = Pages.inputs(x);
ctx.emitValues(inp);
} else {
U.warn("Invalid event!", "event", event);
}
Object page = U.newInstance(currentPage(x));
Pages.load(x, page);
callCmdHandler(x, page, cmd);
ctx = Tags.context();
x.sessionSet(Pages.SESSION_CTX, ctx);
Object content = Pages.contentOf(x, page);
if (content == null || content instanceof HttpExchange) {
return content;
}
String html = PageRenderer.get().toHTML(ctx, content, x);
Pages.store(x, page);
return changes(x, html);
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String get() {
return count > 0 ? String.format("%s:[%s..%s..%s]#%s", sum, min, sum / count, max, count) : "" + ticks;
} | #vulnerable code
@Override
public String get() {
return count > 0 ? String.format("[%s..%s..%s]/%s", min, sum / count, max, count) : null;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result, Customization.of(req).errorHandler());
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
} | #vulnerable code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result, req.routes().custom().errorHandler());
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public HttpExchangeBody goBack(int steps) {
String dest = "/";
List<String> stack = session(SESSION_PAGE_STACK, null);
if (stack != null) {
if (!stack.isEmpty()) {
dest = stack.get(stack.size() - 1);
}
for (int i = 0; i < steps; i++) {
if (!stack.isEmpty()) {
stack.remove(stack.size() - 1);
if (!stack.isEmpty()) {
dest = stack.remove(stack.size() - 1);
}
}
}
}
return redirect(dest);
} | #vulnerable code
@Override
public HttpExchangeBody goBack(int steps) {
List<String> stack = session(SESSION_PAGE_STACK, null);
String dest = !stack.isEmpty() ? stack.get(stack.size() - 1) : "/";
for (int i = 0; i < steps; i++) {
if (stack != null && !stack.isEmpty()) {
stack.remove(stack.size() - 1);
if (!stack.isEmpty()) {
dest = stack.remove(stack.size() - 1);
}
}
}
return redirect(dest);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private byte[] responseToBytes() {
try {
return response.renderToBytes();
} catch (Throwable e) {
HttpIO.error(this, e);
try {
return response.renderToBytes();
} catch (Exception e1) {
Log.error("Internal rendering error!", e1);
return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes();
}
}
} | #vulnerable code
private byte[] responseToBytes() {
try {
return response.renderToBytes();
} catch (Throwable e) {
HttpIO.error(this, e, Customization.of(this).errorHandler());
try {
return response.renderToBytes();
} catch (Exception e1) {
Log.error("Internal rendering error!", e1);
return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes();
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Future<byte[]> get(String uri, Callback<byte[]> callback) {
return request("GET", uri, null, null, null, null, null, callback);
} | #vulnerable code
public Future<byte[]> get(String uri, Callback<byte[]> callback) {
HttpGet req = new HttpGet(uri);
Log.debug("Starting HTTP GET request", "request", req.getRequestLine());
return execute(client, req, callback);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void process(Channel ctx) {
if (ctx.isInitial()) {
return;
}
Buf buf = ctx.input();
RapidoidHelper helper = ctx.helper();
Range[] ranges = helper.ranges1.ranges;
Ranges hdrs = helper.ranges2;
BoolWrap isGet = helper.booleans[0];
BoolWrap isKeepAlive = helper.booleans[1];
Range verb = ranges[ranges.length - 1];
Range uri = ranges[ranges.length - 2];
Range path = ranges[ranges.length - 3];
Range query = ranges[ranges.length - 4];
Range protocol = ranges[ranges.length - 5];
Range body = ranges[ranges.length - 6];
HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper);
// the listener may override all the request dispatching and handler execution
if (!listener.request(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs)) {
return;
}
HttpStatus status = HttpStatus.NOT_FOUND;
FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path);
if (handler != null) {
Map<String, Object> params = null;
if (handler.needsParams()) {
params = U.map();
KeyValueRanges paramsKV = helper.pairs1.reset();
KeyValueRanges headersKV = helper.pairs2.reset();
HTTP_PARSER.parseParams(buf, paramsKV, query);
// parse URL parameters as data
Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true));
if (!isGet.value) {
KeyValueRanges postedKV = helper.pairs3.reset();
KeyValueRanges filesKV = helper.pairs4.reset();
// parse posted body as data
HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data);
}
// filter special data values
Map<String, Object> special = findSpecialData(data);
if (special != null) {
data.keySet().removeAll(special.keySet());
} else {
special = U.cast(Collections.EMPTY_MAP);
}
// put all data directly as parameters
params.putAll(data);
params.put(DATA, data);
params.put(SPECIAL, special);
// finally, the HTTP info
params.put(VERB, verb.str(buf));
params.put(URI, uri.str(buf));
params.put(PATH, path.str(buf));
params.put(CLIENT_ADDRESS, ctx.address());
if (handler.needsHeadersAndCookies()) {
KeyValueRanges cookiesKV = helper.pairs5.reset();
HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper);
Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true));
Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true));
params.put(HEADERS, headers);
params.put(COOKIES, cookies);
params.put(HOST, U.get(headers, "Host", null));
params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null));
}
}
status = handler.handle(ctx, isKeepAlive.value, params);
}
if (status == HttpStatus.NOT_FOUND) {
ctx.write(HTTP_404_NOT_FOUND);
listener.notFound(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs);
}
if (status != HttpStatus.ASYNC) {
ctx.closeIf(!isKeepAlive.value);
}
} | #vulnerable code
public void process(Channel ctx) {
if (ctx.isInitial()) {
return;
}
Buf buf = ctx.input();
RapidoidHelper helper = ctx.helper();
Range[] ranges = helper.ranges1.ranges;
Ranges hdrs = helper.ranges2;
BoolWrap isGet = helper.booleans[0];
BoolWrap isKeepAlive = helper.booleans[1];
Range verb = ranges[ranges.length - 1];
Range uri = ranges[ranges.length - 2];
Range path = ranges[ranges.length - 3];
Range query = ranges[ranges.length - 4];
Range protocol = ranges[ranges.length - 5];
Range body = ranges[ranges.length - 6];
HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper);
HttpStatus status = HttpStatus.NOT_FOUND;
FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path);
if (handler != null) {
Map<String, Object> params = null;
if (handler.needsParams()) {
params = U.map();
KeyValueRanges paramsKV = helper.pairs1.reset();
KeyValueRanges headersKV = helper.pairs2.reset();
HTTP_PARSER.parseParams(buf, paramsKV, query);
// parse URL parameters as data
Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true));
if (!isGet.value) {
KeyValueRanges postedKV = helper.pairs3.reset();
KeyValueRanges filesKV = helper.pairs4.reset();
// parse posted body as data
HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data);
}
// filter special data values
Map<String, Object> special = findSpecialData(data);
if (special != null) {
data.keySet().removeAll(special.keySet());
} else {
special = U.cast(Collections.EMPTY_MAP);
}
// put all data directly as parameters
params.putAll(data);
params.put(DATA, data);
params.put(SPECIAL, special);
// finally, the HTTP info
params.put(VERB, verb.str(buf));
params.put(URI, uri.str(buf));
params.put(PATH, path.str(buf));
params.put(CLIENT_ADDRESS, ctx.address());
if (handler.needsHeadersAndCookies()) {
KeyValueRanges cookiesKV = helper.pairs5.reset();
HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper);
Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true));
Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true));
params.put(HEADERS, headers);
params.put(COOKIES, cookies);
params.put(HOST, U.get(headers, "Host", null));
params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null));
}
}
status = handler.handle(ctx, isKeepAlive.value, params);
}
if (status == HttpStatus.NOT_FOUND) {
ctx.write(HTTP_404_NOT_FOUND);
}
if (status != HttpStatus.ASYNC) {
ctx.closeIf(!isKeepAlive.value);
}
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) {
columns.add("(Actions)");
final String groupName = group.name();
final String kind = group.kind();
info.add(breadcrumb(kind, groupName));
Grid grid = grid(items)
.columns(columns)
.headers(columns)
.toUri(new Mapper<Manageable, String>() {
@Override
public String map(Manageable handle) throws Exception {
return Msc.specialUri("manageables", kind, Msc.urlEncode(handle.id()));
}
})
.pageSize(20);
info.add(grid);
} | #vulnerable code
private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) {
columns.add("(Actions)");
final String groupName = group.name();
String type = U.first(items).getManageableType();
info.add(breadcrumb(type, groupName));
Grid grid = grid(items)
.columns(columns)
.headers(columns)
.toUri(new Mapper<Manageable, String>() {
@Override
public String map(Manageable handle) throws Exception {
return Msc.uri("_manageables", handle.getClass().getSimpleName(), Msc.urlEncode(handle.id()));
}
})
.pageSize(20);
info.add(grid);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
ZipInputStream zip = null;
try {
String pkgPath = pkgToPath(pkg);
File jarFile = new File(jarName);
FileInputStream jarInputStream = new FileInputStream(jarFile);
zip = new ZipInputStream(jarInputStream);
ZipEntry e;
while ((e = zip.getNextEntry()) != null) {
if (!e.isDirectory()) {
String name = e.getName();
if (!ignore(name)) {
if (U.isEmpty(pkg) || name.startsWith(pkgPath)) {
scanFile(classes, regex, filter, annotated, classLoader, name);
}
}
}
}
} catch (Exception e) {
Log.error("Cannot scan JAR: " + jarName, e);
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
Log.error("Couldn't close the ZIP stream!", e);
}
}
}
return classes;
} | #vulnerable code
private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
try {
String pkgPath = pkgToPath(pkg);
ZipInputStream zip = new ZipInputStream(new URL("file://" + jarName).openStream());
ZipEntry e;
while ((e = zip.getNextEntry()) != null) {
if (!e.isDirectory()) {
String name = e.getName();
if (!ignore(name)) {
if (U.isEmpty(pkg) || name.startsWith(pkgPath)) {
scanFile(classes, regex, filter, annotated, classLoader, name);
}
}
}
}
} catch (Exception e) {
throw U.rte(e);
}
return classes;
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public static WebApp bootstrap(WebApp app, String[] args, Object... config) {
Log.info("Starting Rapidoid...", "version", RapidoidInfo.version());
ConfigHelp.processHelp(args);
// FIXME make optional
// print internal state
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Conf.init(args, config);
Log.info("Working directory is: " + System.getProperty("user.dir"));
inferAndSetRootPackage();
if (app == null) {
app = AppTool.createRootApp();
}
registerDefaultPlugins();
Set<String> configArgs = U.set(args);
for (Object arg : config) {
processArg(configArgs, arg);
}
String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]);
Conf.args(configArgsArr);
Log.args(configArgsArr);
AOP.reset();
AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class,
DevMode.class, Role.class, HasRole.class);
return app;
} | #vulnerable code
@SuppressWarnings("unchecked")
public static WebApp bootstrap(WebApp app, String[] args, Object... config) {
Log.info("Starting Rapidoid...", "version", RapidoidInfo.version());
ConfigHelp.processHelp(args);
// FIXME make optional
// print internal state
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Conf.init(args, config);
Log.info("Working directory is: " + System.getProperty("user.dir"));
inferAndSetRootPackage();
if (app == null) {
app = AppTool.createRootApp();
}
registerDefaultPlugins();
Set<String> configArgs = U.set(args);
for (Object arg : config) {
processArg(configArgs, arg);
}
String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]);
Conf.args(configArgsArr);
Log.args(configArgsArr);
AOP.reset();
AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class,
DevMode.class, Role.class, HasRole.class);
return app;
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object call() throws Exception {
List<Object> info = U.list();
Collection<? extends GroupOf<?>> targetGroups = groups != null ? groups : Groups.all();
for (GroupOf<?> group : targetGroups) {
List<? extends Manageable> items = group.items();
List<String> nav = U.list(group.kind());
info.add(h2(group.kind()));
addInfo(baseUri, info, nav, items);
}
info.add(autoRefresh(2000));
return multi(info);
} | #vulnerable code
@Override
public Object call() throws Exception {
List<Object> info = U.list();
for (GroupOf<?> group : Groups.all()) {
List<? extends Manageable> items = group.items();
if (U.notEmpty(items)) {
List<String> columns = U.first(items).getManageableProperties();
if (U.notEmpty(columns)) {
addInfo(info, group, items, columns);
}
}
}
info.add(autoRefresh(2000));
return multi(info);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldParseRequest1() {
RapidoidHelper req = parse(REQ1);
BufGroup bufs = new BufGroup(2);
Buf reqbuf = bufs.from(REQ1, "r2");
eq(REQ1, req.verb, "GET");
eq(REQ1, req.path, "/foo/bar");
eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20");
eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " "));
eq(REQ1, req.protocol, "HTTP/1.1");
eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2");
isNone(req.body);
} | #vulnerable code
@Test
public void shouldParseRequest1() {
ReqData req = parse(REQ1);
BufGroup bufs = new BufGroup(2);
Buf reqbuf = bufs.from(REQ1, "r2");
eq(REQ1, req.rVerb, "GET");
eq(REQ1, req.rPath, "/foo/bar");
eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20");
eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " "));
eq(REQ1, req.rProtocol, "HTTP/1.1");
eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2");
isNone(req.rBody);
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void generateIndex(String path) {
System.out.println();
System.out.println();
System.out.println("*************** " + path);
System.out.println();
System.out.println();
List<Map<String, ?>> examplesl = U.list();
IntWrap nl = new IntWrap();
List<String> eglistl = IO.loadLines("examplesl.txt");
processAll(examplesl, nl, eglistl);
List<Map<String, ?>> examplesh = U.list();
IntWrap nh = new IntWrap();
List<String> eglisth = IO.loadLines("examplesh.txt");
processAll(examplesh, nh, eglisth);
Map<String, ?> model = U.map("examplesh", examplesh, "examplesl", examplesl, "version", UTILS.version()
.replace("-SNAPSHOT", ""));
String html = Templates.fromFile("docs.html").render(model);
IO.save(path + "index.html", html);
} | #vulnerable code
private static void generateIndex(String path) {
System.out.println();
System.out.println();
System.out.println("*************** " + path);
System.out.println();
System.out.println();
List<Map<String, ?>> examples = U.list();
IntWrap nn = new IntWrap();
List<String> eglist = IO.loadLines("examples.txt");
List<String> processed = processAll(examples, nn, eglist);
System.out.println("Processed: " + processed);
Map<String, ?> model = U.map("examples", examples);
String html = Templates.fromFile("docs.html").render(model);
IO.save(path + "index.html", html);
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + Arrays.hashCode(classpath);
result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0);
return result;
} | #vulnerable code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
return result;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void render(Req req, Object value, OutputStream out) throws Exception {
Customization.of(req).xmlMapper().writeValue(out, value);
} | #vulnerable code
@Override
public void render(Req req, Object value, OutputStream out) throws Exception {
Customization.of(req).jacksonXml().writeValue(out, value);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void doProcessing() {
long now = U.time();
int connectingN = connecting.size();
for (int i = 0; i < connectingN; i++) {
ConnectionTarget target = connecting.poll();
assert target != null;
if (target.retryAfter < now) {
Log.debug("connecting", "address", target.addr);
try {
SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT);
newKey.attach(target);
} catch (ClosedChannelException e) {
Log.warn("Closed channel", e);
}
} else {
connecting.add(target);
}
}
RapidoidChannel channel;
while ((channel = connected.poll()) != null) {
SocketChannel socketChannel = channel.socketChannel;
Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress());
try {
SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ);
U.notNull(channel.protocol, "protocol");
RapidoidConnection conn = attachConn(newKey, channel.protocol);
conn.setClient(channel.isClient);
try {
processNext(conn, true);
} finally {
conn.setInitial(false);
}
} catch (ClosedChannelException e) {
Log.warn("Closed channel", e);
}
}
RapidoidConnection restartedConn;
while ((restartedConn = restarting.poll()) != null) {
Log.debug("restarting", "connection", restartedConn);
processNext(restartedConn, true);
}
synchronized (done) {
for (int i = 0; i < done.size(); i++) {
RapidoidConnection conn = done.get(i);
if (conn.key != null && conn.key.isValid()) {
conn.key.interestOps(SelectionKey.OP_WRITE);
}
}
done.clear();
}
} | #vulnerable code
@Override
protected void doProcessing() {
long now = U.time();
int connectingN = connecting.size();
for (int i = 0; i < connectingN; i++) {
ConnectionTarget target = connecting.poll();
assert target != null;
if (target.retryAfter < now) {
Log.debug("connecting", "address", target.addr);
try {
SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT);
newKey.attach(target);
} catch (ClosedChannelException e) {
Log.warn("Closed channel", e);
}
} else {
connecting.add(target);
}
}
RapidoidChannel channel;
while ((channel = connected.poll()) != null) {
SocketChannel socketChannel = channel.socketChannel;
Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress());
try {
SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ);
RapidoidConnection conn = attachConn(newKey, channel.protocol);
conn.setClient(channel.isClient);
try {
processNext(conn, true);
} finally {
conn.setInitial(false);
}
} catch (ClosedChannelException e) {
Log.warn("Closed channel", e);
}
}
RapidoidConnection restartedConn;
while ((restartedConn = restarting.poll()) != null) {
Log.debug("restarting", "connection", restartedConn);
processNext(restartedConn, true);
}
synchronized (done) {
for (int i = 0; i < done.size(); i++) {
RapidoidConnection conn = done.get(i);
if (conn.key != null && conn.key.isValid()) {
conn.key.interestOps(SelectionKey.OP_WRITE);
}
}
done.clear();
}
}
#location 38
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void verifyCase(String info, String actual, String testCaseName) {
String s = File.separator;
String resname = "results" + s + testName() + s + getTestMethodName() + s + testCaseName;
String filename = "src" + s + "test" + s + "resources" + s + resname;
if (ADJUST_RESULTS) {
File testDir = new File(filename).getParentFile();
if (!testDir.exists()) {
if (!testDir.mkdirs()) {
throw new RuntimeException("Couldn't create the test result folder: " + testDir.getAbsolutePath());
}
}
FileOutputStream out;
try {
out = new FileOutputStream(filename);
out.write(actual.getBytes());
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
byte[] bytes = loadRes(resname);
String expected = bytes != null ? new String(bytes) : "";
check(info, actual, expected);
}
} | #vulnerable code
protected void verifyCase(String info, String actual, String testCaseName) {
String s = File.separator;
String resname = "results" + s + testName() + s + getTestMethodName() + s + testCaseName;
String filename = "src" + s + "test" + s + "resources" + s + resname;
if (ADJUST_RESULTS) {
File testDir = new File(filename).getParentFile();
if (!testDir.exists()) {
testDir.mkdirs();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
out.write(actual.getBytes());
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
byte[] bytes = loadRes(resname);
String expected = bytes != null ? new String(bytes) : "";
check(info, actual, expected);
}
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) {
if (req != null) {
if (!req.isStopped()) {
try {
HttpIO.errorAndDone(req, e);
} catch (Exception e1) {
Log.error("HTTP error handler error!", e1);
internalServerError(channel, isKeepAlive, req, contentType);
}
}
return true;
} else {
Log.error("Low-level HTTP handler error!", e);
internalServerError(channel, isKeepAlive, req, contentType);
}
return false;
} | #vulnerable code
private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) {
if (req != null) {
if (!req.isStopped()) {
HttpIO.errorAndDone(req, e);
}
return true;
} else {
Log.error("Low-level HTTP handler error!", e);
HttpIO.startResponse(channel, 500, isKeepAlive, contentType);
byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer());
HttpIO.writeContentLengthAndBody(channel, bytes);
HttpIO.done(channel, isKeepAlive);
}
return false;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + Arrays.hashCode(classpath);
result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0);
return result;
} | #vulnerable code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
return result;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(timeout = 30000)
public void testHikariPool() {
Conf.HIKARI.set("maximumPoolSize", 234);
JdbcClient jdbc = JDBC.api();
jdbc.h2("hikari-test");
jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc));
jdbc.execute("create table abc (id int, name varchar)");
jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
record = Msc.lowercase(record);
eq(record, expected);
});
HikariDataSource hikari = (HikariDataSource) jdbc.dataSource();
eq(hikari.getMaximumPoolSize(), 234);
} | #vulnerable code
@Test(timeout = 30000)
public void testHikariPool() {
JdbcClient jdbc = JDBC.api();
jdbc.h2("hikari-test");
jdbc.pool(new HikariConnectionPool(jdbc));
jdbc.execute("create table abc (id int, name varchar)");
jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
record = Msc.lowercase(record);
eq(record, expected);
});
isTrue(jdbc.pool() instanceof HikariConnectionPool);
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static <T> void invokePostConstruct(T target) {
List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class);
for (Method method : methods) {
Cls.invoke(method, target);
}
} | #vulnerable code
private static <T> void invokePostConstruct(T target) {
List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class);
for (Method method : methods) {
Cls.invoke(null, method, target);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object handle(HttpExchange x) throws Exception {
return Pages.emit(x);
} | #vulnerable code
@Override
public Object handle(HttpExchange x) throws Exception {
int event = U.num(x.data("event"));
TagContext ctx = Pages.ctx(x);
Map<Integer, Object> inp = Pages.inputs(x);
ctx.emit(inp, event);
Object page = U.newInstance(currentPage(x));
ctx = Tags.context();
x.setSession(Pages.SESSION_CTX, ctx);
Object body = Pages.contentOf(x, page);
if (body == null) {
}
if (body instanceof HttpExchange) {
return body;
}
System.out.println(body);
String html = PageRenderer.get().toHTML(ctx, body, x);
Map<String, String> changes = U.map();
changes.put("body", html);
x.json();
return changes;
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception {
return Customization.of(req).jackson().convertValue(properties, paramType);
} | #vulnerable code
@Override
public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception {
return req.custom().jackson().convertValue(properties, paramType);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public static WebApp bootstrap(WebApp app, String[] args, Object... config) {
Log.info("Starting Rapidoid...", "version", RapidoidInfo.version());
ConfigHelp.processHelp(args);
// FIXME make optional
// print internal state
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Conf.init(args, config);
Log.info("Working directory is: " + System.getProperty("user.dir"));
inferAndSetRootPackage();
if (app == null) {
app = AppTool.createRootApp();
}
registerDefaultPlugins();
Set<String> configArgs = U.set(args);
for (Object arg : config) {
processArg(configArgs, arg);
}
String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]);
Conf.args(configArgsArr);
Log.args(configArgsArr);
AOP.reset();
AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class,
DevMode.class, Role.class, HasRole.class);
return app;
} | #vulnerable code
@SuppressWarnings("unchecked")
public static WebApp bootstrap(WebApp app, String[] args, Object... config) {
Log.info("Starting Rapidoid...", "version", RapidoidInfo.version());
ConfigHelp.processHelp(args);
// FIXME make optional
// print internal state
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Conf.init(args, config);
Log.info("Working directory is: " + System.getProperty("user.dir"));
inferAndSetRootPackage();
if (app == null) {
app = AppTool.createRootApp();
}
registerDefaultPlugins();
Set<String> configArgs = U.set(args);
for (Object arg : config) {
processArg(configArgs, arg);
}
String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]);
Conf.args(configArgsArr);
Log.args(configArgsArr);
AOP.reset();
AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class,
DevMode.class, Role.class, HasRole.class);
return app;
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) {
if (req != null) {
if (!req.isStopped()) {
HttpIO.errorAndDone(req, e);
}
return true;
} else {
Log.error("Low-level HTTP handler error!", e);
HttpIO.startResponse(channel, 500, isKeepAlive, contentType);
byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer());
HttpIO.writeContentLengthAndBody(channel, bytes);
HttpIO.done(channel, isKeepAlive);
}
return false;
} | #vulnerable code
private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) {
if (req != null) {
if (!req.isStopped()) {
HttpIO.errorAndDone(req, e, customization.errorHandler());
}
return true;
} else {
Log.error("Low-level HTTP handler error!", e);
HttpIO.startResponse(channel, 500, isKeepAlive, contentType);
byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer());
HttpIO.writeContentLengthAndBody(channel, bytes);
HttpIO.done(channel, isKeepAlive);
}
return false;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
resetResponse();
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void setRootPath(String rootPath) {
Log.info("Setting 'root' application path", "path", rootPath);
Conf.rootPath = cleanPath(rootPath);
setStaticPath(Conf.rootPath + "/static");
setDynamicPath(Conf.rootPath + "/dynamic");
setConfigPath(Conf.rootPath);
} | #vulnerable code
public static void setRootPath(String rootPath) {
Log.info("Setting 'root' application path", "path", rootPath);
Conf.rootPath = cleanPath(rootPath);
setStaticPath(Conf.rootPath + "/static");
setDynamicPath(Conf.rootPath + "/dynamic");
setConfigPath(Conf.rootPath);
setTemplatesPath(Conf.rootPath + "/templates");
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
ZipInputStream zip = null;
try {
String pkgPath = pkgToPath(pkg);
File jarFile = new File(jarName);
FileInputStream jarInputStream = new FileInputStream(jarFile);
zip = new ZipInputStream(jarInputStream);
ZipEntry e;
while ((e = zip.getNextEntry()) != null) {
if (!e.isDirectory()) {
String name = e.getName();
if (!ignore(name)) {
if (U.isEmpty(pkg) || name.startsWith(pkgPath)) {
scanFile(classes, regex, filter, annotated, classLoader, name);
}
}
}
}
} catch (Exception e) {
Log.error("Cannot scan JAR: " + jarName, e);
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
Log.error("Couldn't close the ZIP stream!", e);
}
}
}
return classes;
} | #vulnerable code
private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
try {
String pkgPath = pkgToPath(pkg);
ZipInputStream zip = new ZipInputStream(new URL("file://" + jarName).openStream());
ZipEntry e;
while ((e = zip.getNextEntry()) != null) {
if (!e.isDirectory()) {
String name = e.getName();
if (!ignore(name)) {
if (U.isEmpty(pkg) || name.startsWith(pkgPath)) {
scanFile(classes, regex, filter, annotated, classLoader, name);
}
}
}
}
} catch (Exception e) {
throw U.rte(e);
}
return classes;
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static DivTag field(FormLayout layout, String name, String desc, FieldType type, Object[] options,
Object value) {
desc = U.or(desc, name);
String inputId = "_" + name; // FIXME
Object inp = input_(inputId, name, desc, type, options, value);
LabelTag label;
Object inputWrap;
if (type == FieldType.RADIOS || type == FieldType.CHECKBOXES) {
inp = layout == FormLayout.VERTICAL ? div(inp) : span(inp);
}
if (type == FieldType.CHECKBOX) {
label = null;
inp = div(label(inp, desc)).classs("checkbox");
inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-offset-4 col-sm-8") : inp;
} else {
if (layout != FormLayout.INLINE) {
label = label(desc).for_(inputId);
} else {
if (type == FieldType.RADIOS) {
label = label(desc);
} else {
label = null;
}
}
if (layout == FormLayout.HORIZONTAL) {
label.classs("col-sm-4 control-label");
}
inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-8") : inp;
}
DivTag group = label != null ? div(label, inputWrap) : div(inputWrap);
group.classs("form-group");
return group;
} | #vulnerable code
public static DivTag field(FormLayout layout, String name, String desc, FieldType type, Object[] options,
Object value) {
desc = U.or(desc, name);
String inputId = "_" + name; // FIXME
Object inp = input_(inputId, name, desc, type, options, value);
LabelTag label;
Object inputWrap;
if (type == FieldType.RADIOS) {
inp = layout == FormLayout.VERTICAL ? div(inp) : span(inp);
}
if (type == FieldType.CHECKBOX) {
label = null;
inp = div(label(inp, desc)).classs("checkbox");
inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-offset-4 col-sm-8") : inp;
} else {
if (layout != FormLayout.INLINE) {
label = label(desc).for_(inputId);
} else {
if (type == FieldType.RADIOS) {
label = label(desc);
} else {
label = null;
}
}
if (layout == FormLayout.HORIZONTAL) {
label.classs("col-sm-4 control-label");
}
inputWrap = layout == FormLayout.HORIZONTAL ? div(inp).classs("col-sm-8") : inp;
}
DivTag group = label != null ? div(label, inputWrap) : div(inputWrap);
group.classs("form-group");
return group;
}
#location 34
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String loadResourceAsString(String filename) {
byte[] bytes = loadBytes(filename);
return bytes != null ? new String(bytes) : null;
} | #vulnerable code
public static String loadResourceAsString(String filename) {
return new String(loadBytes(filename));
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static char[] readPassword(String msg) {
Console console = System.console();
if (console != null) {
return console.readPassword(msg);
} else {
U.print(msg);
return readLine().toCharArray();
}
} | #vulnerable code
private static char[] readPassword(String msg) {
Console console = System.console();
if (console != null) {
return console.readPassword(msg);
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
U.print(msg);
try {
return reader.readLine().toCharArray();
} catch (IOException e) {
throw U.rte(e);
}
}
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEncryptWithCustomPassword() {
CryptoKey key = CryptoKey.from("pass".toCharArray());
for (int i = 0; i < 10000; i++) {
String msg1 = "" + i;
byte[] enc = Crypto.encrypt(msg1.getBytes(), key);
byte[] dec = Crypto.decrypt(enc, key);
String msg2 = new String(dec);
eq(msg2, msg1);
}
} | #vulnerable code
@Test
public void testEncryptWithCustomPassword() {
byte[] key = Crypto.pbkdf2("pass".toCharArray());
for (int i = 0; i < 10000; i++) {
String msg1 = "" + i;
byte[] enc = Crypto.encrypt(msg1.getBytes(), key);
byte[] dec = Crypto.decrypt(enc, key);
String msg2 = new String(dec);
eq(msg2, msg1);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
result = 31 * result + Arrays.hashCode(classpath);
result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0);
return result;
} | #vulnerable code
@Override
public int hashCode() {
int result = Arrays.hashCode(packages);
result = 31 * result + (matching != null ? matching.hashCode() : 0);
result = 31 * result + Arrays.hashCode(annotated);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
return result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test(timeout = 30000)
public void testJDBCPoolC3P0() {
JDBC.h2("test1");
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().init().pool();
ComboPooledDataSource c3p0 = pool.pool();
// validate default config
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getInitialPoolSize(), 5);
eq(c3p0.getAcquireIncrement(), 5);
eq(c3p0.getMaxPoolSize(), 100);
eq(c3p0.getMaxStatementsPerConnection(), 10);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
} | #vulnerable code
@Test(timeout = 30000)
public void testJDBCPoolC3P0() {
JDBC.h2("test1").pooled();
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().pool();
ComboPooledDataSource c3p0 = pool.pool();
// validate default config
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getInitialPoolSize(), 5);
eq(c3p0.getAcquireIncrement(), 5);
eq(c3p0.getMaxPoolSize(), 100);
eq(c3p0.getMaxStatementsPerConnection(), 10);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private byte[] responseToBytes() {
try {
return response.renderToBytes();
} catch (Throwable e) {
HttpIO.error(this, e, Customization.of(this).errorHandler());
try {
return response.renderToBytes();
} catch (Exception e1) {
Log.error("Internal rendering error!", e1);
return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes();
}
}
} | #vulnerable code
private byte[] responseToBytes() {
try {
return response.renderToBytes();
} catch (Throwable e) {
HttpIO.error(this, e, custom().errorHandler());
try {
return response.renderToBytes();
} catch (Exception e1) {
Log.error("Internal rendering error!", e1);
return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes();
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) {
final HttpParser parser = new HttpParser();
final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)};
final RapidoidHelper helper = new RapidoidHelper(null);
for (int i = 0; i < 100; i++) {
Msc.benchmark("parse", 3000000, new Runnable() {
int n;
@Override
public void run() {
Buf buf = reqs[n % 4];
buf.position(0);
parser.parse(buf, helper);
n++;
}
});
}
System.out.println(BUFS.instances() + " buffer instances.");
} | #vulnerable code
public static void main(String[] args) {
final HttpParser parser = new HttpParser();
final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)};
final RapidoidHelper helper = new RapidoidHelper(null);
BufRange[] ranges = helper.ranges1.ranges;
final BufRanges headers = helper.ranges2;
final BoolWrap isGet = helper.booleans[0];
final BoolWrap isKeepAlive = helper.booleans[1];
final BufRange verb = ranges[ranges.length - 1];
final BufRange uri = ranges[ranges.length - 2];
final BufRange path = ranges[ranges.length - 3];
final BufRange query = ranges[ranges.length - 4];
final BufRange protocol = ranges[ranges.length - 5];
final BufRange body = ranges[ranges.length - 6];
for (int i = 0; i < 10; i++) {
Msc.benchmark("parse", 3000000, new Runnable() {
int n;
@Override
public void run() {
Buf buf = reqs[n % 4];
buf.position(0);
parser.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, headers, helper);
n++;
}
});
}
System.out.println(BUFS.instances() + " buffer instances.");
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void render(Req req, Object value, OutputStream out) throws Exception {
Customization.of(req).objectMapper().writeValue(out, value);
} | #vulnerable code
@Override
public void render(Req req, Object value, OutputStream out) throws Exception {
Customization.of(req).jackson().writeValue(out, value);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void getClassesFromDir(Collection<Class<?>> classes, File root, File dir, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
U.must(dir.isDirectory());
Log.debug("Traversing directory", "root", root, "dir", dir);
File[] files = dir.listFiles();
if (files == null) {
Log.warn("Not a folder!", "dir", dir);
return;
}
for (File file : files) {
if (file.isDirectory()) {
getClassesFromDir(classes, root, file, pkg, regex, filter, annotated, classLoader);
} else {
String rootPath = U.trimr(root.getAbsolutePath(), File.separatorChar);
int from = rootPath.length() + 1;
String relName = file.getAbsolutePath().substring(from);
if (!ignore(relName)) {
scanFile(classes, regex, filter, annotated, classLoader, relName);
}
}
}
} | #vulnerable code
private static void getClassesFromDir(Collection<Class<?>> classes, File root, File dir, String pkg, Pattern regex,
Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) {
U.must(dir.isDirectory());
Log.debug("Traversing directory", "root", root, "dir", dir);
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
getClassesFromDir(classes, root, file, pkg, regex, filter, annotated, classLoader);
} else {
String rootPath = U.trimr(root.getAbsolutePath(), File.separatorChar);
int from = rootPath.length() + 1;
String relName = file.getAbsolutePath().substring(from);
if (!ignore(relName)) {
scanFile(classes, regex, filter, annotated, classLoader, relName);
}
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Future<byte[]> post(String uri, Map<String, String> headers, Map<String, String> data,
Map<String, String> files, Callback<byte[]> callback) {
return request("POST", uri, headers, data, files, null, null, callback);
} | #vulnerable code
public Future<byte[]> post(String uri, Map<String, String> headers, Map<String, String> data,
Map<String, String> files, Callback<byte[]> callback) {
headers = U.safe(headers);
data = U.safe(data);
files = U.safe(files);
HttpPost req = new HttpPost(uri);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Entry<String, String> entry : files.entrySet()) {
String filename = entry.getValue();
File file = IO.file(filename);
builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
}
for (Entry<String, String> entry : data.entrySet()) {
builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
builder.build().writeTo(stream);
} catch (IOException e) {
throw U.rte(e);
}
byte[] bytes = stream.toByteArray();
NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);
for (Entry<String, String> e : headers.entrySet()) {
req.addHeader(e.getKey(), e.getValue());
}
req.setEntity(entity);
Log.debug("Starting HTTP POST request", "request", req.getRequestLine());
return execute(client, req, callback);
}
#location 40
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void completeResponse() {
U.must(responseCode >= 100);
long wrote = output().size() - bodyPos;
U.must(wrote <= Integer.MAX_VALUE, "Response too big!");
int pos = startingPos + getResp(responseCode).contentLengthPos + 10;
output().putNumAsText(pos, wrote, false);
} | #vulnerable code
public void completeResponse() {
long wrote = output().size() - bodyPos;
U.must(wrote <= Integer.MAX_VALUE, "Response too big!");
int pos = startingPos + getResp(responseCode).contentLengthPos + 10;
output().putNumAsText(pos, wrote, false);
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected byte[] loadRes(String filename) {
InputStream input = TestCommons.class.getClassLoader().getResourceAsStream(filename);
return input != null ? readBytes(input) : null;
} | #vulnerable code
protected byte[] loadRes(String filename) {
try {
URL res = resource(filename);
return res != null ? readBytes(new FileInputStream(new File(res.getFile()))) : null;
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static byte[] render(ReqImpl req, Resp resp) {
Object result = resp.result();
if (result != null) {
result = wrapGuiContent(result);
resp.model().put("result", result);
resp.result(result);
}
ViewRenderer viewRenderer = Customization.of(req).viewRenderer();
U.must(viewRenderer != null, "A view renderer wasn't configured!");
PageRenderer pageRenderer = Customization.of(req).pageRenderer();
U.must(pageRenderer != null, "A page renderer wasn't configured!");
boolean rendered;
String viewName = resp.view();
ByteArrayOutputStream out = new ByteArrayOutputStream();
MVCModel basicModel = new MVCModel(req, resp, resp.model(), resp.screen(), result);
Object[] renderModel = result != null
? new Object[]{basicModel, resp.model(), result}
: new Object[]{basicModel, resp.model()};
try {
rendered = viewRenderer.render(req, viewName, renderModel, out);
} catch (Throwable e) {
throw U.rte("Error while rendering view: " + viewName, e);
}
String renderResult = rendered ? new String(out.toByteArray()) : null;
if (renderResult == null) {
Object cnt = U.or(result, "");
renderResult = new String(HttpUtils.responseToBytes(req, cnt, MediaType.HTML_UTF_8, null));
}
try {
Object response = U.or(pageRenderer.renderPage(req, resp, renderResult), "");
return HttpUtils.responseToBytes(req, response, MediaType.HTML_UTF_8, null);
} catch (Exception e) {
throw U.rte("Error while rendering page!", e);
}
} | #vulnerable code
public static byte[] render(ReqImpl req, Resp resp) {
Object result = resp.result();
if (result != null) {
result = wrapGuiContent(result);
resp.model().put("result", result);
resp.result(result);
}
ViewRenderer viewRenderer = req.routes().custom().viewRenderer();
U.must(viewRenderer != null, "A view renderer wasn't configured!");
PageRenderer pageRenderer = req.routes().custom().pageRenderer();
U.must(pageRenderer != null, "A page renderer wasn't configured!");
boolean rendered;
String viewName = resp.view();
ByteArrayOutputStream out = new ByteArrayOutputStream();
MVCModel basicModel = new MVCModel(req, resp, resp.model(), resp.screen(), result);
Object[] renderModel = result != null
? new Object[]{basicModel, resp.model(), result}
: new Object[]{basicModel, resp.model()};
try {
rendered = viewRenderer.render(req, viewName, renderModel, out);
} catch (Throwable e) {
throw U.rte("Error while rendering view: " + viewName, e);
}
String renderResult = rendered ? new String(out.toByteArray()) : null;
if (renderResult == null) {
Object cnt = U.or(result, "");
renderResult = new String(HttpUtils.responseToBytes(req, cnt, MediaType.HTML_UTF_8, null));
}
try {
Object response = U.or(pageRenderer.renderPage(req, resp, renderResult), "");
return HttpUtils.responseToBytes(req, response, MediaType.HTML_UTF_8, null);
} catch (Exception e) {
throw U.rte("Error while rendering page!", e);
}
}
#location 37
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers());
} | #vulnerable code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(sdDbServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers());
} | #vulnerable code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(sdWorldServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception{
final String data = "博主邮箱:[email protected]";
byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
InetSocketAddress targetHost = new InetSocketAddress("127.0.0.1", 9999);
// 发送udp内容
DatagramSocket socket = new DatagramSocket();
socket.send(new DatagramPacket(bytes, 0, bytes.length, targetHost));
while (true) {
//接收数据报的包
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
// DatagramSocket localUDPSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket();
// if (localUDPSocket == null || (localUDPSocket.isClosed())) {
// continue;
// }
socket.receive(packet);
//解析发来的数据
String response = new String(packet.getData(), 0, packet.getLength(), CharsetUtil.UTF_8);
utilLogger.debug("收到服务器信息" + response);
}
} | #vulnerable code
public static void main(String[] args) throws Exception{
final String data = "博主邮箱:[email protected]";
byte[] bytes = data.getBytes(Charset.forName("UTF-8"));
InetSocketAddress targetHost = new InetSocketAddress("127.0.0.1", 9999);
// 发送udp内容
DatagramSocket socket = new DatagramSocket();
socket.send(new DatagramPacket(bytes, 0, bytes.length, targetHost));
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers());
} | #vulnerable code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(sdDbServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers());
} | #vulnerable code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(sdWorldServers);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers());
} | #vulnerable code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(sdDbServers);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public void init() throws Exception {
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
} | #vulnerable code
@SuppressWarnings("unchecked")
public void init() throws Exception {
Element rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVER_CONFIG).getFile());
Map<Integer, SdServer> serverMap = new HashMap<>();
List<SdServer> sdWorldServers = new ArrayList<SdServer>();
Element element = rootElement.getChild(BOEnum.WORLD.toString().toLowerCase());
List<Element> childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdWorldServers.add(sdServer);
}
List<SdServer> sdGameServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.GAME.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdGameServers.add(sdServer);
}
List<SdServer> sdDbServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.DB.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdDbServers.add(sdServer);
}
synchronized (this.lock) {
this.sdWorldServers = sdWorldServers;
this.sdGameServers = sdGameServers;
this.sdDbServers = sdDbServers;
}
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
SdRpcServiceProvider sdRpcServiceProvider = new SdRpcServiceProvider();
rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVEICE_CONFIG).getFile());
childrenElements = rootElement.getChildren("service");
for (Element childElement : childrenElements) {
sdRpcServiceProvider.load(childElement);
}
synchronized (this.lock) {
this.sdRpcServiceProvider = sdRpcServiceProvider;
}
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
// Class<?> messageClass = null;
// FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
// if (!defaultClassLoader.isJarLoad()) {
// defaultClassLoader.initClassLoaderPath(realClass, ext);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// } else {
// //读取 game_server_handler.jar包所在位置
// URL url = ClassLoader.getSystemClassLoader().getResource("./");
// File file = new File(url.getPath());
// File parentFile = new File(file.getParent());
// String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
// logger.info("message load jar path:" + jarPath);
// JarFile jarFile = new JarFile(new File(jarPath));
// fileClassLoader.initJarPath(jarFile);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// }
Class<?> messageClass = Class.forName(realClass);
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
} | #vulnerable code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
Class<?> messageClass = null;
FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
if (!defaultClassLoader.isJarLoad()) {
defaultClassLoader.initClassLoaderPath(realClass, ext);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
} else {
//读取 game_server_handler.jar包所在位置
URL url = ClassLoader.getSystemClassLoader().getResource("./");
File file = new File(url.getPath());
File parentFile = new File(file.getParent());
String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
logger.info("message load jar path:" + jarPath);
JarFile jarFile = new JarFile(new File(jarPath));
fileClassLoader.initJarPath(jarFile);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
}
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers());
} | #vulnerable code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(sdGameServers);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public void init() throws Exception {
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
} | #vulnerable code
@SuppressWarnings("unchecked")
public void init() throws Exception {
Element rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVER_CONFIG).getFile());
Map<Integer, SdServer> serverMap = new HashMap<>();
List<SdServer> sdWorldServers = new ArrayList<SdServer>();
Element element = rootElement.getChild(BOEnum.WORLD.toString().toLowerCase());
List<Element> childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdWorldServers.add(sdServer);
}
List<SdServer> sdGameServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.GAME.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdGameServers.add(sdServer);
}
List<SdServer> sdDbServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.DB.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdDbServers.add(sdServer);
}
synchronized (this.lock) {
this.sdWorldServers = sdWorldServers;
this.sdGameServers = sdGameServers;
this.sdDbServers = sdDbServers;
}
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
SdRpcServiceProvider sdRpcServiceProvider = new SdRpcServiceProvider();
rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVEICE_CONFIG).getFile());
childrenElements = rootElement.getChildren("service");
for (Element childElement : childrenElements) {
sdRpcServiceProvider.load(childElement);
}
synchronized (this.lock) {
this.sdRpcServiceProvider = sdRpcServiceProvider;
}
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
// Class<?> messageClass = null;
// FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
// if (!defaultClassLoader.isJarLoad()) {
// defaultClassLoader.initClassLoaderPath(realClass, ext);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// } else {
// //读取 game_server_handler.jar包所在位置
// URL url = ClassLoader.getSystemClassLoader().getResource("./");
// File file = new File(url.getPath());
// File parentFile = new File(file.getParent());
// String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
// logger.info("message load jar path:" + jarPath);
// JarFile jarFile = new JarFile(new File(jarPath));
// fileClassLoader.initJarPath(jarFile);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// }
Class<?> messageClass = Class.forName(realClass);
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
} | #vulnerable code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
Class<?> messageClass = null;
FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
if (!defaultClassLoader.isJarLoad()) {
defaultClassLoader.initClassLoaderPath(realClass, ext);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
} else {
//读取 game_server_handler.jar包所在位置
URL url = ClassLoader.getSystemClassLoader().getResource("./");
File file = new File(url.getPath());
File parentFile = new File(file.getParent());
String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
logger.info("message load jar path:" + jarPath);
JarFile jarFile = new JarFile(new File(jarPath));
fileClassLoader.initJarPath(jarFile);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
}
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers());
} | #vulnerable code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(sdGameServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(rpcConfig.getSdWorldServers());
} | #vulnerable code
public void initWorldConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
worldRpcConnectManager.initServers(sdWorldServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
public void init() throws Exception {
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
} | #vulnerable code
@SuppressWarnings("unchecked")
public void init() throws Exception {
Element rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVER_CONFIG).getFile());
Map<Integer, SdServer> serverMap = new HashMap<>();
List<SdServer> sdWorldServers = new ArrayList<SdServer>();
Element element = rootElement.getChild(BOEnum.WORLD.toString().toLowerCase());
List<Element> childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdWorldServers.add(sdServer);
}
List<SdServer> sdGameServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.GAME.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdGameServers.add(sdServer);
}
List<SdServer> sdDbServers = new ArrayList<SdServer>();
element = rootElement.getChild(BOEnum.DB.toString().toLowerCase());
childrenElements = element.getChildren("server");
for (Element childElement : childrenElements) {
SdServer sdServer = new SdServer();
sdServer.load(childElement);
sdDbServers.add(sdServer);
}
synchronized (this.lock) {
this.sdWorldServers = sdWorldServers;
this.sdGameServers = sdGameServers;
this.sdDbServers = sdDbServers;
}
initWorldConnectedServer();
initGameConnectedServer();
initDbConnectServer();
SdRpcServiceProvider sdRpcServiceProvider = new SdRpcServiceProvider();
rootElement = JdomUtils.getRootElemet(FileUtil.getConfigURL(GlobalConstants.ConfigFile.RPC_SERVEICE_CONFIG).getFile());
childrenElements = rootElement.getChildren("service");
for (Element childElement : childrenElements) {
sdRpcServiceProvider.load(childElement);
}
synchronized (this.lock) {
this.sdRpcServiceProvider = sdRpcServiceProvider;
}
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(rpcConfig.getSdGameServers());
} | #vulnerable code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(sdGameServers);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void initGameConnectedServer() throws Exception {
gameRpcConnecetMananger.initManager();
gameRpcConnecetMananger.initServers(sdGameServers);
} | #vulnerable code
public void initGameConnectedServer() throws Exception {
worldRpcConnectManager.initManager();
gameRpcConnecetMananger.initServers(sdGameServers);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) {
// check the history key (a key is the namespace + id)
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
&& getMappedClass(entity).getEntityAnnotation() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
Object cachedInstance = cache.getEntity(key);
if (cachedInstance != null)
return cachedInstance;
else
cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs
}
//hack to bypass things and just read the value.
if (entity instanceof MappedField) {
readMappedField(dbObject, (MappedField) entity, entity, cache);
return entity;
}
MappedClass mc = getMappedClass(entity);
dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
try {
for (MappedField mf : mc.getPersistenceFields()) {
readMappedField(dbObject, mf, entity, cache);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
cache.putEntity(key, entity);
}
mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
return entity;
} | #vulnerable code
Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) {
// check the history key (a key is the namespace + id)
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
&& getMappedClass(entity).getEntityAnnotation() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
Object cachedInstance = cache.getEntity(key);
if (cachedInstance != null)
return cachedInstance;
else
cache.putEntity(key, entity); // to avoid stackOverflow in
// recursive refs
}
MappedClass mc = getMappedClass(entity);
dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
try {
for (MappedField mf : mc.getPersistenceFields()) {
readMappedField(dbObject, mf, entity, cache);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
cache.putEntity(key, entity);
}
mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
return entity;
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected Object getId(Object entity) {
entity = ProxyHelper.unwrap(entity);
// String keyClassName = entity.getClass().getName();
MappedClass mc = mapr.getMappedClass(entity.getClass());
//
// if (mapr.getMappedClasses().containsKey(keyClassName))
// mc = mapr.getMappedClasses().get(keyClassName);
// else
// mc = new MappedClass(entity.getClass(), getMapper());
//
try {
return mc.getIdField().get(entity);
} catch (Exception e) {
return null;
}
} | #vulnerable code
protected Object getId(Object entity) {
entity = ProxyHelper.unwrap(entity);
MappedClass mc;
String keyClassName = entity.getClass().getName();
if (mapr.getMappedClasses().containsKey(keyClassName))
mc = mapr.getMappedClasses().get(keyClassName);
else
mc = new MappedClass(entity.getClass(), getMapper());
try {
return mc.getIdField().get(entity);
} catch (Exception e) {
return null;
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> Key<T> save(String kind, T entity) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getDB().getCollection(kind);
return save(dbColl, entity, getWriteConcern(entity));
} | #vulnerable code
public <T> Key<T> save(String kind, T entity) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getDB().getCollection(kind);
return save(dbColl, entity, defConcern);
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {
// return save(entities, wc);
final List<DBObject> list = entities instanceof List
? new ArrayList<DBObject>(((List<T>) entities).size())
: new ArrayList<DBObject>();
final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
for (final T ent : entities) {
list.add(toDbObject(involvedObjects, ent));
}
final WriteResult wr = null;
final DBObject[] dbObjects = new DBObject[list.size()];
dbColl.insert(list.toArray(dbObjects), wc);
throwOnError(wc, wr);
final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
final Iterator<T> entitiesIT = entities.iterator();
final Iterator<DBObject> dbObjectsIT = list.iterator();
while (entitiesIT.hasNext()) {
final T entity = entitiesIT.next();
final DBObject dbObj = dbObjectsIT.next();
savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
}
return savedKeys;
} | #vulnerable code
private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {
final List<DBObject> list = entities instanceof List
? new ArrayList<DBObject>(((List<T>) entities).size())
: new ArrayList<DBObject>();
final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
for (final T ent : entities) {
final MappedClass mc = mapper.getMappedClass(ent);
if (mc.getAnnotation(NotSaved.class) != null) {
throw new MappingException(
"Entity type: " + mc.getClazz().getName()
+ " is marked as NotSaved which means you should not try to save it!");
}
list.add(entityToDBObj(ent, involvedObjects));
}
final WriteResult wr = null;
final DBObject[] dbObjects = new DBObject[list.size()];
dbColl.insert(list.toArray(dbObjects), wc);
throwOnError(wc, wr);
final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
final Iterator<T> entitiesIT = entities.iterator();
final Iterator<DBObject> dbObjectsIT = list.iterator();
while (entitiesIT.hasNext()) {
final T entity = entitiesIT.next();
final DBObject dbObj = dbObjectsIT.next();
savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
}
return savedKeys;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) {
//hack to bypass things and just read the value.
if (entity instanceof MappedField) {
readMappedField(dbObject, (MappedField) entity, entity, cache);
return entity;
}
// check the history key (a key is the namespace + id)
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
&& getMappedClass(entity).getEntityAnnotation() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
Object cachedInstance = cache.getEntity(key);
if (cachedInstance != null)
return cachedInstance;
else
cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs
}
MappedClass mc = getMappedClass(entity);
dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
try {
for (MappedField mf : mc.getPersistenceFields()) {
readMappedField(dbObject, mf, entity, cache);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
cache.putEntity(key, entity);
}
mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
return entity;
} | #vulnerable code
Object fromDb(DBObject dbObject, final Object entity, EntityCache cache) {
// check the history key (a key is the namespace + id)
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null
&& getMappedClass(entity).getEntityAnnotation() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
Object cachedInstance = cache.getEntity(key);
if (cachedInstance != null)
return cachedInstance;
else
cache.putEntity(key, entity); // to avoid stackOverflow in recursive refs
}
//hack to bypass things and just read the value.
if (entity instanceof MappedField) {
readMappedField(dbObject, (MappedField) entity, entity, cache);
return entity;
}
MappedClass mc = getMappedClass(entity);
dbObject = (BasicDBObject) mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
try {
for (MappedField mf : mc.getPersistenceFields()) {
readMappedField(dbObject, mf, entity, cache);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
Key key = new Key(entity.getClass(), dbObject.get(ID_KEY));
cache.putEntity(key, entity);
}
mc.callLifecycleMethods(PostLoad.class, entity, dbObject, this);
return entity;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) {
Object mappedValue = value;
//convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity
if (isAssignable(mf, value) || isEntity(mc)) {
try {
if (value instanceof Iterable) {
MappedClass mapped = getMappedClass(mf.getSubClass());
if(mapped != null && Key.class.isAssignableFrom(mapped.getClazz())) {
mappedValue = getDBRefs((Iterable) value);
} else {
mappedValue = value;
}
} else {
final Key<?> key = (value instanceof Key) ? (Key<?>) value : getKey(value);
if (key == null) {
mappedValue = toMongoObject(value, false);
} else {
mappedValue = keyToRef(key);
if (mappedValue == value) {
throw new ValidationException("cannot map to @Reference/Key<T>/DBRef field: " + value);
}
}
}
} catch (Exception e) {
log.error("Error converting value(" + value + ") to reference.", e);
mappedValue = toMongoObject(value, false);
}
} else if (mf != null && mf.hasAnnotation(Serialized.class)) { //serialized
try {
mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression());
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (value instanceof DBObject) { //pass-through
mappedValue = value;
} else {
mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf));
if (mappedValue instanceof BasicDBList) {
final BasicDBList list = (BasicDBList) mappedValue;
if (list.size() != 0) {
if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) {
for (Object o : list) {
if (o instanceof DBObject) {
((DBObject) o).removeField(CLASS_NAME_FIELDNAME);
}
}
}
}
} else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) {
((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME);
}
}
return mappedValue;
} | #vulnerable code
public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) {
Object mappedValue = value;
//convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity
if (isAssignable(mf, value) || isEntity(mc)) {
try {
if (value instanceof Iterable) {
if(isMapped(mf.getSubClass())) {
mappedValue = getDBRefs((Iterable) value);
} else {
mappedValue = value;
}
} else {
final Key<?> key = (value instanceof Key) ? (Key<?>) value : getKey(value);
if (key == null) {
mappedValue = toMongoObject(value, false);
} else {
mappedValue = keyToRef(key);
if (mappedValue == value) {
throw new ValidationException("cannot map to @Reference/Key<T>/DBRef field: " + value);
}
}
}
} catch (Exception e) {
log.error("Error converting value(" + value + ") to reference.", e);
mappedValue = toMongoObject(value, false);
}
} else if (mf != null && mf.hasAnnotation(Serialized.class)) { //serialized
try {
mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression());
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (value instanceof DBObject) { //pass-through
mappedValue = value;
} else {
mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf));
if (mappedValue instanceof BasicDBList) {
final BasicDBList list = (BasicDBList) mappedValue;
if (list.size() != 0) {
if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) {
for (Object o : list) {
if (o instanceof DBObject) {
((DBObject) o).removeField(CLASS_NAME_FIELDNAME);
}
}
}
}
} else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) {
((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME);
}
}
return mappedValue;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) {
if (ent instanceof Query)
return update((Query<T>)ent, ops);
MappedClass mc = mapr.getMappedClass(ent);
Query<T> q = (Query<T>) createQuery(mc.getClazz());
q.disableValidation().filter(Mapper.ID_KEY, getId(ent));
if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) {
MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0);
Long oldVer = (Long)versionMF.getFieldValue(ent);
q.filter(versionMF.getNameToStore(), oldVer);
ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer));
}
return update(q, ops);
} | #vulnerable code
public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) {
MappedClass mc = mapr.getMappedClass(ent);
Query<T> q = (Query<T>) createQuery(mc.getClazz());
q.disableValidation().filter(Mapper.ID_KEY, getId(ent));
if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) {
MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0);
Long oldVer = (Long)versionMF.getFieldValue(ent);
q.filter(versionMF.getNameToStore(), oldVer);
ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer));
}
return update(q, ops);
}
#location 3
#vulnerability type NULL_DEREFERENCE | 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.