input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
downloadedVersion = null;
driverManagerType = null;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
GitHubApi release;
if (driverVersion == null || driverVersion.isEmpty() || driverVersion
.equalsIgnoreCase(DriverVersion.LATEST.name())) {
log.debug(
"Connecting to {} to check latest MarionetteDriver release",
driverUrl);
driverVersion = releaseArray[0].getName();
release = releaseArray[0];
} else {
release = getVersion(releaseArray, driverVersion);
}
if (release == null) {
throw new RuntimeException("Version " + driverVersion
+ " is not available for MarionetteDriver");
}
List<LinkedTreeMap<String, Object>> assets = release.getAssets();
List<URL> urls = new ArrayList<>();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url").toString()));
}
reader.close();
return urls;
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersion(releaseArray, driverVersion) };
}
List<URL> urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(
asset.get("browser_download_url").toString()));
}
}
}
reader.close();
return urls;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new WdmHttpClient.Builder().proxy(proxyValue)
.proxyUser(proxyUser).proxyPass(proxyPass).build();
try (WdmHttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(this, wdmHttpClient);
urlFilter = new UrlFilter();
if (isForcingDownload) {
downloader.forceDownload();
}
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(proxyValue, proxyUser, proxyPass);
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(this, wdmHttpClient);
urlFilter = new UrlFilter();
if (isForcingDownload) {
downloader.forceDownload();
}
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Exception for phantomjs 2.5.0 in Linux
if (IS_OS_LINUX && getDriverName().contains("phantomjs")) {
candidateUrls = filterByDistro(candidateUrls, getDistroName(),
"2.5.0");
}
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.trace("No valid binary found for {} {}", getDriverName(),
versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by architecture and OS
candidateUrls = filterByOs(candidateUrls);
candidateUrls = filterByArch(candidateUrls, arch);
// Extra round of filter phantomjs 2.5.0 in Linux
if (IS_OS_LINUX && getDriverName().contains("phantomjs")) {
candidateUrls = filterByDistro(candidateUrls, getDistroName(),
"2.5.0");
}
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.trace("No valid binary found for {} {}", getDriverName(),
versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getDriverVersionLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static final synchronized void download(URL url, String version,
String export, List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| WdmConfig.getBoolean("wdm.override");
if (!download) {
// Check if existing binary is valid
Collection<File> listFiles = FileUtils
.listFiles(targetFile.getParentFile(), null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (download) {
log.info("Downloading {} to {}", url, targetFile);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.addRequestProperty("Connection", "keep-alive");
conn.connect();
FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
targetFile.delete();
} else {
binary = targetFile;
}
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
public static final synchronized void download(URL url, String version,
String export, List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| WdmConfig.getBoolean("wdm.override");
if (!download) {
// Check if existing binary is valid
Collection<File> listFiles = FileUtils
.listFiles(targetFile.getParentFile(), null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (download) {
log.info("Downloading {} to {}", url, targetFile);
HttpURLConnection conn = getConnection(url);
int responseCode = conn.getResponseCode();
log.debug("Response HTTP {}", responseCode);
if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
// HTTP Redirect
URL newUrl = new URL(conn.getHeaderField("Location"));
log.debug("Redirect to {}", newUrl);
conn = getConnection(newUrl);
}
FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
targetFile.delete();
} else {
binary = targetFile;
}
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 50
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// For Chromium snap
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// For Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 47
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
if (!config.isAvoidPreferences()) {
storeVersionToDownload(version);
}
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
if (!config.isAvoidPreferences()) {
storeVersionToDownload(version);
}
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected String resolveDriverVersion(String driverVersion) {
preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(driverVersion, browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected String resolveDriverVersion(String driverVersion) {
String preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(preferenceKey, browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(preferenceKey, driverVersion,
browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isLatest = true;
isSnap = false;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
config().reset();
mirrorLog = false;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isSnap = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retry = true;
isLatest = true;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isLatest = true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected String download(String driverVersion) throws IOException {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = String.format(
"%s %s for %s %s not found in %s", getDriverName(),
getLabel(driverVersion), os, arch.toString(),
getDriverUrl());
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
return downloader.download(url, versionToDownload, getDriverName());
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected String download(String driverVersion) throws IOException {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = String.format(
"%s %s for %s %s not found in %s", getDriverName(),
getDriverVersionLabel(driverVersion), os, arch.toString(),
getDriverUrl());
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
return downloader.download(url, driverVersionToDownload,
getDriverName());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
Optional<String> optionalBrowserVersion = config()
.isAvoidAutoVersion() ? empty() : getBrowserVersion();
if (optionalBrowserVersion.isPresent()) {
String browserVersion = optionalBrowserVersion.get();
preferenceKey = getDriverManagerType().name().toLowerCase()
+ browserVersion;
if (getLatest && !config.isOverride()
&& !config().isAvoidAutoVersion()
&& !config().isAvoidPreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
version = preferences
.getValueFromPreferences(preferenceKey);
} else {
version = getVersionForInstalledBrowser(
getDriverManagerType());
}
getLatest = version.isEmpty();
}
}
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
getLatest = isNullOrEmpty(version);
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
useBeta = config().isUseBetaVersions();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected List<File> getFilesInCache() {
List<File> listFiles = (List<File>) listFiles(
new File(downloader.getTargetPath()), null, true);
sort(listFiles);
return listFiles;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected List<File> getFilesInCache() {
List<File> listFiles = (List<File>) listFiles(
new File(config.getTargetPath()), null, true);
sort(listFiles);
return listFiles;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected Optional<String> getDefaultBrowserVersion(String programFilesEnv,
String winBrowserName, String linuxBrowserName,
String macBrowserName, String versionFlag,
String browserNameInOutput) {
if (IS_OS_WINDOWS) {
String programFiles = System.getenv(programFilesEnv)
.replaceAll("\\\\", "\\\\\\\\");
String browserPath = browserBinaryPath != null ? browserBinaryPath
: programFiles + winBrowserName;
String browserVersionOutput = runAndWait(getExecFile(), "wmic",
"datafile", "where", "name='" + browserPath + "'", "get",
"Version", "/value");
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional
.of(getVersionFromWmicOutput(browserVersionOutput));
}
} else if (IS_OS_LINUX || IS_OS_MAC) {
String browserPath;
if (browserBinaryPath != null) {
browserPath = browserBinaryPath;
} else {
browserPath = IS_OS_LINUX ? linuxBrowserName : macBrowserName;
}
String browserVersionOutput = runAndWait(browserPath, versionFlag);
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional.of(getVersionFromPosixOutput(
browserVersionOutput, browserNameInOutput));
}
}
return empty();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected Optional<String> getDefaultBrowserVersion(String programFilesEnv,
String winBrowserName, String linuxBrowserName,
String macBrowserName, String versionFlag,
String browserNameInOutput) {
String browserBinaryPath = config().getBinaryPath();
if (IS_OS_WINDOWS) {
String programFiles = System.getenv(programFilesEnv)
.replaceAll("\\\\", "\\\\\\\\");
String browserPath = browserBinaryPath != null ? browserBinaryPath
: programFiles + winBrowserName;
String browserVersionOutput = runAndWait(getExecFile(), "wmic",
"datafile", "where", "name='" + browserPath + "'", "get",
"Version", "/value");
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional
.of(getVersionFromWmicOutput(browserVersionOutput));
}
} else if (IS_OS_LINUX || IS_OS_MAC) {
String browserPath;
if (browserBinaryPath != null) {
browserPath = browserBinaryPath;
} else {
browserPath = IS_OS_LINUX ? linuxBrowserName : macBrowserName;
}
String browserVersionOutput = runAndWait(browserPath, versionFlag);
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional.of(getVersionFromPosixOutput(
browserVersionOutput, browserNameInOutput));
}
}
return empty();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void storeVersionToDownload(String driverVersion) {
if (!isUnknown(driverVersion)) {
if (driverVersion.startsWith(".")) {
driverVersion = driverVersion.substring(1);
}
versionToDownload = driverVersion;
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void storeVersionToDownload(String driverVersion) {
if (!isUnknown(driverVersion)) {
if (driverVersion.startsWith(".")) {
driverVersion = driverVersion.substring(1);
}
driverVersionToDownload = driverVersion;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reset() {
useBetaVersions = getBoolean("wdm.useBetaVersions");
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
versionToDownload = null;
version = null;
proxyValue = null;
binaryPath = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
useBetaVersions = false;
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
version = null;
proxyValue = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getProxyValue(),
config().getProxyUser(), config().getProxyPass());
httpClient.setTimeout(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = config().isForcingCache() || !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
version, driverInCache.get());
exportDriver(config().getExportParameter(exportParameterKey),
driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + config().getMyOsName() + arch.toString()
+ " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
e.printStackTrace();
handleException(e, arch, version);
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getProxyValue(),
config().getProxyUser(), config().getProxyPass());
httpClient.setTimeout(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = config().isForcingCache() || !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
version, driverInCache.get());
exportDriver(config().getExportParameter(exportParameterKey),
driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + config().getMyOsName() + arch.toString()
+ " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void manage(Architecture arch, String version) {
try {
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(DriverVersion.LATEST.name())
|| version.equalsIgnoreCase(
DriverVersion.NOT_SPECIFIED.name());
String driverInCache = null;
if (!getLatest) {
driverInCache = existsDriverInCache(Downloader.getTargetPath(),
getDriverName(), version);
}
if (driverInCache != null) {
System.setProperty(VERSION_PROPERTY, version);
exportDriver(getExportParameter(), driverInCache);
} else {
// Get the complete list of URLs
List<URL> urls = getDrivers();
if (!urls.isEmpty()) {
List<URL> candidateUrls;
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
if (getLatest) {
candidateUrls = getLatest(urls, getDriverName());
} else {
candidateUrls = getVersion(urls, getDriverName(),
version);
}
if (versionToDownload == null) {
break;
}
if (this.getClass().equals(EdgeDriverManager.class)) {
// Microsoft Edge binaries are different
continueSearchingVersion = false;
} else {
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty()
&& getLatest;
if (continueSearchingVersion) {
log.debug("No valid binary found for {} {}",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
}
} while (continueSearchingVersion);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errMessage = getDriverName() + " " + versionStr
+ " for " + MY_OS_NAME + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errMessage);
throw new RuntimeException(errMessage);
}
for (URL url : candidateUrls) {
String export = candidateUrls.contains(url)
? getExportParameter() : null;
System.setProperty(VERSION_PROPERTY, versionToDownload);
Downloader.download(url, versionToDownload, export,
getDriverName());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 72
#vulnerability type NULL_DEREFERENCE | #fixed code
public void manage(Architecture arch, String version) {
try {
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(DriverVersion.LATEST.name())
|| version.equalsIgnoreCase(
DriverVersion.NOT_SPECIFIED.name());
String driverInCache = null;
if (!getLatest) {
versionToDownload = version;
driverInCache = existsDriverInCache(Downloader.getTargetPath(),
getDriverName(), version);
}
if (driverInCache != null) {
System.setProperty(VERSION_PROPERTY, version);
exportDriver(getExportParameter(), driverInCache);
} else {
// Get the complete list of URLs
List<URL> urls = getDrivers();
if (!urls.isEmpty()) {
List<URL> candidateUrls;
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
if (getLatest) {
candidateUrls = getLatest(urls, getDriverName());
} else {
candidateUrls = getVersion(urls, getDriverName(),
version);
}
if (versionToDownload == null) {
break;
}
log.trace("All URLS: {}", urls);
log.trace("Candidate URLS: {}", candidateUrls);
if (this.getClass().equals(EdgeDriverManager.class)) {
// Microsoft Edge binaries are different
continueSearchingVersion = false;
} else {
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty()
&& getLatest;
if (continueSearchingVersion) {
log.debug("No valid binary found for {} {}",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
}
} while (continueSearchingVersion);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errMessage = getDriverName() + " " + versionStr
+ " for " + MY_OS_NAME + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errMessage);
throw new RuntimeException(errMessage);
}
for (URL url : candidateUrls) {
String export = candidateUrls.contains(url)
? getExportParameter() : null;
System.setProperty(VERSION_PROPERTY, versionToDownload);
Downloader.download(url, versionToDownload, export,
getDriverName());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void exportDriver(String variableValue) {
driverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void exportDriver(String variableValue) {
downloadedDriverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected String getTargetPath() {
String path = (String) resolveConfigKey("wdm.targetPath", targetPath);
if (path.contains(HOME)) {
path = path.replace(HOME, System.getProperty("user.home"));
}
return path;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
protected String getTargetPath() {
String path = null;
Object resolved = resolveConfigKey("wdm.targetPath", targetPath);
if (resolved != null) {
path = (String) resolved;
if (path.contains(HOME)) {
path = path.replace(HOME, System.getProperty("user.home"));
}
}
return path;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testServer() throws IOException {
String serverUrl = String.format("http://localhost:%s/%s", serverPort,
path);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(serverUrl).build();
Response response = client.newCall(request).execute();
assertTrue(response.isSuccessful());
ResponseBody body = response.body();
log.debug("Content-Type {}", body.contentType());
log.debug("Content-Length {}", body.contentLength());
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testServer() throws IOException {
String serverUrl = String.format("http://localhost:%s/%s", serverPort,
path);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(serverUrl).build();
// Assert response
Response response = client.newCall(request).execute();
assertTrue(response.isSuccessful());
// Assert attachment
String attachment = String.format("attachment; filename=\"%s\"",
driver);
assertTrue(response.headers().values("Content-Disposition")
.contains(attachment));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isSnap = false;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void reset() {
config().reset();
mirrorLog = false;
driverVersionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isSnap = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void downloadAndExport(String driverVersion) throws IOException {
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String versionStr = isUnknown(driverVersion) ? "(latest version)"
: driverVersion;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(driverVersion);
downloadedVersion = driverVersion;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
String exportValue = downloader.download(url, versionToDownload,
getDriverName());
exportDriver(exportValue);
downloadedVersion = versionToDownload;
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void downloadAndExport(String driverVersion) throws IOException {
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String versionStr = isUnknown(driverVersion) ? "(latest version)"
: driverVersion;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(driverVersion);
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
String exportValue = downloader.download(url, versionToDownload,
getDriverName());
exportDriver(exportValue);
}
downloadedVersion = versionToDownload;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
logger.info("Exiting...");
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
try (final GeneratorScheduler scheduler = new GeneratorScheduler(Duration.ofSeconds(1))) {
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
apps.add(simpleDataApplication("data-1", scheduler, "sine", sine(100, 0, ofSeconds(120))));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
}
logger.info("Exiting...");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(final String... args) throws Throwable {
toInfinityAndBeyond();
final Options opts = new Options();
opts.addOption("n", "basename", true, "The base name of the simulator instance");
opts.addOption(null, "name-factory", true, "The name factory to use");
opts.addOption("c", "count", true, "The number of instances to start");
opts.addOption("h", "broker-host", true, "The broker's host");
opts.addOption("b", "broker", true, "The URL to the broker");
opts.addOption("a", "account-name", true, "The name of the account");
opts.addOption("s", "shutdown", true, "Shutdown simulator after x seconds");
final CommandLine cli = new DefaultParser().parse(opts, args);
final String basename = replace(cli.getOptionValue('n', env("KSIM_BASE_NAME", "sim-")));
final String nameFactoryName = cli.getOptionValue("name-factory", env("KSIM_NAME_FACTORY", null));
final int count = Integer.parseInt(replace(cli.getOptionValue('c', env("KSIM_NUM_GATEWAYS", "1"))));
final String brokerHost = replace(cli.getOptionValue("bh"));
final String broker = replace(cli.getOptionValue('b', createBrokerUrl(Optional.ofNullable(brokerHost))));
final String accountName = replace(cli.getOptionValue('a', env("KSIM_ACCOUNT_NAME", "kapua-sys")));
final long shutdownAfter = Long
.parseLong(replace(cli.getOptionValue('s', Long.toString(Long.MAX_VALUE / 1_000L))));
dumpEnv();
logger.info("Starting simulation ...");
logger.info("\tbasename : {}", basename);
logger.info("\tname-factory : {}", nameFactoryName);
logger.info("\tcount: {}", count);
logger.info("\tbroker: {}", broker);
logger.info("\taccount-name: {}", accountName);
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final List<AutoCloseable> close = new LinkedList<>();
final NameFactory nameFactory = createNameFactory(nameFactoryName)
.orElseGet(() -> NameFactories.prefixed(basename));
try {
for (int i = 1; i <= count; i++) {
final String name = nameFactory.generateName(i);
logger.info("Creating instance #{} - {}", i, name);
final GatewayConfiguration configuration = new GatewayConfiguration(broker, accountName, name);
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
close.add(transport);
final Simulator simulator = new Simulator(configuration, transport, apps);
close.add(simulator);
}
Thread.sleep(shutdownAfter * 1_000L);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
closeAll(close);
}
logger.info("Exiting...");
}
#location 52
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(final String... args) throws Throwable {
toInfinityAndBeyond();
final Options opts = new Options();
opts.addOption(
builder("n")
.longOpt("basename")
.hasArg().argName("BASENAME")
.desc("The base name of the simulator instance")
.build());
opts.addOption(
builder()
.longOpt("name-factory")
.hasArg().argName("FACTORY")
.desc("The name factory to use")
.build());
opts.addOption(
builder("c")
.longOpt("count")
.hasArg().argName("COUNT")
.type(Integer.class)
.desc("The number of instances to start")
.build());
opts.addOption(
builder("a")
.longOpt("account-name")
.hasArg().argName("NAME")
.desc("The name of the account (defaults to 'kapua-sys')")
.build());
opts.addOption(
builder("s")
.longOpt("seconds")
.hasArg().argName("SECONDS")
.type(Long.class)
.desc("Shutdown simulator after <SECONDS> seconds")
.build());
opts.addOption("?", "help", false, null);
{
final OptionGroup broker = new OptionGroup();
broker.setRequired(false);
broker.addOption(
builder("h")
.longOpt("broker-host")
.hasArg().argName("HOST")
.desc("Only the hostname of the broker, used for building the full URL")
.build());
broker.addOption(
builder("b")
.longOpt("broker")
.hasArg().argName("URL")
.desc("The full URL to the broker").build());
opts.addOptionGroup(broker);
}
{
final OptionGroup logging = new OptionGroup();
logging.setRequired(false);
logging.addOption(builder("q").longOpt("quiet").desc("Suppress output").build());
logging.addOption(builder("v").longOpt("verbose").desc("Show more output").build());
logging.addOption(builder("d").longOpt("debug").desc("Show debug output").build());
opts.addOptionGroup(logging);
}
final CommandLine cli;
try {
cli = new DefaultParser().parse(opts, args);
} catch (final ParseException e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
return;
}
if (cli.hasOption('?')) {
showHelp(opts);
System.exit(0);
}
setupLogging(cli);
final String basename = replace(cli.getOptionValue('n', env("KSIM_BASE_NAME", "sim-")));
final String nameFactoryName = cli.getOptionValue("name-factory", env("KSIM_NAME_FACTORY", null));
final int count = Integer.parseInt(replace(cli.getOptionValue('c', env("KSIM_NUM_GATEWAYS", "1"))));
final String brokerHost = replace(cli.getOptionValue("bh"));
final String broker = replace(cli.getOptionValue('b', createBrokerUrl(Optional.ofNullable(brokerHost))));
final String accountName = replace(cli.getOptionValue('a', env("KSIM_ACCOUNT_NAME", "kapua-sys")));
final long shutdownAfter = Long
.parseLong(replace(cli.getOptionValue('s', Long.toString(Long.MAX_VALUE / 1_000L))));
dumpEnv();
logger.info("Starting simulation ...");
logger.info("\tbasename : {}", basename);
logger.info("\tname-factory : {}", nameFactoryName);
logger.info("\tcount: {}", count);
logger.info("\tbroker: {}", broker);
logger.info("\taccount-name: {}", accountName);
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final List<AutoCloseable> close = new LinkedList<>();
final NameFactory nameFactory = createNameFactory(nameFactoryName)
.orElseGet(() -> NameFactories.prefixed(basename));
try {
for (int i = 1; i <= count; i++) {
final String name = nameFactory.generateName(i);
logger.info("Creating instance #{} - {}", i, name);
final GatewayConfiguration configuration = new GatewayConfiguration(broker, accountName, name);
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
close.add(transport);
final Simulator simulator = new Simulator(configuration, transport, apps);
close.add(simulator);
}
Thread.sleep(shutdownAfter * 1_000L);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
closeAll(close);
}
logger.info("Exiting...");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String authCode = req.getParameter("code");
String uri = "http://localhost:9090/auth/realms/master/protocol/openid-connect/token";
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=console&redirect_uri=" + callbackUrl;
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
resp.sendRedirect("http://localhost:8889/console.jsp?gwt.codesvr=127.0.0.1:9997&access_token=" + accessToken);
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ConsoleSetting settings = ConsoleSetting.getInstance();
String authCode = req.getParameter("code");
String uri = settings.getString(ConsoleSettingKeys.SSO_OPENID_SERVER_ENDPOINT_TOKEN);
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_CLIENT_ID) + "&redirect_uri=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_REDIRECT_URI);
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
String baseUri = settings.getString(ConsoleSettingKeys.SITE_HOME_URI);
String separator = baseUri.contains("?") ? "&" : "?";
resp.sendRedirect(baseUri + separator + "access_token=" + accessToken);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
logger.info("Exiting...");
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
try (final GeneratorScheduler scheduler = new GeneratorScheduler(Duration.ofSeconds(1))) {
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
apps.add(simpleDataApplication("data-1", scheduler, "sine", sine(100, 0, ofSeconds(120))));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
}
logger.info("Exiting...");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 35
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 92
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 137
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String authCode = req.getParameter("code");
String uri = "http://localhost:9090/auth/realms/master/protocol/openid-connect/token";
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=console&redirect_uri=" + callbackUrl;
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
resp.sendRedirect("http://localhost:8889/console.jsp?gwt.codesvr=127.0.0.1:9997&access_token=" + accessToken);
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ConsoleSetting settings = ConsoleSetting.getInstance();
String authCode = req.getParameter("code");
String uri = settings.getString(ConsoleSettingKeys.SSO_OPENID_SERVER_ENDPOINT_TOKEN);
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_CLIENT_ID) + "&redirect_uri=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_REDIRECT_URI);
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
String baseUri = settings.getString(ConsoleSettingKeys.SITE_HOME_URI);
String separator = baseUri.contains("?") ? "&" : "?";
resp.sendRedirect(baseUri + separator + "access_token=" + accessToken);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
int nblocks = blockIds.length;
if (modifiesInedges) {
int startStreamBlock = rangeStartEdgePtr / blocksize;
for(int i=0; i < nblocks; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
if (i >= startStreamBlock) {
// Synchronous write
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
} else {
// Asynchronous write (not implemented yet, so is same as synchronous)
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
} else if (modifiesOutedges) {
int last = streamingOffsetEdgePtr;
if (last == 0) {
last = edataFilesize;
}
int startblock = (int) (rangeStartEdgePtr / blocksize);
int endblock = (int) (last / blocksize);
for(int i=startblock; i <= endblock; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
/* Release all blocks */
for(Integer blockId : blockIds) {
dataBlockManager.release(blockId);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
loadAdj();
edataFilesize = (int) new File(edgeDataFilename).length();
blockId = dataBlockManager.allocateBlock(edataFilesize);
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockId, edataPtr, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockId, edataPtr, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
/* Load the edge data from file. Should be done asynchronously. */
if (!loaded) {
int read = 0;
FileInputStream fdis = new FileInputStream(new File(edgeDataFilename));
while (read < edataFilesize) {
read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read);
}
loaded = true;
}
}
#location 90
#vulnerability type RESOURCE_LEAK | #fixed code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
blocksize = ChiFilenames.getBlocksize(converter.sizeOf());
loadAdj();
loadEdata();
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
int nblocks = blockIds.length;
if (modifiesInedges) {
int startStreamBlock = rangeStartEdgePtr / blocksize;
for(int i=0; i < nblocks; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
if (i >= startStreamBlock) {
// Synchronous write
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
} else {
// Asynchronous write (not implemented yet, so is same as synchronous)
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
} else if (modifiesOutedges) {
int last = streamingOffsetEdgePtr;
if (last == 0) {
last = edataFilesize;
}
int startblock = (int) (rangeStartEdgePtr / blocksize);
int endblock = (int) (last / blocksize);
for(int i=startblock; i <= endblock; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
/* Release all blocks */
for(Integer blockId : blockIds) {
dataBlockManager.release(blockId);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
loadAdj();
edataFilesize = (int) new File(edgeDataFilename).length();
blockId = dataBlockManager.allocateBlock(edataFilesize);
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockId, edataPtr, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockId, edataPtr, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
/* Load the edge data from file. Should be done asynchronously. */
if (!loaded) {
int read = 0;
FileInputStream fdis = new FileInputStream(new File(edgeDataFilename));
while (read < edataFilesize) {
read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read);
}
loaded = true;
}
}
#location 84
#vulnerability type RESOURCE_LEAK | #fixed code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
blocksize = ChiFilenames.getBlocksize(converter.sizeOf());
loadAdj();
loadEdata();
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.flush();
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.flush();
rFile.close();
}
dataBlockManager.release(blockId);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.flush();
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.flush();
rFile.close();
}
dataBlockManager.release(blockId);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
int nblocks = blockIds.length;
if (modifiesInedges) {
int startStreamBlock = rangeStartEdgePtr / blocksize;
for(int i=0; i < nblocks; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
if (i >= startStreamBlock) {
// Synchronous write
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
} else {
// Asynchronous write (not implemented yet, so is same as synchronous)
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
} else if (modifiesOutedges) {
int last = streamingOffsetEdgePtr;
if (last == 0) {
last = edataFilesize;
}
int startblock = (int) (rangeStartEdgePtr / blocksize);
int endblock = (int) (last / blocksize);
for(int i=startblock; i <= endblock; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
/* Release all blocks */
for(Integer blockId : blockIds) {
dataBlockManager.release(blockId);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void send() throws Exception {
logger.debug("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + message + "\"");
if ((message == null) || (endpoint == null)) {
logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint + "\" message=\"" + message + "\"");
throw new Exception("Message and Endpoint must both be set");
}
HttpPost httpPost = new HttpPost(endpoint);
StringEntity stringEntity = new StringEntity(message);
httpPost.setEntity(stringEntity);
composeHeader(httpPost);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// accept all 2xx status codes
if (statusCode > 200 || statusCode >= 300) {
if (entity != null) {
InputStream instream = entity.getContent();
InputStreamReader responseReader = new InputStreamReader(instream);
StringBuffer buffer = new StringBuffer();
char []arr = new char[1024];
int size = 0;
while ((size = responseReader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, size);
}
instream.close();
}
logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode);
throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"), "Unreachable endpoint " + endpoint + " returns status code " + statusCode);
} else {
if (entity != null) {
EntityUtils.consume(entity);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void send() throws Exception {
if ((message == null) || (endpoint == null)) {
logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint + "\" message=\"" + message + "\"");
throw new Exception("Message and Endpoint must both be set");
}
HttpPost httpPost = new HttpPost(endpoint);
String msg = null;
if (message.getMessageStructure() == CNSMessageStructure.json) {
msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http);
} else {
msg = message.getMessage();
}
if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http);
}
logger.info("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\"");
StringEntity stringEntity = new StringEntity(msg);
httpPost.setEntity(stringEntity);
composeHeader(httpPost);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// accept all 2xx status codes
if (statusCode > 200 || statusCode >= 300) {
if (entity != null) {
InputStream instream = entity.getContent();
InputStreamReader responseReader = new InputStreamReader(instream);
StringBuffer buffer = new StringBuffer();
char []arr = new char[1024];
int size = 0;
while ((size = responseReader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, size);
}
instream.close();
}
logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode);
throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"), "Unreachable endpoint " + endpoint + " returns status code " + statusCode);
} else {
if (entity != null) {
EntityUtils.consume(entity);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String topicArn = request.getParameter("topicArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(userId);
out.println("<html>");
simpleHeader(request, out, "View/Edit Topic Delivery Policy");
if (params.containsKey("Update")) {
String numRetries = request.getParameter("numRetries");
String retriesNoDelay = request.getParameter("retriesNoDelay");
String minDelay = request.getParameter("minDelay");
String minDelayRetries = request.getParameter("minDelayRetries");
String maxDelay = request.getParameter("maxDelay");
String maxDelayRetries = request.getParameter("maxDelayRetries");
String maxReceiveRate = request.getParameter("maxReceiveRate");
String backoffFunc = request.getParameter("backoffFunc");
String ignoreOverride = request.getParameter("ignoreOverride");
CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy();
CNSRetryPolicy defaultHealthyRetryPolicy = new CNSRetryPolicy();
if (maxDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMaxDelayTarget(Integer.parseInt(maxDelay));
}
if (minDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMinDelayTarget(Integer.parseInt(minDelay));
}
if (maxDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMaxDelayRetries(Integer.parseInt(maxDelayRetries));
}
if (minDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMinDelayRetries(Integer.parseInt(minDelayRetries));
}
if (retriesNoDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumNoDelayRetries(Integer.parseInt(retriesNoDelay));
}
if (numRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumRetries(Integer.parseInt(numRetries));
}
defaultHealthyRetryPolicy.setBackOffFunction(CnsBackoffFunction.valueOf(backoffFunc));
deliveryPolicy.setDefaultHealthyRetryPolicy(defaultHealthyRetryPolicy);
deliveryPolicy.setDisableSubscriptionOverrides(ignoreOverride != null ? true: false);
CNSThrottlePolicy defaultThrottle = new CNSThrottlePolicy();
if (maxReceiveRate.trim().length() > 0) {
defaultThrottle.setMaxReceivesPerSecond(Integer.parseInt(maxReceiveRate));
}
deliveryPolicy.setDefaultThrottlePolicy(defaultThrottle );
try {
SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest(topicArn, "DeliveryPolicy", deliveryPolicy.toString());
sns.setTopicAttributes(setTopicAttributesRequest);
logger.debug("event=set_delivery_policy topic_arn=" + topicArn + " userId= " + userId);
} catch (Exception ex) {
logger.error("event=set_delivery_policy user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
int numRetries=0, retriesNoDelay = 0, minDelay = 0, minDelayRetries = 0, maxDelay = 0, maxDelayRetries = 0, maxReceiveRate = 0;
String retryBackoff = "linear";
boolean ignoreOverride = false;
if (topicArn != null) {
Map<String, String> attributes = null;
CNSTopicDeliveryPolicy deliveryPolicy = null;
try {
GetTopicAttributesRequest getTopicAttributesRequest = new GetTopicAttributesRequest(topicArn);
GetTopicAttributesResult getTopicAttributesResult = sns.getTopicAttributes(getTopicAttributesRequest);
attributes = getTopicAttributesResult.getAttributes();
deliveryPolicy = new CNSTopicDeliveryPolicy(new JSONObject(attributes.get("DeliveryPolicy")));
} catch (Exception ex) {
logger.error("event=failed_to_get_attributes arn=" + topicArn, ex);
throw new ServletException(ex);
}
if (deliveryPolicy != null) {
CNSRetryPolicy healPol = deliveryPolicy.getDefaultHealthyRetryPolicy();
if (healPol != null) {
numRetries= healPol.getNumRetries();
retriesNoDelay = healPol.getNumNoDelayRetries();
minDelay = healPol.getMinDelayTarget();
minDelayRetries = healPol.getNumMinDelayRetries();
maxDelay = healPol.getMaxDelayTarget();
maxDelayRetries = healPol.getNumMaxDelayRetries();
retryBackoff = healPol.getBackOffFunction().toString();
}
CNSThrottlePolicy throttlePol = deliveryPolicy.getDefaultThrottlePolicy();
if (throttlePol != null) {
if (throttlePol.getMaxReceivesPerSecond() != null) {
maxReceiveRate = throttlePol.getMaxReceivesPerSecond().intValue();
}
}
ignoreOverride = deliveryPolicy.isDisableSubscriptionOverrides();
}
}
out.println("<body>");
out.println("<h1>View/Edit Topic Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/editdeliverypolicy?topicArn="+topicArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table>");
out.println("<tr><td colspan=2><b><font color='orange'>Delivery Policy</font></b></td></tr>");
out.println("<tr><td colspan=2><b>Apply these delivery policies for the topic:</b></td></tr>");
out.println("<tr><td>Number of retries:</td><td><input type='text' name='numRetries' size='50' value='" + numRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between 0 - 100</font></I></td></tr>");
out.println("<tr><td>Retries with no delay:</td><td><input type='text' name='retriesNoDelay' size='50' value='" + retriesNoDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Minimum delay:</td><td><input type='text' name='minDelay' size='50' value='" + minDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds.Between 0 - maximum delay</font></I></td></tr>");
out.println("<tr><td>Minimum delay retries:</td><td><input type='text' name='minDelayRetries' size='50' value='" + minDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum delay:</td><td><input type='text' name='maxDelay' size='50' value='" + maxDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds. Between minimum delay - 3600</font></I></td></tr>");
out.println("<tr><td>Maximum delay retries:</td><td><input type='text' name='maxDelayRetries' size='50' value='" + maxDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum receive rate:</td><td><input type='text' name='maxReceiveRate' size='50' value='" + maxReceiveRate + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Receives per second. >= 1</font></I></td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
if (retryBackoff.equals("linear")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear' selected>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("arithmetic")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic' selected>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("geometric")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric' selected>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("exponential")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential' selected>Exponential</option></select></td></tr>");
}
if (ignoreOverride) {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride' checked></td></tr>");
} else {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride'></td></tr>");
}
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
#location 117
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String topicArn = request.getParameter("topicArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(request);
out.println("<html>");
simpleHeader(request, out, "View/Edit Topic Delivery Policy");
if (params.containsKey("Update")) {
String numRetries = request.getParameter("numRetries");
String retriesNoDelay = request.getParameter("retriesNoDelay");
String minDelay = request.getParameter("minDelay");
String minDelayRetries = request.getParameter("minDelayRetries");
String maxDelay = request.getParameter("maxDelay");
String maxDelayRetries = request.getParameter("maxDelayRetries");
String maxReceiveRate = request.getParameter("maxReceiveRate");
String backoffFunc = request.getParameter("backoffFunc");
String ignoreOverride = request.getParameter("ignoreOverride");
CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy();
CNSRetryPolicy defaultHealthyRetryPolicy = new CNSRetryPolicy();
if (maxDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMaxDelayTarget(Integer.parseInt(maxDelay));
}
if (minDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMinDelayTarget(Integer.parseInt(minDelay));
}
if (maxDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMaxDelayRetries(Integer.parseInt(maxDelayRetries));
}
if (minDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMinDelayRetries(Integer.parseInt(minDelayRetries));
}
if (retriesNoDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumNoDelayRetries(Integer.parseInt(retriesNoDelay));
}
if (numRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumRetries(Integer.parseInt(numRetries));
}
defaultHealthyRetryPolicy.setBackOffFunction(CnsBackoffFunction.valueOf(backoffFunc));
deliveryPolicy.setDefaultHealthyRetryPolicy(defaultHealthyRetryPolicy);
deliveryPolicy.setDisableSubscriptionOverrides(ignoreOverride != null ? true: false);
CNSThrottlePolicy defaultThrottle = new CNSThrottlePolicy();
if (maxReceiveRate.trim().length() > 0) {
defaultThrottle.setMaxReceivesPerSecond(Integer.parseInt(maxReceiveRate));
}
deliveryPolicy.setDefaultThrottlePolicy(defaultThrottle );
try {
SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest(topicArn, "DeliveryPolicy", deliveryPolicy.toString());
sns.setTopicAttributes(setTopicAttributesRequest);
logger.debug("event=set_delivery_policy topic_arn=" + topicArn + " userId= " + userId);
} catch (Exception ex) {
logger.error("event=set_delivery_policy user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
int numRetries=0, retriesNoDelay = 0, minDelay = 0, minDelayRetries = 0, maxDelay = 0, maxDelayRetries = 0, maxReceiveRate = 0;
String retryBackoff = "linear";
boolean ignoreOverride = false;
if (topicArn != null) {
Map<String, String> attributes = null;
CNSTopicDeliveryPolicy deliveryPolicy = null;
try {
GetTopicAttributesRequest getTopicAttributesRequest = new GetTopicAttributesRequest(topicArn);
GetTopicAttributesResult getTopicAttributesResult = sns.getTopicAttributes(getTopicAttributesRequest);
attributes = getTopicAttributesResult.getAttributes();
deliveryPolicy = new CNSTopicDeliveryPolicy(new JSONObject(attributes.get("DeliveryPolicy")));
} catch (Exception ex) {
logger.error("event=failed_to_get_attributes arn=" + topicArn, ex);
throw new ServletException(ex);
}
if (deliveryPolicy != null) {
CNSRetryPolicy healPol = deliveryPolicy.getDefaultHealthyRetryPolicy();
if (healPol != null) {
numRetries= healPol.getNumRetries();
retriesNoDelay = healPol.getNumNoDelayRetries();
minDelay = healPol.getMinDelayTarget();
minDelayRetries = healPol.getNumMinDelayRetries();
maxDelay = healPol.getMaxDelayTarget();
maxDelayRetries = healPol.getNumMaxDelayRetries();
retryBackoff = healPol.getBackOffFunction().toString();
}
CNSThrottlePolicy throttlePol = deliveryPolicy.getDefaultThrottlePolicy();
if (throttlePol != null) {
if (throttlePol.getMaxReceivesPerSecond() != null) {
maxReceiveRate = throttlePol.getMaxReceivesPerSecond().intValue();
}
}
ignoreOverride = deliveryPolicy.isDisableSubscriptionOverrides();
}
}
out.println("<body>");
out.println("<h1>View/Edit Topic Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/editdeliverypolicy?topicArn="+topicArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table>");
out.println("<tr><td colspan=2><b><font color='orange'>Delivery Policy</font></b></td></tr>");
out.println("<tr><td colspan=2><b>Apply these delivery policies for the topic:</b></td></tr>");
out.println("<tr><td>Number of retries:</td><td><input type='text' name='numRetries' size='50' value='" + numRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between 0 - 100</font></I></td></tr>");
out.println("<tr><td>Retries with no delay:</td><td><input type='text' name='retriesNoDelay' size='50' value='" + retriesNoDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Minimum delay:</td><td><input type='text' name='minDelay' size='50' value='" + minDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds.Between 0 - maximum delay</font></I></td></tr>");
out.println("<tr><td>Minimum delay retries:</td><td><input type='text' name='minDelayRetries' size='50' value='" + minDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum delay:</td><td><input type='text' name='maxDelay' size='50' value='" + maxDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds. Between minimum delay - 3600</font></I></td></tr>");
out.println("<tr><td>Maximum delay retries:</td><td><input type='text' name='maxDelayRetries' size='50' value='" + maxDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum receive rate:</td><td><input type='text' name='maxReceiveRate' size='50' value='" + maxReceiveRate + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Receives per second. >= 1</font></I></td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
if (retryBackoff.equals("linear")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear' selected>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("arithmetic")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic' selected>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("geometric")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric' selected>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("exponential")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential' selected>Exponential</option></select></td></tr>");
}
if (ignoreOverride) {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride' checked></td></tr>");
} else {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride'></td></tr>");
}
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Map<?, ?> parameters = request.getParameterMap();
String userId = request.getParameter("userId");
String topicArn = request.getParameter("topicArn");
String endPoint = request.getParameter("endPoint");
String protocol = request.getParameter("protocol");
String arn = request.getParameter("arn");
String nextToken = request.getParameter("nextToken");
connect(userId);
if (parameters.containsKey("Subscribe")) {
try {
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol.toLowerCase(), endPoint);
sns.subscribe(subscribeRequest);
} catch (Exception ex) {
logger.error("event=subscribe", ex);
throw new ServletException(ex);
}
} else if (parameters.containsKey("Unsubscribe")) {
try {
UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(arn);
sns.unsubscribe(unsubscribeRequest);
} catch (Exception ex) {
logger.error("event=unsubscribe arn=" + arn , ex);
throw new ServletException(ex);
}
}
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsByTopicResult listSubscriptionsByTopicResult = null;
try {
listSubscriptionsByTopicResult = sns.listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken));
subscriptions = listSubscriptionsByTopicResult.getSubscriptions();
} catch (Exception ex) {
logger.error("event=listAllSubscriptionsByTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
ICNSTopicPersistence topicHandler = PersistenceFactory.getTopicPersistence();
CNSTopic topic = null;
try {
topic = topicHandler.getTopic(topicArn);
} catch (Exception ex) {
logger.error("event=getTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
out.println("<html>");
out.println("<script type='text/javascript' language='javascript'>");
out.println("function changeEndpointHint(protocol){ ");
out.println(" if (protocol == 'HTTP' || protocol == 'HTTPS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. http://company.com'; }");
out.println(" else if (protocol == 'EMAIL' || protocol == 'EMAIL_JSON') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. [email protected]'; }");
out.println(" else if (protocol == 'CQS' || protocol == 'SQS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. arn:aws:cqs:ccp:555555555555:my-queue'; } ");
out.println("}");
out.println("</script>");
header(request, out, "Subscriptions for Topic "+ ((topic != null) ? topic.getName():""));
out.println("<body>");
out.println("<h2>Subscriptions for Topic "+ ((topic != null) ? topic.getName():"") + "</h2>");
if (user != null) {
out.println("<table><tr><td><b>User Name:</b></td><td>"+ user.getUserName()+"</td></tr>");
out.println("<tr><td><b>User ID:</b></td><td>"+ user.getUserId()+"</td></tr>");
out.println("<tr><td><b>Access Key:</b></td><td>"+user.getAccessKey()+"</td></tr>");
out.println("<tr><td><b>Access Secret:</b></td><td>"+user.getAccessSecret()+"</td></tr>");
out.println("<tr><td><b>Topic Name:</b></td><td>"+ topic.getName()+"</td></tr>");
out.println("<tr><td><b>Topic Display Name:</b></td><td>" + topic.getDisplayName()+ "</td></tr>");
out.println("<tr><td><b>Topic Arn:</b></td><td>" + topic.getArn()+ "</td></tr>");
out.println("<tr><td><b>Num Subscriptions:</b></td><td>" + subscriptions.size()+ "</td></tr></table>");
}
out.println("<p><table><tr><td><b>Protocol</b></td><td><b>End Point</b></td><td> </td></tr>");
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td><select name='protocol' onchange='changeEndpointHint(this.value)'><option value='HTTP'>HTTP</option><option value='HTTPS'>HTTPS</option><option value='EMAIL'>EMAIL</option><option value='EMAIL_JSON'>EMAIL_JSON</option><option value='CQS'>CQS</option><option value='SQS'>SQS</option></select></td>");
out.println("<td><input type='text' name='endPoint' id = 'endPoint' size='65' placeholder='e.g. http://company.com'><input type='hidden' name='userId' value='"+ userId + "'></td><td><input type='submit' value='Subscribe' name='Subscribe' /></td></tr>");
out.println("</form></table>");
out.println("<p><hr width='100%' align='left' />");
out.println("<p><span class='content'><table border='1'>");
out.println("<tr><th>Row</th>");
out.println("<th>Arn</th>");
out.println("<th>Protocol</th>");
out.println("<th>End Point</th>");
out.println("<th> </th>");
out.println("<th> </th></tr>");
for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
Subscription s = subscriptions.get(i);
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+user.getUserId()+"&arn="+s.getSubscriptionArn()+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td>"+i+"</td>");
out.println("<td>"+s.getSubscriptionArn() +"<input type='hidden' name='arn' value="+s.getSubscriptionArn()+"></td>");
out.println("<td>"+s.getProtocol()+"</td>");
out.println("<td>"+s.getEndpoint()+"</td>");
if (s.getProtocol().toString().equals("http") && !s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/subscription/editdeliverypolicy?subscriptionArn="+ s.getSubscriptionArn() + "&userId=" + userId + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Delivery Policy</a></td>");
} else {
out.println("<td> </td>");
}
if (s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td> </td>");
} else {
out.println("<td><input type='submit' value='Unsubscribe' name='Unsubscribe'/></td>");
}
out.println("</tr></form>");
}
out.println("</table></span></p>");
if (listSubscriptionsByTopicResult != null && listSubscriptionsByTopicResult.getNextToken() != null) {
out.println("<p><a href='/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"&nextToken="+response.encodeURL(listSubscriptionsByTopicResult.getNextToken())+"'>next ></a></p>");
}
out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a>");
out.println("<a href='/webui/cnsuser?userId="+userId+"&topicArn="+topicArn+"'>BACK TO TOPIC</a></h5>");
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
#location 92
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Map<?, ?> parameters = request.getParameterMap();
String userId = request.getParameter("userId");
String topicArn = request.getParameter("topicArn");
String endPoint = request.getParameter("endPoint");
String protocol = request.getParameter("protocol");
String arn = request.getParameter("arn");
String nextToken = request.getParameter("nextToken");
connect(request);
if (parameters.containsKey("Subscribe")) {
try {
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol.toLowerCase(), endPoint);
sns.subscribe(subscribeRequest);
} catch (Exception ex) {
logger.error("event=subscribe", ex);
throw new ServletException(ex);
}
} else if (parameters.containsKey("Unsubscribe")) {
try {
UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(arn);
sns.unsubscribe(unsubscribeRequest);
} catch (Exception ex) {
logger.error("event=unsubscribe arn=" + arn , ex);
throw new ServletException(ex);
}
}
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsByTopicResult listSubscriptionsByTopicResult = null;
try {
listSubscriptionsByTopicResult = sns.listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken));
subscriptions = listSubscriptionsByTopicResult.getSubscriptions();
} catch (Exception ex) {
logger.error("event=listAllSubscriptionsByTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
ICNSTopicPersistence topicHandler = PersistenceFactory.getTopicPersistence();
CNSTopic topic = null;
try {
topic = topicHandler.getTopic(topicArn);
} catch (Exception ex) {
logger.error("event=getTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
out.println("<html>");
out.println("<script type='text/javascript' language='javascript'>");
out.println("function changeEndpointHint(protocol){ ");
out.println(" if (protocol == 'HTTP' || protocol == 'HTTPS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. http://company.com'; }");
out.println(" else if (protocol == 'EMAIL' || protocol == 'EMAIL_JSON') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. [email protected]'; }");
out.println(" else if (protocol == 'CQS' || protocol == 'SQS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. arn:aws:cqs:ccp:555555555555:my-queue'; } ");
out.println("}");
out.println("</script>");
header(request, out, "Subscriptions for Topic "+ ((topic != null) ? topic.getName():""));
out.println("<body>");
out.println("<h2>Subscriptions for Topic "+ ((topic != null) ? topic.getName():"") + "</h2>");
if (user != null) {
out.println("<table><tr><td><b>User Name:</b></td><td>"+ user.getUserName()+"</td></tr>");
out.println("<tr><td><b>User ID:</b></td><td>"+ user.getUserId()+"</td></tr>");
out.println("<tr><td><b>Access Key:</b></td><td>"+user.getAccessKey()+"</td></tr>");
out.println("<tr><td><b>Access Secret:</b></td><td>"+user.getAccessSecret()+"</td></tr>");
out.println("<tr><td><b>Topic Name:</b></td><td>"+ topic.getName()+"</td></tr>");
out.println("<tr><td><b>Topic Display Name:</b></td><td>" + topic.getDisplayName()+ "</td></tr>");
out.println("<tr><td><b>Topic Arn:</b></td><td>" + topic.getArn()+ "</td></tr>");
out.println("<tr><td><b>Num Subscriptions:</b></td><td>" + subscriptions.size()+ "</td></tr></table>");
}
out.println("<p><table><tr><td><b>Protocol</b></td><td><b>End Point</b></td><td> </td></tr>");
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td><select name='protocol' onchange='changeEndpointHint(this.value)'><option value='HTTP'>HTTP</option><option value='HTTPS'>HTTPS</option><option value='EMAIL'>EMAIL</option><option value='EMAIL_JSON'>EMAIL_JSON</option><option value='CQS'>CQS</option><option value='SQS'>SQS</option></select></td>");
out.println("<td><input type='text' name='endPoint' id = 'endPoint' size='65' placeholder='e.g. http://company.com'><input type='hidden' name='userId' value='"+ userId + "'></td><td><input type='submit' value='Subscribe' name='Subscribe' /></td></tr>");
out.println("</form></table>");
out.println("<p><hr width='100%' align='left' />");
out.println("<p><span class='content'><table border='1'>");
out.println("<tr><th>Row</th>");
out.println("<th>Arn</th>");
out.println("<th>Protocol</th>");
out.println("<th>End Point</th>");
out.println("<th> </th>");
out.println("<th> </th></tr>");
for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
Subscription s = subscriptions.get(i);
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+user.getUserId()+"&arn="+s.getSubscriptionArn()+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td>"+i+"</td>");
out.println("<td>"+s.getSubscriptionArn() +"<input type='hidden' name='arn' value="+s.getSubscriptionArn()+"></td>");
out.println("<td>"+s.getProtocol()+"</td>");
out.println("<td>"+s.getEndpoint()+"</td>");
if (s.getProtocol().toString().equals("http") && !s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/subscription/editdeliverypolicy?subscriptionArn="+ s.getSubscriptionArn() + "&userId=" + userId + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Delivery Policy</a></td>");
} else {
out.println("<td> </td>");
}
if (s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td> </td>");
} else {
out.println("<td><input type='submit' value='Unsubscribe' name='Unsubscribe'/></td>");
}
out.println("</tr></form>");
}
out.println("</table></span></p>");
if (listSubscriptionsByTopicResult != null && listSubscriptionsByTopicResult.getNextToken() != null) {
out.println("<p><a href='/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"&nextToken="+response.encodeURL(listSubscriptionsByTopicResult.getNextToken())+"'>next ></a></p>");
}
out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a>");
out.println("<a href='/webui/cnsuser?userId="+userId+"&topicArn="+topicArn+"'>BACK TO TOPIC</a></h5>");
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void state4ENTITY_LENGTH() throws ProtocolException {
// get content length
int clen = Integer.parseInt(httpMessage.getFirstHeader(HttpHeaders.CONTENT_LENGTH.getName()).getValue());
if (clen < 0) {
throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "content length < 0");
}
// slice content value
byte[] content = sliceByLength(clen);
if (content == null) {
return;
}
// render current request with entity
entity.setContent(content);
httpMessage.setEntity(entity);
// to next state
state = ENTITY_ENCODING;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void state4ENTITY_LENGTH() throws ProtocolException {
// get content length
int clen = Integer.parseInt(httpMessage.getFirstHeader(HttpHeaderType.CONTENT_LENGTH.getName()).getValue());
if (clen < 0) {
throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "content length < 0");
}
// slice content value
byte[] content = sliceByLength(clen);
if (content == null) {
return;
}
// render current request with entity
entity.setContent(content);
httpMessage.setEntity(entity);
// to next state
state = ENTITY_ENCODING;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
long timeoutMillis = unit.toMillis(timeout);
long endTime = System.currentTimeMillis() + timeoutMillis;
synchronized (this) {
if (ready) return ready;
if (timeoutMillis <= 0) return ready;
waiters++;
try {
while (!ready) {
wait(timeoutMillis);
if (endTime < System.currentTimeMillis() && !ready) {
exception = new TimeoutException();
break;
}
}
} finally {
waiters--;
}
}
return ready;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
long timeoutMillis = unit.toMillis(timeout);
long endTime = System.currentTimeMillis() + timeoutMillis;
synchronized (this) {
if (done) return done;
if (timeoutMillis <= 0) return done;
waiters++;
try {
while (!done) {
wait(timeoutMillis);
if (endTime < System.currentTimeMillis() && !done) {
exception = new TimeoutException();
break;
}
}
} finally {
waiters--;
}
}
return done;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String readFileAsString(String filePath) throws IOException {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath)));
inputStream.read(buffer);
} finally {
inputStream.close();
}
return new String(buffer);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String readFileAsString(String filePath) throws IOException {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(getFile(filePath)));
bis.read(buffer);
} finally {
if (bis != null) {
bis.close();
}
}
return new String(buffer);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void state4ENTITY() throws ProtocolException {
boolean done = skip(CR, LF);
if (!done) {
return;
}
// content length
if (httpMessage.getFirstHeader(HttpHeaders.CONTENT_LENGTH.getName()) != null) {
entity = new HttpEntity();
entity.setCharset(getContentCharset(httpMessage));
state = ENTITY_LENGTH;
}
// chunked
else if (TRANSFER_ENCODING_CHUNKED.equals(httpMessage.getFirstHeader(HttpHeaders.TRANSFER_ENCODING.getName()).getValue())) {
entity = new HttpChunkEntity();
entity.setCharset(getContentCharset(httpMessage));
state = ENTITY_CHUNKED_SIZE;
}
// no entity
else {
state = END;
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void state4ENTITY() throws ProtocolException {
boolean done = skip(CR, LF);
if (!done) {
return;
}
// content length
if (httpMessage.getFirstHeader(HttpHeaderType.CONTENT_LENGTH.getName()) != null) {
entity = new HttpEntity();
entity.setContentType(getContentType(httpMessage));
state = ENTITY_LENGTH;
}
// chunked
else if (TRANSFER_ENCODING_CHUNKED.equals(httpMessage.getFirstHeader(HttpHeaderType.TRANSFER_ENCODING.getName()).getValue())) {
entity = new HttpChunkEntity();
entity.setContentType(getContentType(httpMessage));
state = ENTITY_CHUNKED_SIZE;
}
// no entity
else {
state = END;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void writeStringToFile(String content, String filePath)
throws Exception {
BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
outputStream.write(content.getBytes());
outputStream.flush();
} finally {
outputStream.close();
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void writeStringToFile(String content, String filePath)
throws Exception {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
bos.write(content.getBytes());
bos.flush();
} finally {
if (bos != null) {
bos.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@BeforeClass
public static void startElasticsearchRestClient() throws IOException {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
testClusterHost = System.getProperty("tests.cluster.host");
if (testClusterHost == null) {
// We start an elasticsearch Docker instance
Properties props = new Properties();
props.load(AbstractITCase.class.getResourceAsStream("/elasticsearch.version.properties"));
container = new ElasticsearchContainer().withVersion(props.getProperty("version"));
container.withEnv("ELASTIC_PASSWORD", testClusterPass);
container.setWaitStrategy(
new HttpWaitStrategy()
.forStatusCode(200)
.withBasicCredentials(testClusterUser, testClusterPass)
.withStartupTimeout(Duration.ofSeconds(90)));
container.start();
testClusterHost = container.getHost().getHostName();
testClusterPort = container.getFirstMappedPort();
} else {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
}
if (testClusterHost == null) {
Thread.dumpStack();
}
// We build the elasticsearch High Level Client based on the parameters
elasticsearchClient = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchWithSecurity = Elasticsearch.builder()
.addNode(Elasticsearch.Node.builder()
.setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build())
.setUsername(testClusterUser)
.setPassword(testClusterPass)
.build();
// We make sure the cluster is running
testClusterRunning();
// We set what will be elasticsearch behavior as it depends on the cluster version
elasticsearchClient.setElasticsearchBehavior();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@BeforeClass
public static void startElasticsearchRestClient() throws IOException {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
testClusterHost = System.getProperty("tests.cluster.host");
if (testClusterHost == null) {
ElasticsearchClient elasticsearchClientTemporary = null;
try {
testClusterHost = "localhost";
// We test if we have already something running at the testClusterHost address
elasticsearchClientTemporary = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchClientTemporary.info();
staticLogger.debug("A node is already running locally. No need to start a Docker instance.");
} catch (ConnectException e) {
staticLogger.debug("No local node running. We need to start a Docker instance.");
// We start an elasticsearch Docker instance
Properties props = new Properties();
props.load(AbstractITCase.class.getResourceAsStream("/elasticsearch.version.properties"));
container = new ElasticsearchContainer().withVersion(props.getProperty("version"));
container.withEnv("ELASTIC_PASSWORD", testClusterPass);
container.setWaitStrategy(
new HttpWaitStrategy()
.forStatusCode(200)
.withBasicCredentials(testClusterUser, testClusterPass)
.withStartupTimeout(Duration.ofSeconds(90)));
container.start();
testClusterHost = container.getHost().getHostName();
testClusterPort = container.getFirstMappedPort();
} finally {
// We need to close the temporary client
if (elasticsearchClientTemporary != null) {
elasticsearchClientTemporary.shutdown();
}
}
} else {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
}
// We build the elasticsearch High Level Client based on the parameters
elasticsearchClient = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchWithSecurity = Elasticsearch.builder()
.addNode(Elasticsearch.Node.builder()
.setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build())
.setUsername(testClusterUser)
.setPassword(testClusterPass)
.build();
// We make sure the cluster is running
testClusterRunning();
// We set what will be elasticsearch behavior as it depends on the cluster version
elasticsearchClient.setElasticsearchBehavior();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Collection<FileAbstractModel> getFiles(String dir) {
if (logger.isDebugEnabled()) logger.debug("Listing local files from {}", dir);
File[] files = new File(dir).listFiles();
Collection<FileAbstractModel> result = new ArrayList<>(files.length);
// Iterate other files
for (File file : files) {
result.add(toFileAbstractModel(dir, file));
}
if (logger.isDebugEnabled()) logger.debug("{} local files found", result.size());
return result;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Collection<FileAbstractModel> getFiles(String dir) {
logger.debug("Listing local files from {}", dir);
File[] files = new File(dir).listFiles();
Collection<FileAbstractModel> result;
if (files != null) {
result = new ArrayList<>(files.length);
// Iterate other files
for (File file : files) {
result.add(toFileAbstractModel(dir, file));
}
} else {
logger.debug("Symlink on windows gives null for listFiles(). Skipping [{}]", dir);
result = Collections.EMPTY_LIST;
}
logger.debug("{} local files found", result.size());
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start() throws Exception {
logger.info("Starting FS crawler");
if (loop < 0) {
logger.info("FS crawler started in watch mode. It will run unless you stop it with CTRL+C.");
}
if (loop == 0 && !rest) {
closed = true;
}
if (closed) {
logger.info("Fs crawler is closed. Exiting");
return;
}
esClientManager.start();
esClientManager.createIndices(settings);
// Start the REST Server if needed
if (rest) {
RestServer.start(settings, esClientManager);
logger.info("FS crawler Rest service started on [{}]", settings.getRest().url());
}
// Start the crawler thread - but not if only in rest mode
if (loop != 0) {
fsCrawlerThread = new Thread(new FSParser(settings), "fs-crawler");
fsCrawlerThread.start();
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start() throws Exception {
logger.info("Starting FS crawler");
if (loop < 0) {
logger.info("FS crawler started in watch mode. It will run unless you stop it with CTRL+C.");
}
if (loop == 0 && !rest) {
closed = true;
}
if (closed) {
logger.info("Fs crawler is closed. Exiting");
return;
}
esClientManager.start();
esClientManager.createIndices(settings);
// Start the crawler thread - but not if only in rest mode
if (loop != 0) {
fsCrawlerThread = new Thread(new FSParser(settings), "fs-crawler");
fsCrawlerThread.start();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected SuggestRefreshResponse newResponse(SuggestRefreshRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
failedShards++;
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new SuggestRefreshResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected SuggestRefreshResponse newResponse(SuggestRefreshRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = Lists.newArrayList();
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
failedShards++;
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new SuggestRefreshResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new SMSEMOASettings("Fonseca");
Algorithm algorithm = smsemoaSettings.configure() ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
double dic = (Double)crossover.getParameter("distributionIndex") ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
double dim = (Double)mutation.getParameter("distributionIndex") ;
assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon);
assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon);
assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon);
assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon);
assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new SMSEMOASettings("Fonseca");
SMSEMOA algorithm = (SMSEMOA) smsemoaSettings.configure() ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
double dic = crossover.getDistributionIndex() ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
double dim = mutation.getDistributionIndex() ;
double offset = algorithm.getOffset() ;
assertEquals(100, algorithm.getPopulationSize());
assertEquals(25000, algorithm.getMaxEvaluations());
assertEquals(0.9, pc, epsilon);
assertEquals(20.0, dic, epsilon);
assertEquals(1.0/problem.getNumberOfVariables(), pm, epsilon);
assertEquals(20.0, dim, epsilon);
assertEquals(100.0, offset, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 85
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void loadInstance() {
try {
File archivo = new File(fileName_);
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(archivo);
br = new BufferedReader(fr);
// File reading
String line;
int lineCnt = 0;
line = br.readLine(); // reading the first line (special case)
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
try {
Point auxPoint = new Point(dimensions_);
for (int i = 0; i < dimensions_; i++) {
auxPoint.vector_[i] = new Double(st.nextToken());
}
add(auxPoint);
line = br.readLine();
lineCnt++;
} catch (NumberFormatException e) {
Configuration.logger_.log(
Level.WARNING,
"Number in a wrong format in line " + lineCnt + "\n" + line, e);
line = br.readLine();
lineCnt++;
} catch (NoSuchElementException e2) {
Configuration.logger_.log(
Level.WARNING,
"Line " + lineCnt + " does not have the right number of objectives\n" + line, e2);
line = br.readLine();
lineCnt++;
}
}
br.close();
} catch (FileNotFoundException e3) {
Configuration.logger_
.log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3);
} catch (IOException e3) {
Configuration.logger_
.log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3);
}
}
#location 44
#vulnerability type RESOURCE_LEAK | #fixed code
public void loadInstance() throws IOException {
File archivo = new File(fileName_);
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(archivo);
br = new BufferedReader(fr);
// File reading
String line;
int lineCnt = 0;
line = br.readLine(); // reading the first line (special case)
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
try {
Point auxPoint = new Point(dimensions_);
for (int i = 0; i < dimensions_; i++) {
auxPoint.vector_[i] = new Double(st.nextToken());
}
add(auxPoint);
line = br.readLine();
lineCnt++;
} catch (NumberFormatException e) {
Configuration.logger_.log(
Level.WARNING,
"Number in a wrong format in line " + lineCnt + "\n" + line, e);
line = br.readLine();
lineCnt++;
} catch (NoSuchElementException e2) {
Configuration.logger_.log(
Level.WARNING,
"Line " + lineCnt + " does not have the right number of objectives\n" + line, e2);
line = br.readLine();
lineCnt++;
}
}
br.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public SolutionSet execute() throws JMException, ClassNotFoundException {
initParams();
success_ = false;
globalBest_ = null ;
//->Step 1 (and 3) Create the initial population and evaluate
for (int i = 0; i < swarmSize_; i++) {
Solution particle = new Solution(problem_);
problem_.evaluate(particle);
evaluations_ ++ ;
swarm_.add(particle);
if ((globalBest_ == null) || (particle.getObjective(0) < globalBest_.getObjective(0)))
globalBest_ = new Solution(particle) ;
}
//-> Step2. Initialize the speed_ of each particle to 0
for (int i = 0; i < swarmSize_; i++) {
for (int j = 0; j < problem_.getNumberOfVariables(); j++) {
speed_[i][j] = 0.0;
}
}
//-> Step 6. Initialize the memory of each particle
for (int i = 0; i < swarm_.size(); i++) {
Solution particle = new Solution(swarm_.get(i));
localBest_[i] = particle;
}
//-> Step 7. Iterations ..
while (iteration_ < maxIterations_) {
int bestIndividual = (Integer)findBestSolution_.execute(swarm_) ;
try {
//Compute the speed_
computeSpeed(iteration_, maxIterations_);
} catch (IOException ex) {
Logger.getLogger(StandardPSO2011.class.getName()).log(Level.SEVERE, null, ex);
}
//Compute the new positions for the swarm_
computeNewPositions();
//Mutate the swarm_
//mopsoMutation(iteration_, maxIterations_);
//Evaluate the new swarm_ in new positions
for (int i = 0; i < swarm_.size(); i++) {
Solution particle = swarm_.get(i);
problem_.evaluate(particle);
evaluations_ ++ ;
}
//Actualize the memory of this particle
for (int i = 0; i < swarm_.size(); i++) {
//int flag = comparator_.compare(swarm_.get(i), localBest_[i]);
//if (flag < 0) { // the new particle is best_ than the older remember
if ((swarm_.get(i).getObjective(0) < localBest_[i].getObjective(0))) {
Solution particle = new Solution(swarm_.get(i));
localBest_[i] = particle;
} // if
if ((swarm_.get(i).getObjective(0) < globalBest_.getObjective(0))) {
Solution particle = new Solution(swarm_.get(i));
globalBest_ = particle;
} // if
}
iteration_++;
}
// Return a population with the best individual
SolutionSet resultPopulation = new SolutionSet(1) ;
resultPopulation.add(swarm_.get((Integer)findBestSolution_.execute(swarm_))) ;
return resultPopulation ;
}
#location 60
#vulnerability type NULL_DEREFERENCE | #fixed code
public SolutionSet execute() throws JMException, ClassNotFoundException {
initParams();
success_ = false;
// Step 1 Create the initial population and evaluate
for (int i = 0; i < swarmSize_; i++) {
Solution particle = new Solution(problem_);
problem_.evaluate(particle);
evaluations_ ++ ;
swarm_.add(particle);
}
//-> Step2. Initialize the speed_ of each particle
for (int i = 0; i < swarmSize_; i++) {
XReal particle = new XReal(swarm_.get(i)) ;
for (int j = 0; j < problem_.getNumberOfVariables(); j++) {
speed_[i][j] = PseudoRandom.randDouble(problem_.getLowerLimit(j)- particle.getValue(i),
problem_.getUpperLimit(j)- particle.getValue(i)) ;
}
}
//-> Step 6. Initialize the memory of each particle
for (int i = 0; i < swarm_.size(); i++) {
Solution particle = new Solution(swarm_.get(i));
localBest_[i] = particle;
neighborhoodBest_[i] = getNeighbourWithMinimumFitness(i) ;
}
//-> Step 7. Iterations ..
while (iteration_ < maxIterations_) {
//Compute the speed_
computeSpeed() ;
//Compute the new positions for the swarm_
computeNewPositions();
//Evaluate the new swarm_ in new positions
for (int i = 0; i < swarm_.size(); i++) {
Solution particle = swarm_.get(i);
problem_.evaluate(particle);
evaluations_ ++ ;
}
//Actualize the memory of this particle
for (int i = 0; i < swarm_.size(); i++) {
//int flag = comparator_.compare(swarm_.get(i), localBest_[i]);
//if (flag < 0) { // the new particle is best_ than the older remember
if ((swarm_.get(i).getObjective(0) < localBest_[i].getObjective(0))) {
Solution particle = new Solution(swarm_.get(i));
localBest_[i] = particle;
} // if
if ((swarm_.get(i).getObjective(0) < neighborhoodBest_[i].getObjective(0))) {
Solution particle = new Solution(swarm_.get(i));
neighborhoodBest_[i] = particle;
} // if
}
iteration_++;
}
// Return a population with the best individual
SolutionSet resultPopulation = new SolutionSet(1) ;
resultPopulation.add(swarm_.get((Integer)findBestSolution_.execute(swarm_))) ;
return resultPopulation ;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 84
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void loadInstance() {
try {
File archivo = new File(fileName_);
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(archivo);
br = new BufferedReader(fr);
// File reading
String line;
int lineCnt = 0;
line = br.readLine(); // reading the first line (special case)
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
try {
Point auxPoint = new Point(dimensions_);
for (int i = 0; i < dimensions_; i++) {
auxPoint.vector_[i] = new Double(st.nextToken());
}
add(auxPoint);
line = br.readLine();
lineCnt++;
} catch (NumberFormatException e) {
Configuration.logger_.log(
Level.WARNING,
"Number in a wrong format in line " + lineCnt + "\n" + line, e);
line = br.readLine();
lineCnt++;
} catch (NoSuchElementException e2) {
Configuration.logger_.log(
Level.WARNING,
"Line " + lineCnt + " does not have the right number of objectives\n" + line, e2);
line = br.readLine();
lineCnt++;
}
}
br.close();
} catch (FileNotFoundException e3) {
Configuration.logger_
.log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3);
} catch (IOException e3) {
Configuration.logger_
.log(Level.SEVERE, "The file " + fileName_ + " has not been found in your file system", e3);
}
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
public void loadInstance() throws IOException {
File archivo = new File(fileName_);
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(archivo);
br = new BufferedReader(fr);
// File reading
String line;
int lineCnt = 0;
line = br.readLine(); // reading the first line (special case)
while (line != null) {
StringTokenizer st = new StringTokenizer(line);
try {
Point auxPoint = new Point(dimensions_);
for (int i = 0; i < dimensions_; i++) {
auxPoint.vector_[i] = new Double(st.nextToken());
}
add(auxPoint);
line = br.readLine();
lineCnt++;
} catch (NumberFormatException e) {
Configuration.logger_.log(
Level.WARNING,
"Number in a wrong format in line " + lineCnt + "\n" + line, e);
line = br.readLine();
lineCnt++;
} catch (NoSuchElementException e2) {
Configuration.logger_.log(
Level.WARNING,
"Line " + lineCnt + " does not have the right number of objectives\n" + line, e2);
line = br.readLine();
lineCnt++;
}
}
br.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 83
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
neighborhood_ = parentThread_.neighborhood_;
problem_ = parentThread_.problem_;
lambda_ = parentThread_.lambda_;
population_ = parentThread_.population_;
z_ = parentThread_.z_;
indArray_ = parentThread_.indArray_;
barrier_ = parentThread_.barrier_;
int partitions = parentThread_.populationSize_ / parentThread_.numberOfThreads_;
evaluations_ = 0;
maxEvaluations_ = parentThread_.maxEvaluations_ / parentThread_.numberOfThreads_;
try {
//Configuration.logger_.info("en espera: " + barrier_.getNumberWaiting()) ;
barrier_.await();
//Configuration.logger_.info("Running: " + id_ ) ;
} catch (InterruptedException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
} catch (BrokenBarrierException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
}
int first;
int last;
first = partitions * id_;
if (id_ == (parentThread_.numberOfThreads_ - 1)) {
last = parentThread_.populationSize_ - 1;
} else {
last = first + partitions - 1;
}
Configuration.logger_.info("Id: " + id_ + " Partitions: " + partitions +
" First: " + first + " Last: " + last);
do {
for (int i = first; i <= last; i++) {
int n = i;
int type;
double rnd = PseudoRandom.randDouble();
// STEP 2.1. Mating selection based on probability
if (rnd < parentThread_.delta_) {
// neighborhood
type = 1;
} else {
// whole population
type = 2;
}
Vector<Integer> p = new Vector<Integer>();
this.matingSelection(p, n, 2, type);
// STEP 2.2. Reproduction
Solution child = null;
Solution[] parents = new Solution[3];
try {
synchronized (parentThread_) {
parents[0] = parentThread_.population_.get(p.get(0));
parents[1] = parentThread_.population_.get(p.get(1));
parents[2] = parentThread_.population_.get(n);
// Apply DE crossover
child = (Solution) parentThread_.crossover_
.execute(new Object[] {parentThread_.population_.get(n), parents});
}
// Apply mutation
parentThread_.mutation_.execute(child);
// Evaluation
parentThread_.problem_.evaluate(child);
} catch (JMetalException ex) {
Logger.getLogger(pMOEAD.class.getName()).log(Level.SEVERE, null, ex);
}
evaluations_++;
// STEP 2.3. Repair. Not necessary
// STEP 2.4. Update z_
updateReference(child);
// STEP 2.5. Update of solutions
try {
updateOfSolutions(child, n, type);
} catch (JMetalException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
}
}
} while (evaluations_ < maxEvaluations_);
long estimatedTime = System.currentTimeMillis() - parentThread_.initTime_;
Configuration.logger_.info("Time thread " + id_ + ": " + estimatedTime);
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
neighborhood_ = parentThread_.neighborhood_;
problem_ = parentThread_.problem_;
lambda_ = parentThread_.lambda_;
population_ = parentThread_.population_;
z_ = parentThread_.z_;
indArray_ = parentThread_.indArray_;
barrier_ = parentThread_.barrier_;
int partitions = parentThread_.populationSize_ / parentThread_.numberOfThreads_;
evaluations_ = 0;
maxEvaluations_ = parentThread_.maxEvaluations_ / parentThread_.numberOfThreads_;
try {
//Configuration.logger_.info("en espera: " + barrier_.getNumberWaiting()) ;
barrier_.await();
//Configuration.logger_.info("Running: " + id_ ) ;
} catch (InterruptedException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
} catch (BrokenBarrierException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
}
int first;
int last;
first = partitions * id_;
if (id_ == (parentThread_.numberOfThreads_ - 1)) {
last = parentThread_.populationSize_ - 1;
} else {
last = first + partitions - 1;
}
Configuration.logger_.info("Id: " + id_ + " Partitions: " + partitions +
" First: " + first + " Last: " + last);
do {
for (int i = first; i <= last; i++) {
int n = i;
int type;
double rnd = PseudoRandom.randDouble();
// STEP 2.1. Mating selection based on probability
if (rnd < parentThread_.delta_) {
// neighborhood
type = 1;
} else {
// whole population
type = 2;
}
Vector<Integer> p = new Vector<Integer>();
this.matingSelection(p, n, 2, type);
// STEP 2.2. Reproduction
Solution child = null;
Solution[] parents = new Solution[3];
try {
synchronized (parentThread_) {
parents[0] = parentThread_.population_.get(p.get(0));
parents[1] = parentThread_.population_.get(p.get(1));
parents[2] = parentThread_.population_.get(n);
// Apply DE crossover
child = (Solution) parentThread_.crossover_
.execute(new Object[] {parentThread_.population_.get(n), parents});
}
// Apply mutation
parentThread_.mutation_.execute(child);
// Evaluation
parentThread_.problem_.evaluate(child);
} catch (JMetalException ex) {
Logger.getLogger(pMOEAD.class.getName()).log(Level.SEVERE, null, ex);
}
evaluations_++;
// STEP 2.3. Repair. Not necessary
// STEP 2.4. Update idealPoint
updateReference(child);
// STEP 2.5. Update of solutions
try {
updateOfSolutions(child, n, type);
} catch (JMetalException e) {
Configuration.logger_.log(Level.SEVERE, "Error", e);
}
}
} while (evaluations_ < maxEvaluations_);
long estimatedTime = System.currentTimeMillis() - parentThread_.initTime_;
Configuration.logger_.info("Time thread " + id_ + ": " + estimatedTime);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 85
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static public void loadColumnVectorFromFile(String file, int rows, double[] column)
throws JMetalException {
try {
BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadColumnVector(brSrc, rows, column);
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
static public void loadColumnVectorFromFile(String file, int rows, double[] column)
throws JMetalException {
try {
BufferedReader brSrc =
new BufferedReader(
new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ;
//BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadColumnVector(brSrc, rows, column);
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new SMSEMOASettings("Fonseca");
Algorithm algorithm = smsemoaSettings.configure(configuration_) ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
double dic = (Double)crossover.getParameter("distributionIndex") ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
double dim = (Double)mutation.getParameter("distributionIndex") ;
assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon);
assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon);
assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon);
assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon);
assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new SMSEMOASettings("Fonseca");
SMSEMOA algorithm = (SMSEMOA) smsemoaSettings.configure(configuration) ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
double dic = crossover.getDistributionIndex() ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
double dim = mutation.getDistributionIndex() ;
double offset = algorithm.getOffset() ;
assertEquals(100, algorithm.getPopulationSize());
assertEquals(25000, algorithm.getMaxEvaluations());
assertEquals(0.9, pc, epsilon);
assertEquals(20.0, dic, epsilon);
assertEquals(1.0/problem.getNumberOfVariables(), pm, epsilon);
assertEquals(20.0, dim, epsilon);
assertEquals(100.0, offset, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5");
Algorithm algorithm = nsgaIISettings.configure() ;
Problem problem = new ZDT5("Binary") ;
SinglePointCrossover crossover = (SinglePointCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
BitFlipMutation mutation = (BitFlipMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
assertEquals("NSGAIIBinary_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
assertEquals("NSGAIIBinary_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon);
assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5");
NSGAII algorithm = (NSGAII)nsgaIISettings.configure() ;
Problem problem = new ZDT5("Binary") ;
SinglePointCrossover crossover = (SinglePointCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
BitFlipMutation mutation = (BitFlipMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
assertEquals("NSGAIIBinary_SettingsTest", 100, algorithm.getPopulationSize());
assertEquals("NSGAIIBinary_SettingsTest", 25000, algorithm.getMaxEvaluations()) ;
assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon);
assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
//problem = new Kursawe("Real", 3);
//problem = new Kursawe("BinaryReal", 3);
//problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
//problem = new ConstrEx("Real");
//problem = new DTLZ1("Real");
//problem = new OKA2("Real") ;
}
//Injector injector = Guice.createInjector(new ExecutorModule()) ;
//Executor executor = injector.getInstance(Executor.class) ;
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator();
//SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ;
algorithm = new NSGAIIE(problem, evaluator);
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 25000);
// Mutation and Crossover for Real codification
HashMap<String, Object> crossoverParameters = new HashMap<String, Object>();
crossoverParameters.put("probability", 0.9);
crossoverParameters.put("distributionIndex", 20.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters);
HashMap<String, Object> mutationParameters = new HashMap<String, Object>();
mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables());
mutationParameters.put("distributionIndex", 20.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters);
// Selection Operator
HashMap<String, Object> selectionParameters = null; // FIXME: why we are passing null?
selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
logger_.info("Total execution time: " + estimatedTime + "ms");
// Result messages
FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ;
fileContext.setSeparator("\t");
logger_.info("Variables values have been writen to file VAR.tsv");
SolutionSetOutput.printVariablesToFile(fileContext, population) ;
fileContext = new DefaultFileOutputContext("FUN.tsv");
fileContext.setSeparator("\t");
SolutionSetOutput.printObjectivesToFile(fileContext, population);
//population.printObjectivesToFile("FUN");
//logger_.info("Objectives values have been written to file FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
int evaluations = (Integer) algorithm.getOutputParameter("evaluations");
logger_.info("Speed : " + evaluations + " evaluations");
}
evaluator.shutdown();
}
#location 87
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
//problem = new Kursawe("BinaryReal", 3);
//problem = new Water("Real");
//problem = new ZDT3("ArrayReal", 30);
//problem = new ConstrEx("Real");
//problem = new DTLZ1("Real");
//problem = new OKA2("Real") ;
}
//Injector injector = Guice.createInjector(new ExecutorModule()) ;
//Executor executor = injector.getInstance(Executor.class) ;
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator();
//SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ;
algorithm = new NSGAIIE(problem, evaluator);
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 25000);
// Mutation and Crossover for Real codification
HashMap<String, Object> crossoverParameters = new HashMap<String, Object>();
crossoverParameters.put("probability", 0.9);
crossoverParameters.put("distributionIndex", 20.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters);
HashMap<String, Object> mutationParameters = new HashMap<String, Object>();
mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables());
mutationParameters.put("distributionIndex", 20.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters);
// Selection Operator
HashMap<String, Object> selectionParameters = new HashMap<String, Object>() ;
selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
logger_.info("Total execution time: " + estimatedTime + "ms");
// Result messages
FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ;
fileContext.setSeparator("\t");
logger_.info("Variables values have been writen to file VAR.tsv");
SolutionSetOutput.printVariablesToFile(fileContext, population) ;
fileContext = new DefaultFileOutputContext("FUN.tsv");
fileContext.setSeparator("\t");
SolutionSetOutput.printObjectivesToFile(fileContext, population);
//population.printObjectivesToFile("FUN");
//logger_.info("Objectives values have been written to file FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
int evaluations = (Integer) algorithm.getOutputParameter("evaluations");
logger_.info("Speed : " + evaluations + " evaluations");
}
evaluator.shutdown();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix)
throws JMetalException {
try {
BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadMatrix(brSrc, rows, columns, matrix);
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix)
throws JMetalException {
try {
BufferedReader brSrc =
new BufferedReader(
new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ;
//BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadMatrix(brSrc, rows, columns, matrix);
brSrc.close();
} catch (Exception e) {
throw new JMetalException("Error in Benchmark.java", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new FastSMSEMOASettings("Fonseca");
Algorithm algorithm = smsemoaSettings.configure(configuration_) ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
double dic = (Double)crossover.getParameter("distributionIndex") ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
double dim = (Double)mutation.getParameter("distributionIndex") ;
Assert.assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
Assert.assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
Assert.assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings fastSMEEMOASettings = new FastSMSEMOASettings("Fonseca");
FastSMSEMOA algorithm = (FastSMSEMOA) fastSMEEMOASettings.configure(configuration) ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
double dic = crossover.getDistributionIndex() ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
double dim = mutation.getDistributionIndex() ;
double offset = algorithm.getOffset() ;
assertEquals(100, algorithm.getPopulationSize());
assertEquals(25000, algorithm.getMaxEvaluations());
assertEquals(0.9, pc, epsilon);
assertEquals(20.0, dic, epsilon);
assertEquals(1.0 / problem.getNumberOfVariables(), pm, epsilon);
assertEquals(20.0, dim, epsilon);
assertEquals(100.0, offset, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws JMException {
double epsilon = 0.000000000000001;
Settings GDE3Settings = new GDE3_Settings("Fonseca");
Algorithm algorithm = GDE3Settings.configure();
//Problem problem = new Fonseca("Real");
DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover)algorithm.getOperator("crossover") ;
double CR = (Double)crossover.getParameter("CR") ;
double F = (Double)crossover.getParameter("F") ;
Assert.assertEquals("GDE3_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
Assert.assertEquals("GDE3_SettingsTest", 250, ((Integer)algorithm.getInputParameter("maxIterations")).intValue());
Assert.assertEquals("GDE3_SettingsTest", 0.5, CR, epsilon);
Assert.assertEquals("GDE3_SettingsTest", 0.5, F, epsilon);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void test() throws JMException {
double epsilon = 0.000000000000001;
GDE3_Settings GDE3Settings = new GDE3_Settings("Fonseca");
GDE3 algorithm = (GDE3) GDE3Settings.configure();
DifferentialEvolutionCrossover crossover =
(DifferentialEvolutionCrossover) algorithm.getCrossoverOperator();
Assert.assertEquals("GDE3_SettingsTest", 100, algorithm.getPopulationSize());
Assert.assertEquals("GDE3_SettingsTest", 250, algorithm.getMaxIterations());
Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getCr(), epsilon);
Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getF(), epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int compare(Solution o1, Solution o2) {
if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
}
int flagComparatorRank = RANK_COMPARATOR.compare(o1, o2);
if (flagComparatorRank != 0) {
return flagComparatorRank;
}
/* His rank is equal, then distance crowding RANK_COMPARATOR */
double distance1 = (double)o1.getAlgorithmAttributes().getAttribute("CrowdingDistance");
double distance2 = (double)o2.getAlgorithmAttributes().getAttribute("CrowdingDistance");
if (distance1 > distance2) {
return -1;
}
if (distance1 < distance2) {
return 1;
}
return 0;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public int compare(Solution o1, Solution o2) {
if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
}
int flagComparatorRank = RANK_COMPARATOR.compare(o1, o2);
if (flagComparatorRank != 0) {
return flagComparatorRank;
}
/* His rank is equal, then distance crowding RANK_COMPARATOR */
double distance1 = NSGAIIAttr.getAttributes(o1).getCrowdingDistance() ;
double distance2 = NSGAIIAttr.getAttributes(o2).getCrowdingDistance() ;
//double distance1 = (double)o1.getAlgorithmAttributes().getAttribute("CrowdingDistance");
//double distance2 = (double)o2.getAlgorithmAttributes().getAttribute("CrowdingDistance");
if (distance1 > distance2) {
return -1;
}
if (distance1 < distance2) {
return 1;
}
return 0;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5");
Algorithm algorithm = nsgaIISettings.configure(configuration_) ;
Problem problem = new ZDT5("Binary") ;
SinglePointCrossover crossover = (SinglePointCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
BitFlipMutation mutation = (BitFlipMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
assertEquals("NSGAIIBinary_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
assertEquals("NSGAIIBinary_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon);
assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure2() throws Exception {
double epsilon = 0.000000000000001 ;
Settings nsgaIISettings = new NSGAIIBinarySettings("ZDT5");
NSGAII algorithm = (NSGAII)nsgaIISettings.configure(configuration_) ;
Problem problem = new ZDT5("Binary") ;
SinglePointCrossover crossover = (SinglePointCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
BitFlipMutation mutation = (BitFlipMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
assertEquals("NSGAIIBinary_SettingsTest", 100, algorithm.getPopulationSize());
assertEquals("NSGAIIBinary_SettingsTest", 25000, algorithm.getMaxEvaluations()) ;
assertEquals("NSGAIIBinary_SettingsTest", 0.9, pc, epsilon);
assertEquals("NSGAIIBinary_SettingsTest", 1.0/problem.getNumberOfBits(), pm, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 81
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
/*
* Alternatives:
* - "NSGAII"
* - "SteadyStateNSGAII"
*/
String nsgaIIVersion = "NSGAII" ;
/*
* Alternatives:
* - evaluator = new SequentialSolutionSetEvaluator() // NSGAII
* - evaluator = new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII
*/
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAIITemplate.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build(nsgaIIVersion) ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int compare(Solution solution1, Solution solution2) {
if (solution1 == null) {
return 1;
} else if (solution2 == null) {
return -1;
}
if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") < (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) {
return -1;
}
if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") > (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) {
return 1;
}
return 0;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public int compare(Solution solution1, Solution solution2) {
if (solution1 == null) {
return 1;
} else if (solution2 == null) {
return -1;
}
if (NSGAIIAttr.getAttributes(solution1).getRank() < NSGAIIAttr.getAttributes(solution2).getRank()) {
return -1;
}
if (NSGAIIAttr.getAttributes(solution1).getRank() > NSGAIIAttr.getAttributes(solution2).getRank()) {
return 1;
}
return 0;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static public void loadNMatrixFromFile(String file, int N, int rows, int columns,
double[][][] matrix) throws JMetalException {
try {
BufferedReader brSrc = new BufferedReader(new FileReader(file));
for (int i = 0; i < N; i++) {
loadMatrix(brSrc, rows, columns, matrix[i]);
}
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
static public void loadNMatrixFromFile(String file, int N, int rows, int columns,
double[][][] matrix) throws JMetalException {
try {
BufferedReader brSrc =
new BufferedReader(
new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ;
//BufferedReader brSrc = new BufferedReader(new FileReader(file));
for (int i = 0; i < N; i++) {
loadMatrix(brSrc, rows, columns, matrix[i]);
}
brSrc.close();
} catch (Exception e) {
throw new JMetalException("Error in Benchmark.java", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
//problem = new Kursawe("Real", 3);
//problem = new Kursawe("BinaryReal", 3);
//problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
//problem = new ConstrEx("Real");
//problem = new DTLZ1("Real");
//problem = new OKA2("Real") ;
}
//Injector injector = Guice.createInjector(new ExecutorModule()) ;
//Executor executor = injector.getInstance(Executor.class) ;
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator();
//SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ;
algorithm = new NSGAIIE(problem, evaluator);
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 25000);
// Mutation and Crossover for Real codification
HashMap<String, Object> crossoverParameters = new HashMap<String, Object>();
crossoverParameters.put("probability", 0.9);
crossoverParameters.put("distributionIndex", 20.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters);
HashMap<String, Object> mutationParameters = new HashMap<String, Object>();
mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables());
mutationParameters.put("distributionIndex", 20.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters);
// Selection Operator
HashMap<String, Object> selectionParameters = null; // FIXME: why we are passing null?
selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
logger_.info("Total execution time: " + estimatedTime + "ms");
// Result messages
FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ;
fileContext.setSeparator("\t");
logger_.info("Variables values have been writen to file VAR.tsv");
SolutionSetOutput.printVariablesToFile(fileContext, population) ;
fileContext = new DefaultFileOutputContext("FUN.tsv");
fileContext.setSeparator("\t");
SolutionSetOutput.printObjectivesToFile(fileContext, population);
//population.printObjectivesToFile("FUN");
//logger_.info("Objectives values have been written to file FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
int evaluations = (Integer) algorithm.getOutputParameter("evaluations");
logger_.info("Speed : " + evaluations + " evaluations");
}
evaluator.shutdown();
}
#location 82
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
//problem = new Kursawe("BinaryReal", 3);
//problem = new Water("Real");
//problem = new ZDT3("ArrayReal", 30);
//problem = new ConstrEx("Real");
//problem = new DTLZ1("Real");
//problem = new OKA2("Real") ;
}
//Injector injector = Guice.createInjector(new ExecutorModule()) ;
//Executor executor = injector.getInstance(Executor.class) ;
SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator();
//SolutionSetEvaluator executor = new MultithreadedSolutionSetEvaluator(4, problem) ;
algorithm = new NSGAIIE(problem, evaluator);
// Algorithm parameters
algorithm.setInputParameter("populationSize", 100);
algorithm.setInputParameter("maxEvaluations", 25000);
// Mutation and Crossover for Real codification
HashMap<String, Object> crossoverParameters = new HashMap<String, Object>();
crossoverParameters.put("probability", 0.9);
crossoverParameters.put("distributionIndex", 20.0);
crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", crossoverParameters);
HashMap<String, Object> mutationParameters = new HashMap<String, Object>();
mutationParameters.put("probability", 1.0 / problem.getNumberOfVariables());
mutationParameters.put("distributionIndex", 20.0);
mutation = MutationFactory.getMutationOperator("PolynomialMutation", mutationParameters);
// Selection Operator
HashMap<String, Object> selectionParameters = new HashMap<String, Object>() ;
selection = SelectionFactory.getSelectionOperator("BinaryTournament2", selectionParameters);
// Add the operators to the algorithm
algorithm.addOperator("crossover", crossover);
algorithm.addOperator("mutation", mutation);
algorithm.addOperator("selection", selection);
// Add the indicator object to the algorithm
algorithm.setInputParameter("indicators", indicators);
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
logger_.info("Total execution time: " + estimatedTime + "ms");
// Result messages
FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ;
fileContext.setSeparator("\t");
logger_.info("Variables values have been writen to file VAR.tsv");
SolutionSetOutput.printVariablesToFile(fileContext, population) ;
fileContext = new DefaultFileOutputContext("FUN.tsv");
fileContext.setSeparator("\t");
SolutionSetOutput.printObjectivesToFile(fileContext, population);
//population.printObjectivesToFile("FUN");
//logger_.info("Objectives values have been written to file FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
int evaluations = (Integer) algorithm.getOutputParameter("evaluations");
logger_.info("Speed : " + evaluations + " evaluations");
}
evaluator.shutdown();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings smsemoaSettings = new FastSMSEMOASettings("Fonseca");
Algorithm algorithm = smsemoaSettings.configure() ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ;
double pc = (Double)crossover.getParameter("probability") ;
double dic = (Double)crossover.getParameter("distributionIndex") ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ;
double pm = (Double)mutation.getParameter("probability") ;
double dim = (Double)mutation.getParameter("distributionIndex") ;
Assert.assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
Assert.assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue());
Assert.assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon);
Assert.assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConfigure() throws Exception {
double epsilon = 0.000000000000001 ;
Settings fastSMEEMOASettings = new FastSMSEMOASettings("Fonseca");
FastSMSEMOA algorithm = (FastSMSEMOA) fastSMEEMOASettings.configure() ;
Problem problem = new Fonseca("Real") ;
SBXCrossover crossover = (SBXCrossover) algorithm.getCrossoverOperator() ;
double pc = crossover.getCrossoverProbability() ;
double dic = crossover.getDistributionIndex() ;
PolynomialMutation mutation = (PolynomialMutation)algorithm.getMutationOperator() ;
double pm = mutation.getMutationProbability() ;
double dim = mutation.getDistributionIndex() ;
double offset = algorithm.getOffset() ;
assertEquals(100, algorithm.getPopulationSize());
assertEquals(25000, algorithm.getMaxEvaluations());
assertEquals(0.9, pc, epsilon);
assertEquals(20.0, dic, epsilon);
assertEquals(1.0/problem.getNumberOfVariables(), pm, epsilon);
assertEquals(20.0, dim, epsilon);
assertEquals(100.0, offset, epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test2() throws JMException {
double epsilon = 0.000000000000001;
Settings GDE3Settings = new GDE3_Settings("Fonseca");
Algorithm algorithm = GDE3Settings.configure(configuration_);
//Problem problem = new Fonseca("Real");
DifferentialEvolutionCrossover crossover = (DifferentialEvolutionCrossover)algorithm.getOperator("crossover") ;
double CR = (Double)crossover.getParameter("CR") ;
double F = (Double)crossover.getParameter("F") ;
Assert.assertEquals("GDE3_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue());
Assert.assertEquals("GDE3_SettingsTest", 250, ((Integer)algorithm.getInputParameter("maxIterations")).intValue());
Assert.assertEquals("GDE3_SettingsTest", 0.5, CR, epsilon);
Assert.assertEquals("GDE3_SettingsTest", 0.5, F, epsilon);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void test2() throws JMException {
double epsilon = 0.000000000000001;
Settings GDE3Settings = new GDE3_Settings("Fonseca");
GDE3 algorithm = (GDE3) GDE3Settings.configure(configuration_);
DifferentialEvolutionCrossover crossover =
(DifferentialEvolutionCrossover) algorithm.getCrossoverOperator();
Assert.assertEquals("GDE3_SettingsTest", 100, algorithm.getPopulationSize());
Assert.assertEquals("GDE3_SettingsTest", 250, algorithm.getMaxIterations());
Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getCr(), epsilon);
Assert.assertEquals("GDE3_SettingsTest", 0.5, crossover.getF(), epsilon);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Kursawe("BinaryReal", 3);
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
SolutionSetEvaluator evaluator = new MultithreadedSolutionSetEvaluator(4, problem) ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAII.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build() ;
// Execute the Algorithm
long initTime = System.currentTimeMillis();
SolutionSet population = algorithm.execute();
long estimatedTime = System.currentTimeMillis() - initTime;
logger_.info("Total execution time: " + estimatedTime + "ms");
// Result messages
FileOutputContext fileContext = new DefaultFileOutputContext("VAR.tsv") ;
fileContext.setSeparator("\t");
logger_.info("Variables values have been writen to file VAR.tsv");
SolutionSetOutput.printVariablesToFile(fileContext, population) ;
fileContext = new DefaultFileOutputContext("FUN.tsv");
fileContext.setSeparator("\t");
SolutionSetOutput.printObjectivesToFile(fileContext, population);
logger_.info("Objectives values have been written to file FUN");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
}
#location 65
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) throws
JMException,
SecurityException,
IOException,
ClassNotFoundException {
Problem problem;
Algorithm algorithm;
Operator crossover;
Operator mutation;
Operator selection;
QualityIndicator indicators;
// Logger object and file to store log messages
logger_ = Configuration.logger_;
fileHandler_ = new FileHandler("NSGAII_main.log");
logger_.addHandler(fileHandler_);
indicators = null;
if (args.length == 1) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
} else if (args.length == 2) {
Object[] params = {"Real"};
problem = (new ProblemFactory()).getProblem(args[0], params);
indicators = new QualityIndicator(problem, args[1]);
} else {
problem = new Kursawe("Real", 3);
/*
Examples:
problem = new Kursawe("BinaryReal", 3);
problem = new Water("Real");
problem = new ZDT3("ArrayReal", 30);
problem = new ConstrEx("Real");
problem = new DTLZ1("Real");
problem = new OKA2("Real")
*/
}
SolutionSetEvaluator evaluator = new MultithreadedSolutionSetEvaluator(4, problem) ;
crossover = new SBXCrossover.Builder()
.distributionIndex(20.0)
.probability(0.9)
.build() ;
mutation = new PolynomialMutation.Builder()
.distributionIndex(20.0)
.probability(1.0/problem.getNumberOfVariables())
.build();
selection = new BinaryTournament2.Builder()
.build();
algorithm = new NSGAII.Builder(problem, evaluator)
.crossover(crossover)
.mutation(mutation)
.selection(selection)
.maxEvaluations(25000)
.populationSize(100)
.build() ;
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm)
.execute() ;
SolutionSet population = algorithmRunner.getSolutionSet() ;
long computingTime = algorithmRunner.getComputingTime() ;
new SolutionSetOutput.Printer(population)
.separator("\t")
.varFileOutputContext(new DefaultFileOutputContext("VAR.tsv"))
.funFileOutputContext(new DefaultFileOutputContext("FUN.tsv"))
.print();
logger_.info("Total execution time: " + computingTime + "ms");
logger_.info("Objectives values have been written to file FUN.tsv");
logger_.info("Variables values have been written to file VAR.tsv");
if (indicators != null) {
logger_.info("Quality indicators");
logger_.info("Hypervolume: " + indicators.getHypervolume(population));
logger_.info("GD : " + indicators.getGD(population));
logger_.info("IGD : " + indicators.getIGD(population));
logger_.info("Spread : " + indicators.getSpread(population));
logger_.info("Epsilon : " + indicators.getEpsilon(population));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws JMetalException, IOException {
ExperimentData experimentData = new ExperimentData.Builder("Experiment2")
.algorithmNameList(new String[]{"NSGAII", "SMPSO", "MOCell"})
.problemList(new String[]{"ZDT1", "ZDT2", "ZDT3", "ZDT4"})
.experimentBaseDirectory("/Users/antelverde/Softw/jMetal/jMetalGitHub/pruebas")
.outputParetoFrontFileName("FUN")
.outputParetoSetFileName("VAR")
.independentRuns(20)
.build() ;
AlgorithmExecution algorithmExecution = new AlgorithmExecution.Builder(experimentData)
.numberOfThreads(8)
.paretoSetFileName("VAR")
.paretoFrontFileName("FUN")
//.useAlgorithmConfigurationFiles()
.build() ;
ParetoFrontsGeneration paretoFrontsGeneration = new ParetoFrontsGeneration.Builder(experimentData)
.build() ;
String[] indicatorList = new String[]{"HV", "IGD", "EPSILON", "SPREAD", "GD"} ;
QualityIndicatorGeneration qualityIndicatorGeneration = new QualityIndicatorGeneration.Builder(experimentData)
.paretoFrontDirectory("/Users/antelverde/Softw/pruebas/data/paretoFronts")
.paretoFrontFiles(new String[]{"ZDT1.pf","ZDT2.pf", "ZDT3.pf", "ZDT4.pf"})
.qualityIndicatorList(indicatorList)
.build() ;
SetCoverageTables setCoverageTables = new SetCoverageTables.Builder(experimentData)
.build() ;
BoxplotGeneration boxplotGeneration = new BoxplotGeneration.Builder(experimentData)
.indicatorList(indicatorList)
.numberOfRows(2)
.numberOfColumns(2)
.build() ;
Experiment2 experiment = new Experiment2.Builder(experimentData)
.addExperimentOutput(algorithmExecution)
.addExperimentOutput(paretoFrontsGeneration)
.addExperimentOutput(qualityIndicatorGeneration)
.addExperimentOutput(setCoverageTables)
.addExperimentOutput(boxplotGeneration)
.build() ;
experiment.run();
}
#location 46
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws JMetalException, IOException {
ExperimentData experimentData = new ExperimentData.Builder("Experiment2")
.algorithmNameList(new String[]{"NSGAII", "SMPSO", "MOCell"})
.problemList(new String[]{"ZDT1", "ZDT2", "ZDT3", "ZDT4"})
.experimentBaseDirectory("/Users/antelverde/Softw/jMetal/jMetalGitHub/pruebas")
.outputParetoFrontFileName("FUN")
.outputParetoSetFileName("VAR")
.independentRuns(20)
.build() ;
AlgorithmExecution algorithmExecution = new AlgorithmExecution.Builder(experimentData)
.numberOfThreads(8)
.paretoSetFileName("VAR")
.paretoFrontFileName("FUN")
//.useAlgorithmConfigurationFiles()
.build() ;
ParetoFrontsGeneration paretoFrontsGeneration = new ParetoFrontsGeneration.Builder(experimentData)
.build() ;
String[] indicatorList = new String[]{"HV", "IGD", "EPSILON", "SPREAD", "GD"} ;
QualityIndicatorGeneration qualityIndicatorGeneration = new QualityIndicatorGeneration.Builder(experimentData)
.paretoFrontDirectory("/Users/antelverde/Softw/pruebas/data/paretoFronts")
.paretoFrontFiles(new String[]{"ZDT1.pf","ZDT2.pf", "ZDT3.pf", "ZDT4.pf"})
.qualityIndicatorList(indicatorList)
.build() ;
SetCoverageTableGeneration setCoverageTables = new SetCoverageTableGeneration.Builder(experimentData)
.build() ;
BoxplotGeneration boxplotGeneration = new BoxplotGeneration.Builder(experimentData)
.indicatorList(indicatorList)
.numberOfRows(2)
.numberOfColumns(2)
.build() ;
WilcoxonTestTableGeneration wilcoxonTestTableGeneration =
new WilcoxonTestTableGeneration.Builder(experimentData)
.indicatorList(indicatorList)
.build() ;
Experiment2 experiment = new Experiment2.Builder(experimentData)
//.addExperimentOutput(algorithmExecution)
//.addExperimentOutput(paretoFrontsGeneration)
//.addExperimentOutput(qualityIndicatorGeneration)
//.addExperimentOutput(setCoverageTables)
//.addExperimentOutput(boxplotGeneration)
.addExperimentOutput(wilcoxonTestTableGeneration)
.build() ;
experiment.run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static public void loadRowVectorFromFile(String file, int columns, double[] row)
throws JMetalException {
try {
BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadRowVector(brSrc, columns, row);
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
static public void loadRowVectorFromFile(String file, int columns, double[] row)
throws JMetalException {
try {
BufferedReader brSrc =
new BufferedReader(
new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource(file).getPath()))) ;
//BufferedReader brSrc = new BufferedReader(new FileReader(file));
loadRowVector(brSrc, columns, row);
brSrc.close();
} catch (Exception e) {
JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e);
throw new JMetalException("Error in Benchmark.java");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void updateOfSolutions(Solution indiv, int id, int type) {
// indiv: child solution
// id: the id of current subproblem
// type: update solutions in - neighborhood (1) or whole population (otherwise)
int size;
int time;
time = 0;
if (type == 1) {
size = parentThread_.neighborhood_[id].length;
} else {
size = parentThread_.population_.size();
}
int[] perm = new int[size];
Utils.randomPermutation(perm, size);
for (int i = 0; i < size; i++) {
int k;
if (type == 1) {
k = parentThread_.neighborhood_[id][perm[i]];
} else {
k = perm[i]; // calculate the values of objective function regarding the current subproblem
}
double f1, f2;
f2 = fitnessFunction(indiv, parentThread_.lambda_[k]);
synchronized (parentThread_) {
f1 = fitnessFunction(parentThread_.population_.get(k), parentThread_.lambda_[k]);
if (f2 < f1) {
parentThread_.population_.replace(k, new Solution(indiv));
//population[k].indiv = indiv;
time++;
}
}
// the maximal number of solutions updated is not allowed to exceed 'limit'
if (time >= parentThread_.nr_) {
return;
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void initIdealPoint() throws JMException, ClassNotFoundException {
for (int i = 0; i < problem_.getNumberOfObjectives(); i++) {
z_[i] = 1.0e+30;
indArray_[i] = new Solution(problem_);
problem_.evaluate(indArray_[i]);
evaluations_++;
} // for
for (int i = 0; i < populationSize_; i++) {
updateReference(population_.get(i));
} // for
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int compare(Solution o1, Solution o2) {
if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
}
int flagComparatorRank = RANK_COMPARATOR.compare(o1, o2);
if (flagComparatorRank != 0) {
return flagComparatorRank;
}
/* His rank is equal, then distance crowding RANK_COMPARATOR */
double distance1 = (double)o1.getAttributes().getAttribute("CrowdingDistance");
double distance2 = (double)o2.getAttributes().getAttribute("CrowdingDistance");
if (distance1 > distance2) {
return -1;
}
if (distance1 < distance2) {
return 1;
}
return 0;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public int compare(Solution o1, Solution o2) {
if (o1 == null) {
return 1;
} else if (o2 == null) {
return -1;
}
int flagComparatorRank = RANK_COMPARATOR.compare(o1, o2);
if (flagComparatorRank != 0) {
return flagComparatorRank;
}
/* His rank is equal, then distance crowding RANK_COMPARATOR */
double distance1 = (double)o1.getAlgorithmAttributes().getAttribute("CrowdingDistance");
double distance2 = (double)o2.getAlgorithmAttributes().getAttribute("CrowdingDistance");
if (distance1 > distance2) {
return -1;
}
if (distance1 < distance2) {
return 1;
}
return 0;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static LoggedInStatus webappLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException
{
// check if there a session and a login information attached to it
HttpSession session = request.getSession(true);
LoggedIn login = getUserLoggedIn(session);
/*if (login != null)
{
// check if this request needs admin rights and the user has them
if (requiresAdminRights && (! login.isAdmin()))
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS);
}
return new LoggedInStatus(login, LoggedInStatus.S_ALREADYLOGGEDIN);
}*/
// since the above failed, check if there is valid login information on the request parameters
String username = request.getParameter("username");
String password = request.getParameter("password");
login = getSuccessfulLogin(username, password);
if (login != null)
{
// check if this request needs admin rights and the user has them
if (requiresAdminRights && (! login.isAdmin()))
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS);
}
// add the login information to the session
session = request.getSession(true); // force the creation of a new session if there is none
session.setAttribute("login", login);
return new LoggedInStatus(login, LoggedInStatus.S_VALIDLOGIN);
}
// both situations failed
if (! request.getRequestURI().equalsIgnoreCase("/login.jsp"))
response.sendRedirect("/login.jsp");
if ((username == null) && (password == null))
return new LoggedInStatus(null, LoggedInStatus.S_NOINFORMATION);
else
return new LoggedInStatus(null, LoggedInStatus.S_INVALIDCREDENTIALS);
}
#location 33
#vulnerability type NULL_DEREFERENCE | #fixed code
public static LoggedInStatus webappLogin(HttpServletRequest request, HttpServletResponse response, boolean requiresAdminRights) throws IOException
{
// check if there a session and a login information attached to it
//HttpSession session = request.getSession(true);
//LoggedIn login = getUserLoggedIn(session);
/*if (login != null)
{
// check if this request needs admin rights and the user has them
if (requiresAdminRights && (! login.isAdmin()))
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS);
}
return new LoggedInStatus(login, LoggedInStatus.S_ALREADYLOGGEDIN);
}*/
// since the above failed, check if there is valid login information on the request parameters
String username = request.getParameter("username");
String password = request.getParameter("password");
LoggedIn login = getSuccessfulLogin(username, password);
if (login != null)
{
// check if this request needs admin rights and the user has them
if (requiresAdminRights && (! login.isAdmin()))
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new LoggedInStatus(null, LoggedInStatus.S_UNAUTHORIZEDACCESS);
}
// add the login information to the session
HttpSession session = request.getSession(true); // force the creation of a new session if there is none
session.setAttribute("login", login);
return new LoggedInStatus(login, LoggedInStatus.S_VALIDLOGIN);
}
// both situations failed
if ((username == null) && (password == null))
return new LoggedInStatus(null, LoggedInStatus.S_NOINFORMATION);
else
return new LoggedInStatus(null, LoggedInStatus.S_INVALIDCREDENTIALS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void printLine(SearchResult result){
StringBuilder builder = new StringBuilder();
HashMap<String, Object> extraFields = result.getExtraData();
for (String tag : tagsOrder) {
Object temp1 = extraFields.get(tag);
String temp1String = temp1.toString();
if(NumberUtils.isNumber(temp1String)){
temp1String = NumberUtils.createBigDecimal(temp1String).toPlainString();
}
String s = (temp1 != null) ? StringUtils.trimToEmpty(temp1String) : "";
if (s.length() > 0) {
String temp = StringUtils.replaceEach(s, searchChars, replaceChars);
builder.append('\"').append(temp).append("\";");
} else {
builder.append(";");
}
}
log.debug("Printing Line: ", builder.toString());
nLines++;
this.writter.println(builder.toString());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void printLine(SearchResult result){
StringBuilder builder = new StringBuilder();
HashMap<String, Object> extraFields = result.getExtraData();
for (String tag : tagsOrder) {
Object temp1 = extraFields.get(tag);
final String s = (temp1 != null) ?
temp1.toString().trim() : "";
if (s.length() > 0) {
String temp = StringUtils.replaceEach(s, searchChars, replaceChars);
builder.append('\"').append(temp).append("\";");
} else {
builder.append(";");
}
}
log.trace("Printing Line: ", builder.toString());
nLines++;
this.writter.println(builder.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void printLine(SearchResult result){
StringBuilder builder = new StringBuilder();
HashMap<String, Object> extraFields = result.getExtraData();
for (String tag : tagsOrder) {
Object temp1 = extraFields.get(tag);
String s = StringUtils.trimToEmpty(temp1.toString());
if (s.length() > 0) {
String temp = StringUtils.replaceEach(s, searchChars, replaceChars);
builder.append(temp).append(";");
} else {
builder.append(";");
}
}
log.debug("Printing Line: ", builder.toString());
nLines++;
this.writter.println(builder.toString());
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void printLine(SearchResult result){
StringBuilder builder = new StringBuilder();
HashMap<String, Object> extraFields = result.getExtraData();
for (String tag : tagsOrder) {
Object temp1 = extraFields.get(tag);
String s = (temp1 != null) ? StringUtils.trimToEmpty(temp1.toString()) : "";
if (s.length() > 0) {
String temp = StringUtils.replaceEach(s, searchChars, replaceChars);
builder.append(temp).append(";");
} else {
builder.append(";");
}
}
log.debug("Printing Line: ", builder.toString());
nLines++;
this.writter.println(builder.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void doGetExportCvs(HttpServletRequest req, HttpServletResponse resp) throws IOException{
resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv");
String queryString = req.getParameter("query");
String[] fields = req.getParameterValues("fields");
String[] providers = req.getParameterValues("providers");
boolean keyword = Boolean.parseBoolean(req.getParameter("keyword"));
System.out.println("queryString: "+ queryString);
for(String field: fields)
System.out.println("field: "+ field);
System.out.println("keyword: "+ keyword);
if(queryString == null)
resp.sendError(401, "Query Parameters not found");
if(fields == null || fields.length==0)
resp.sendError(402, "Fields Parameters not found");
if (!keyword) {
QueryExpressionBuilder q = new QueryExpressionBuilder(queryString);
queryString = q.getQueryString();
}
List<String> fieldList = new ArrayList<>(fields.length);
Map<String, String> fieldsMap = new HashMap<>();
for(String f : fields){
fieldList.add(f);
fieldsMap.put(f, f);
}
ExportToCSVQueryTask task = new ExportToCSVQueryTask( fieldList,
resp.getOutputStream());
if(providers == null || providers.length == 0) {
PluginController.getInstance().queryAll(task, queryString, fieldsMap);
} else {
List<String> providersList = new ArrayList<>();
for (String f : providers) {
providersList.add(f);
}
PluginController.getInstance().query(task, providersList, queryString,
fieldsMap);
}
task.await();
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
private void doGetExportCvs(HttpServletRequest req, HttpServletResponse resp) throws IOException{
resp.setHeader("Content-disposition","attachment; filename=QueryResultsExport.csv");
String queryString = req.getParameter("query");
String[] fields = req.getParameterValues("fields");
String[] providers = req.getParameterValues("providers");
boolean keyword = Boolean.parseBoolean(req.getParameter("keyword"));
logger.debug("queryString: {}", queryString);
logger.debug("fields: {}", Arrays.asList(fields));
logger.debug("keyword: {}", keyword);
if(queryString == null)
resp.sendError(401, "Query Parameters not found");
if(fields == null || fields.length==0)
resp.sendError(402, "Fields Parameters not found");
if (!keyword) {
QueryExpressionBuilder q = new QueryExpressionBuilder(queryString);
queryString = q.getQueryString();
}
List<String> fieldList = Arrays.asList(fields);
Map<String, String> fieldsMap = new HashMap<>();
for(String f : fields){
fieldsMap.put(f, f);
}
ExportToCSVQueryTask task = new ExportToCSVQueryTask( fieldList,
resp.getOutputStream());
if(providers == null || providers.length == 0) {
PluginController.getInstance().queryAll(task, queryString, fieldsMap);
} else {
List<String> providersList = Arrays.asList(providers);
PluginController.getInstance().query(task, providersList, queryString,
fieldsMap);
}
task.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void printFile(byte[] bytes) throws Exception {
InputStream in;
if(encrypt){
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(bytes);
in = new ByteArrayInputStream(encryptedBytes);
}
else
in = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(filename);
byte[] input = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(input)) != -1) {
out.write(input, 0, bytesRead);
out.flush();
}
out.close();
in.close();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public void printFile(byte[] bytes) throws IOException {
if (encrypt) {
byte[] encryptedBytes = new byte[0];
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedBytes = cipher.doFinal(bytes);
} catch (BadPaddingException e) {
logger.error("Invalid Key to decrypt users file.", e);
} catch (IllegalBlockSizeException e) {
logger.error("Users file \"{}\" is corrupted.", filename, e);
} catch (InvalidKeyException e) {
logger.error("Invalid Key to decrypt users file.", e);
}
printFileAux(encryptedBytes);
} else {
printFileAux(bytes);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//resp.addHeader("Access-Control-Allow-Origin", "*");
HttpSession session = req.getSession(false);
LoggedIn mLoggedIn = Session.getUserLoggedIn(session);
if(mLoggedIn == null){
resp.sendError(401);
return;
}
JSONObject json_resp = new JSONObject();
json_resp.put("user", mLoggedIn.getUserName());
json_resp.put("admin", mLoggedIn.isAdmin());
User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName());
JSONArray rolesObj = new JSONArray();
for (Role r : u.getRoles())
{
rolesObj.add(r.getName());
}
json_resp.put("roles", rolesObj);
//Set response content type
resp.setContentType("application/json");
//Write response
json_resp.write(resp.getWriter());
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String token = req.getHeader("Authorization");
User user = Authentication.getInstance().getUsername(token);
if(user == null) {
resp.sendError(401);
return;
}
JSONObject json_resp = new JSONObject();
json_resp.put("user", user.getUsername());
json_resp.put("admin", user.isAdmin());
JSONArray rolesObj = new JSONArray();
for (Role r : user.getRoles()) {
rolesObj.add(r.getName());
}
json_resp.put("roles", rolesObj);
//Set response content type
resp.setContentType("application/json");
//Write response
json_resp.write(resp.getWriter());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//resp.addHeader("Access-Control-Allow-Origin", "*");
//Try login
// Does not require admini rights.
LoggedIn mLoggedIn = Session.webappLogin(req, resp, false).getLogin();
//servletLogin(req, resp, true);//auth.login(user, pass);
if (mLoggedIn == null) {
resp.sendError(401, "Login failed");
return;
}
JSONObject json_resp = new JSONObject();
json_resp.put("user", mLoggedIn.getUserName());
json_resp.put("admin", mLoggedIn.isAdmin());
User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName());
JSONArray rolesObj = new JSONArray();
for (Role r : u.getRoles())
{
rolesObj.add(r.getName());
}
json_resp.put("roles", rolesObj);
json_resp.put("token", mLoggedIn.getToken());
//Set response content type
resp.setContentType("application/json");
//Write response
json_resp.write(resp.getWriter());
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//resp.addHeader("Access-Control-Allow-Origin", "*");
//Try login
// Does not require admini rights.
LoggedIn mLoggedIn = Session.webappLogin(req, resp, false).getLogin();
//servletLogin(req, resp, true);//auth.login(user, pass);
if (mLoggedIn == null) {
resp.sendError(401, "Login failed");
return;
}
JSONObject json_resp = new JSONObject();
json_resp.put("user", mLoggedIn.getUserName());
json_resp.put("admin", mLoggedIn.isAdmin());
User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName());
JSONArray rolesObj = new JSONArray();
if (u!=null&&u.getRoles()!=null) {
for (Role r : u.getRoles()) {
if (r!=null)
rolesObj.add(r.getName());
}
json_resp.put("roles", rolesObj);
}
json_resp.put("token", mLoggedIn.getToken());
//Set response content type
resp.setContentType("application/json");
//Write response
json_resp.write(resp.getWriter());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public JSONResource json(URI anUri) throws IOException, MalformedURLException {
JSONObject json = JSONObject.class.cast(anUri.toURL().openConnection().getContent());
return new JSONResource(json);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public JSONResource json(URI anUri) throws IOException {
return doGET(anUri, new JSONResource());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public JSONResource json(URI anUri) throws IOException, MalformedURLException {
JSONObject json = JSONObject.class.cast(anUri.toURL().openConnection().getContent());
return new JSONResource(json);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public JSONResource json(URI anUri) throws IOException {
return doGET(anUri, new JSONResource());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName(vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i)));
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong(vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
readMap.clear();
writeMap.clear();
populateReadWriteMaps();
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName((String) vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i)));
String index = vals.get("Index").get(i).toString();
if (readMap.containsKey(index)) {
ds.setReads(readMap.get(index));
}
if (writeMap.containsKey(index)) {
ds.setWrites(writeMap.get(index));
}
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong((String) vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Display[] getDisplays() {
List<Display> displays = new ArrayList<Display>();
ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose");
boolean foundEdid = false;
StringBuilder sb = new StringBuilder();
for (String s : xrandr) {
if (s.contains("EDID")) {
foundEdid = true;
sb = new StringBuilder();
continue;
}
if (foundEdid) {
sb.append(s.trim());
if (sb.length() >= 256) {
String edidStr = sb.toString();
LOG.debug("Parsed EDID: {}", edidStr);
Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr));
displays.add(display);
foundEdid = false;
}
}
}
return displays.toArray(new Display[displays.size()]);
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Display[] getDisplays() {
List<Display> displays = new ArrayList<Display>();
ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose");
if (xrandr != null) {
boolean foundEdid = false;
StringBuilder sb = new StringBuilder();
for (String s : xrandr) {
if (s.contains("EDID")) {
foundEdid = true;
sb = new StringBuilder();
continue;
}
if (foundEdid) {
sb.append(s.trim());
if (sb.length() >= 256) {
String edidStr = sb.toString();
LOG.debug("Parsed EDID: {}", edidStr);
Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr));
displays.add(display);
foundEdid = false;
}
}
}
}
return displays.toArray(new Display[displays.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Map<Integer, PerfCounterBlock> buildProcessMapFromPerfCounters(Collection<Integer> pids) {
Map<Integer, PerfCounterBlock> processMap = new HashMap<>();
Pair<List<String>, Map<ProcessPerformanceProperty, List<Long>>> instanceValues = ProcessInformation
.queryProcessCounters();
long now = System.currentTimeMillis(); // 1970 epoch
List<String> instances = instanceValues.getA();
Map<ProcessPerformanceProperty, List<Long>> valueMap = instanceValues.getB();
List<Long> pidList = valueMap.get(ProcessPerformanceProperty.PROCESSID);
List<Long> ppidList = valueMap.get(ProcessPerformanceProperty.PARENTPROCESSID);
List<Long> priorityList = valueMap.get(ProcessPerformanceProperty.PRIORITY);
List<Long> ioReadList = valueMap.get(ProcessPerformanceProperty.READTRANSFERCOUNT);
List<Long> ioWriteList = valueMap.get(ProcessPerformanceProperty.WRITETRANSFERCOUNT);
List<Long> workingSetSizeList = valueMap.get(ProcessPerformanceProperty.PRIVATEPAGECOUNT);
List<Long> creationTimeList = valueMap.get(ProcessPerformanceProperty.CREATIONDATE);
for (int inst = 0; inst < instances.size(); inst++) {
int pid = pidList.get(inst).intValue();
if (pids == null || pids.contains(pid)) {
// if creation time value is less than current millis, it's in 1970 epoch,
// otherwise it's 1601 epoch and we must convert
long ctime = creationTimeList.get(inst);
if (ctime > now) {
ctime = WinBase.FILETIME.filetimeToDate((int) (ctime >> 32), (int) (ctime & 0xffffffffL)).getTime();
}
processMap.put(pid,
new PerfCounterBlock(instances.get(inst), ppidList.get(inst).intValue(),
priorityList.get(inst).intValue(), workingSetSizeList.get(inst), ctime, now - ctime,
ioReadList.get(inst), ioWriteList.get(inst)));
}
}
return processMap;
}
#location 4
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static Map<Integer, PerfCounterBlock> buildProcessMapFromPerfCounters(Collection<Integer> pids) {
Map<Integer, PerfCounterBlock> processMap = new HashMap<>();
Pair<List<String>, Map<ProcessPerformanceProperty, List<Long>>> instanceValues = ProcessInformation
.queryProcessCounters();
long now = System.currentTimeMillis(); // 1970 epoch
List<String> instances = instanceValues.getA();
Map<ProcessPerformanceProperty, List<Long>> valueMap = instanceValues.getB();
List<Long> pidList = valueMap.get(ProcessPerformanceProperty.PROCESSID);
List<Long> ppidList = valueMap.get(ProcessPerformanceProperty.PARENTPROCESSID);
List<Long> priorityList = valueMap.get(ProcessPerformanceProperty.PRIORITY);
List<Long> ioReadList = valueMap.get(ProcessPerformanceProperty.READTRANSFERCOUNT);
List<Long> ioWriteList = valueMap.get(ProcessPerformanceProperty.WRITETRANSFERCOUNT);
List<Long> workingSetSizeList = valueMap.get(ProcessPerformanceProperty.PRIVATEPAGECOUNT);
List<Long> creationTimeList = valueMap.get(ProcessPerformanceProperty.CREATIONDATE);
List<Long> pageFaultsList = valueMap.get(ProcessPerformanceProperty.PAGEFAULTSPERSEC);
for (int inst = 0; inst < instances.size(); inst++) {
int pid = pidList.get(inst).intValue();
if (pids == null || pids.contains(pid)) {
// if creation time value is less than current millis, it's in 1970 epoch,
// otherwise it's 1601 epoch and we must convert
long ctime = creationTimeList.get(inst);
if (ctime > now) {
ctime = WinBase.FILETIME.filetimeToDate((int) (ctime >> 32), (int) (ctime & 0xffffffffL)).getTime();
}
processMap.put(pid,
new PerfCounterBlock(instances.get(inst), ppidList.get(inst).intValue(),
priorityList.get(inst).intValue(), workingSetSizeList.get(inst), ctime, now - ctime,
ioReadList.get(inst), ioWriteList.get(inst), pageFaultsList.get(inst).intValue()));
}
}
return processMap;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition",
DRIVE_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition",
LOGICAL_DISK_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_PROPERTIES, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap.put(deviceID,
new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid,
ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L),
((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive));
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_STRINGS, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap
.put(deviceID,
new HWPartition(
(String) hwPartitionQueryMap
.get(WmiProperty.NAME.name()).get(
i),
(String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i),
(String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid,
(Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i),
((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(),
logicalDrive));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public float getProcessorLoad() {
// should be same as on Mac. Not tested.
ArrayList<String> topResult = ExecutingCommand.runNative("top -l 1 -R -F -n1"); // cpu load is in [3]
String[] idle = topResult.get(3).split(" "); // idle value is in [6]
return 100 - Float.valueOf(idle[6].replace("%", ""));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public float getProcessorLoad() {
Scanner in = null;
try {
in = new Scanner(new FileReader("/proc/stat"));
} catch (FileNotFoundException e) {
System.err.println("Problem with: /proc/stat");
System.err.println(e.getMessage());
return -1;
}
in.useDelimiter("\n");
String[] result = in.next().split(" ");
ArrayList<Float> loads = new ArrayList<Float>();
for (String load : result) {
if (load.matches("-?\\d+(\\.\\d+)?")) {
loads.add(Float.valueOf(load));
}
}
// ((Total-PrevTotal)-(Idle-PrevIdle))/(Total-PrevTotal) - see http://stackoverflow.com/a/23376195/4359897
float totalCpuLoad = (loads.get(0) + loads.get(2))*100 / (loads.get(0) + loads.get(2) + loads.get(3));
return FormatUtil.round(totalCpuLoad, 2);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public long getAvailable() {
long returnCurrentUsageMemory = 0;
Scanner in = null;
try {
in = new Scanner(new FileReader("/proc/meminfo"));
} catch (FileNotFoundException e) {
return returnCurrentUsageMemory;
}
in.useDelimiter("\n");
while (in.hasNext()) {
String checkLine = in.next();
if (checkLine.startsWith("MemAvailable:")) {
String[] memorySplit = checkLine.split("\\s+");
returnCurrentUsageMemory = parseMeminfo(memorySplit);
break;
} else if (checkLine.startsWith("MemFree:")) {
String[] memorySplit = checkLine.split("\\s+");
returnCurrentUsageMemory += parseMeminfo(memorySplit);
} else if (checkLine.startsWith("Inactive:")) {
String[] memorySplit = checkLine.split("\\s+");
returnCurrentUsageMemory += parseMeminfo(memorySplit);
}
}
in.close();
return returnCurrentUsageMemory;
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
public long getAvailable() {
long availableMemory = 0;
List<String> memInfo = null;
try {
memInfo = FileUtil.readFile("/proc/meminfo");
} catch (IOException e) {
System.err.println("Problem with: /proc/meminfo");
System.err.println(e.getMessage());
return availableMemory;
}
for (String checkLine : memInfo) {
// If we have MemAvailable, it trumps all. See code in
// https://git.kernel.org/cgit/linux/kernel/git/torvalds/
// linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
if (checkLine.startsWith("MemAvailable:")) {
String[] memorySplit = checkLine.split("\\s+");
availableMemory = parseMeminfo(memorySplit);
break;
} else
// Otherwise we combine MemFree + Active(file), Inactive(file), and
// SReclaimable. Free+cached is no longer appropriate. MemAvailable
// reduces these values using watermarks to estimate when swapping
// is prevented, omitted here for simplicity (assuming 0 swap).
if (checkLine.startsWith("MemFree:")) {
String[] memorySplit = checkLine.split("\\s+");
availableMemory += parseMeminfo(memorySplit);
} else if (checkLine.startsWith("Active(file):")) {
String[] memorySplit = checkLine.split("\\s+");
availableMemory += parseMeminfo(memorySplit);
} else if (checkLine.startsWith("Inactive(file):")) {
String[] memorySplit = checkLine.split("\\s+");
availableMemory += parseMeminfo(memorySplit);
} else if (checkLine.startsWith("SReclaimable:")) {
String[] memorySplit = checkLine.split("\\s+");
availableMemory += parseMeminfo(memorySplit);
}
}
return availableMemory;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (valueMap.isEmpty()) {
return queryValuesFromWMI(propertyEnum, perfWmiClass);
}
return valueMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (!valueMap.isEmpty()) {
return valueMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryValuesFromWMI(propertyEnum, perfWmiClass);
} | 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.