output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, true); app.run(); }
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } ClueConfiguration config = ClueConfiguration.load(); String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, config, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, config, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, config, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine(); if (line == null || line.isEmpty()) continue; line = line.trim(); String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } }
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ app = new ClueApplication(idxLocation, false); String cmd = args[1]; String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } else{ app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } } } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile) && destFile.setReadOnly(); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } }
#vulnerable code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); }
#vulnerable code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { return operations.doWithSession(restOperations -> leaseEndpoints.renew(lease, restOperations)); }
#vulnerable code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { HttpEntity<Object> leaseRenewalEntity = getLeaseRenewalBody(lease); ResponseEntity<Map<String, Object>> entity = operations .doWithSession(restOperations -> (ResponseEntity) restOperations .exchange("sys/renew", HttpMethod.PUT, leaseRenewalEntity, Map.class)); Assert.state(entity != null && entity.getBody() != null, "Renew response must not be null"); Map<String, Object> body = entity.getBody(); String leaseId = (String) body.get("lease_id"); Number leaseDuration = (Number) body.get("lease_duration"); boolean renewable = (Boolean) body.get("renewable"); return Lease.of(leaseId, leaseDuration != null ? leaseDuration.longValue() : 0, renewable); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithSession(restOperations -> { try { ResponseEntity<Map<String, Boolean>> body = (ResponseEntity) restOperations .exchange("sys/init", HttpMethod.GET, emptyNamespace(null), Map.class); Assert.state(body.getBody() != null, "Initialization response must not be null"); return body.getBody().get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); }
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithVault(restOperations -> { try { Map<String, Boolean> body = restOperations.getForObject("sys/init", Map.class); Assert.state(body != null, "Initialization response must not be null"); return body.get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); }
#vulnerable code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, DEFAULT_FORCE_BATCH_STATEMENTS_ORDERING); }
#vulnerable code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, true); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context, Optional.empty()); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); }
#vulnerable code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments,true); return session.prepare(statement.getQueryString()); }
#vulnerable code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments); return session.prepare(statement.getQueryString()); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addInterceptorsToEntityMetas(List<Interceptor<?>> interceptors, Map<Class<?>, EntityMeta> entityMetaMap) { for (Interceptor<?> interceptor : interceptors) { Class<?> parentEntityClass = propertyParser.inferEntityClassFromInterceptor(interceptor); final Set<Class<?>> candidateEntityClasses = from(entityMetaMap.keySet()) .filter(new ChildClassOf(parentEntityClass)) .toSet(); for (Class<?> candidateEntityClass : candidateEntityClasses) { final EntityMeta entityMeta = entityMetaMap.get(candidateEntityClass); Validator.validateBeanMappingTrue(entityMeta != null, "The entity class '%s' is not found", parentEntityClass.getCanonicalName()); entityMeta.forInterception().addInterceptor(interceptor); } } }
#vulnerable code public void addInterceptorsToEntityMetas(List<Interceptor<?>> interceptors, Map<Class<?>, EntityMeta> entityMetaMap) { for (Interceptor<?> interceptor : interceptors) { Class<?> entityClass = propertyParser.inferEntityClassFromInterceptor(interceptor); EntityMeta entityMeta = entityMetaMap.get(entityClass); Validator.validateBeanMappingTrue(entityMeta != null, "The entity class '%s' is not found", entityClass.getCanonicalName()); entityMeta.forInterception().addInterceptor(interceptor); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Map<CQLQueryType, PreparedStatement> prepareClusteredCounterQueryMap(Session session, EntityMeta meta) { PropertyMeta idMeta = meta.getIdMeta(); PropertyMeta counterMeta = meta.getFirstMeta(); String tableName = meta.getTableName(); String counterName = counterMeta.getPropertyName(); RegularStatement incrementStatement = prepareWhereClauseForUpdate(idMeta,update(tableName) .with(incr(counterName, bindMarker())),false); RegularStatement decrementStatement = prepareWhereClauseForUpdate(idMeta,update(tableName) .with(decr(counterName, bindMarker())), false); RegularStatement selectStatement = prepareWhereClauseForSelect(idMeta, select(counterName).from(tableName)); RegularStatement deleteStatement = prepareWhereClauseForDelete(idMeta, QueryBuilder.delete().from(tableName)); Map<CQLQueryType, PreparedStatement> clusteredCounterPSMap = new HashMap<>(); clusteredCounterPSMap.put(INCR, session.prepare(incrementStatement)); clusteredCounterPSMap.put(DECR, session.prepare(decrementStatement)); clusteredCounterPSMap.put(SELECT, session.prepare(selectStatement)); clusteredCounterPSMap.put(DELETE, session.prepare(deleteStatement)); return clusteredCounterPSMap; }
#vulnerable code public Map<CQLQueryType, PreparedStatement> prepareClusteredCounterQueryMap(Session session, EntityMeta meta) { PropertyMeta idMeta = meta.getIdMeta(); PropertyMeta counterMeta = meta.getFirstMeta(); String tableName = meta.getTableName(); String counterName = counterMeta.getPropertyName(); RegularStatement incrStatement = prepareWhereClauseForUpdate(idMeta, update(tableName).with(incr(counterName, 100L))); String incr = incrStatement.getQueryString().replaceAll("100", "?"); RegularStatement decrStatement = prepareWhereClauseForUpdate(idMeta, update(tableName).with(decr(counterName, 100L))); String decr = decrStatement.getQueryString().replaceAll("100", "?"); RegularStatement selectStatement = prepareWhereClauseForSelect(idMeta, select(counterName).from(tableName)); String select = selectStatement.getQueryString(); RegularStatement deleteStatement = prepareWhereClauseForDelete(idMeta, QueryBuilder.delete().from(tableName)); String delete = deleteStatement.getQueryString(); Map<CQLQueryType, PreparedStatement> clusteredCounterPSMap = new HashMap<AchillesCounter.CQLQueryType, PreparedStatement>(); clusteredCounterPSMap.put(INCR, session.prepare(incr.toString())); clusteredCounterPSMap.put(DECR, session.prepare(decr.toString())); clusteredCounterPSMap.put(SELECT, session.prepare(select.toString())); clusteredCounterPSMap.put(DELETE, session.prepare(delete.toString())); return clusteredCounterPSMap; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } if (isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } }
#vulnerable code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } final StandardPodUtils podUtils = new StandardPodUtils( new DefaultKubernetesClient()); if (podUtils.isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:1+::{\"name\":\"tobi\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); }
#vulnerable code @Test public void testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String resource = resources.get(queryDecoder.path()); if (resource != null) { // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set content type HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); // write header ctx.write(res); // create resource inputstream and check InputStream is = getClass().getResourceAsStream(resource); if (is == null) { sendError(ctx, NOT_FOUND); return; } // write the stream ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is)); // close the channel on finish writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); File resource = resources.get(queryDecoder.path()); if (resource != null) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); if (isNotModified(req, resource)) { sendNotModified(ctx); req.release(); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(resource, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); setContentLength(res, fileLength); setContentTypeHeader(res, resource); setDateAndCacheHeaders(res, resource); // write the response header ctx.write(res); // write the content to the channel ChannelFuture writeFuture = writeContent(raf, fileLength, ctx.channel()); // close the request channel writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } super.channelRead(ctx, msg); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void disconnect() { ChannelFuture future = send(new Packet(PacketType.DISCONNECT)); if(future != null) { future.addListener(ChannelFutureListener.CLOSE); } onChannelDisconnect(); }
#vulnerable code public void disconnect() { ChannelFuture future = send(new Packet(PacketType.DISCONNECT)); future.addListener(ChannelFutureListener.CLOSE); onChannelDisconnect(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"woot\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("5:::{\"name\":\"woot\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { jsonSupport.writeValue(out, values); } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } }
#vulnerable code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { if (binary) { // handling websocket encoding bug ByteBuf b = allocateBuffer(allocator); try { ByteBufOutputStream os = new ByteBufOutputStream(b); jsonSupport.writeValue(os, values); CharsetEncoder enc = CharsetUtil.ISO_8859_1.newEncoder(); String str = b.toString(CharsetUtil.ISO_8859_1); if (enc.canEncode(str)) { buf.writeBytes(str.getBytes(CharsetUtil.UTF_8)); } else { buf.writeBytes(b); } } finally { b.release(); } } else { jsonSupport.writeValue(out, values); } } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } } #location 64 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeDisconnection() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("0::/woot", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.DISCONNECT, packet.getType()); Assert.assertEquals("/woot", packet.getNsp()); }
#vulnerable code @Test public void testDecodeDisconnection() throws IOException { Packet packet = decoder.decodePacket("0::/woot", null); Assert.assertEquals(PacketType.DISCONNECT, packet.getType()); Assert.assertEquals("/woot", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::woot", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("3:::woot", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); }
#vulnerable code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:1+::{\"a\":\"b\"}", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); }
#vulnerable code @Test public void testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePacket("4:1+::{\"a\":\"b\"}", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUTF8Decode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"Привет\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); }
#vulnerable code @Test public void testUTF8Decode() throws IOException { Packet packet = decoder.decodePacket("4:::\"Привет\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeId() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:1::asdfasdf", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); }
#vulnerable code @Test public void testDecodeId() throws IOException { Packet packet = decoder.decodePacket("3:1::asdfasdf", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeWithQueryString() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("1::/test:?test=1", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/test", packet.getNsp()); // Assert.assertEquals("?test=1", packet.getQs()); }
#vulnerable code @Test public void testDecodeWithQueryString() throws IOException { Packet packet = decoder.decodePacket("1::/test:?test=1", null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/test", packet.getNsp()); // Assert.assertEquals("?test=1", packet.getQs()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("6:::140", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("6:::140", null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodingNewline() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::\n", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); }
#vulnerable code @Test public void testDecodingNewline() throws IOException { Packet packet = decoder.decodePacket("3:::\n", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"2\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); }
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("4:::\"2\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:5:/tobi", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); }
#vulnerable code @Test public void testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePacket("3:5:/tobi", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String resource = resources.get(queryDecoder.path()); if (resource != null) { // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set content type HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); // write header ctx.write(res); // create resource inputstream and check InputStream is = getClass().getResourceAsStream(resource); if (is == null) { sendError(ctx, NOT_FOUND); return; } // write the stream ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is)); // close the channel on finish writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); File resource = resources.get(queryDecoder.path()); if (resource != null) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); if (isNotModified(req, resource)) { sendNotModified(ctx); req.release(); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(resource, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); setContentLength(res, fileLength); setContentTypeHeader(res, resource); setDateAndCacheHeaders(res, resource); // write the response header ctx.write(res); // write the content to the channel ChannelFuture writeFuture = writeContent(raf, fileLength, ctx.channel()); // close the request channel writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } super.channelRead(ctx, msg); } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: running simple benchmarks [" + timeout + " seconds]"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } }
#vulnerable code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null && System.getProperty("skipBenchmark").equals("true")) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: [PostfixExpression] simple benchmark"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canUpsertWithWriteConcern() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().concern(WriteConcern.SAFE).with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); assertThat(writeResult.getLastConcern()).isEqualTo(WriteConcern.SAFE); }
#vulnerable code @Test public void canUpsertWithWriteConcern() throws Exception { WriteConcern writeConcern = spy(WriteConcern.SAFE); /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}", writeConcern); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); verify(writeConcern).callGetLastError(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ People john = new People("John", "21 Jump Street"); collection.save(john); john.setAddress("new address"); /* when */ collection.save(john); /* then */ ObjectId johnId = john.getId(); People johnWithNewAddress = collection.findOne(johnId).as(People.class); assertThat(johnWithNewAddress.getId()).isEqualTo(johnId); assertThat(johnWithNewAddress.getAddress()).isEqualTo("new address"); }
#vulnerable code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ String idAsString = collection.save(new People("John", "21 Jump Street")); ObjectId id = new ObjectId(idAsString); People people = collection.findOne(id).as(People.class); people.setAddress("new address"); /* when */ collection.save(people); /* then */ people = collection.findOne(id).as(People.class); assertThat(people.getId()).isEqualTo(id); assertThat(people.getAddress()).isEqualTo("new address"); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(new People("John", new Coordinate(1, 1))); /* when */ People result = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(result.getId()).isEqualTo(id); }
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(this.people); /* when */ People people = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(people.getId()).isEqualTo(id); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ People john = new People("John", "21 Jump Street"); collection.save(john); john.setAddress("new address"); /* when */ collection.save(john); /* then */ ObjectId johnId = john.getId(); People johnWithNewAddress = collection.findOne(johnId).as(People.class); assertThat(johnWithNewAddress.getId()).isEqualTo(johnId); assertThat(johnWithNewAddress.getAddress()).isEqualTo("new address"); }
#vulnerable code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ String idAsString = collection.save(new People("John", "21 Jump Street")); ObjectId id = new ObjectId(idAsString); People people = collection.findOne(id).as(People.class); people.setAddress("new address"); /* when */ collection.save(people); /* then */ people = collection.findOne(id).as(People.class); assertThat(people.getId()).isEqualTo(id); assertThat(people.getAddress()).isEqualTo("new address"); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Party party = collection.findOne().as(Party.class); assertThat(party.friends).onProperty("name").containsExactly("Robert", "John"); }
#vulnerable code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Friends friends = collection.findOne().as(Friends.class); assertThat(friends.friends).onProperty("name").containsExactly("Robert", "John"); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOneWithObjectId() throws Exception { /* given */ Friend john = new Friend("John", "22 Wall Street Avenue"); collection.save(john); Friend foundFriend = collection.findOne(john.getId()).as(Friend.class); /* then */ assertThat(foundFriend).isNotNull(); assertThat(foundFriend.getId()).isEqualTo(john.getId()); }
#vulnerable code @Test public void canFindOneWithObjectId() throws Exception { /* given */ People john = new People("John", "22 Wall Street Avenue"); collection.save(john); People foundPeople = collection.findOne(john.getId()).as(People.class); /* then */ assertThat(foundPeople).isNotNull(); assertThat(foundPeople.getId()).isEqualTo(john.getId()); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOneWithEmptyQuery() throws Exception { /* given */ collection.save(new Friend("John", "22 Wall Street Avenue")); /* when */ Friend friend = collection.findOne().as(Friend.class); /* then */ assertThat(friend.getName()).isEqualTo("John"); }
#vulnerable code @Test public void canFindOneWithEmptyQuery() throws Exception { /* given */ collection.save(new People("John", "22 Wall Street Avenue")); /* when */ People people = collection.findOne().as(People.class); /* then */ assertThat(people.getName()).isEqualTo("John"); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canSaveAnObjectWithAnObjectId() throws Exception { People john = new People(new ObjectId("47cc67093475061e3d95369d"), "John"); collection.save(john); People result = collection.findOne(new ObjectId("47cc67093475061e3d95369d")).as(People.class); assertThat(result).isNotNull(); }
#vulnerable code @Test public void canSaveAnObjectWithAnObjectId() throws Exception { People john = new People(new ObjectId("47cc67093475061e3d95369d"), "John"); String id = collection.save(john); People result = collection.findOne(new ObjectId(id)).as(People.class); assertThat(result).isNotNull(); assertThat(result.getId()).isEqualTo("47cc67093475061e3d95369d"); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canFindOne() throws Exception { /* given */ collection.save(new Friend("John", "22 Wall Street Avenue")); /* when */ Friend friend = collection.findOne("{name:'John'}").as(Friend.class); /* then */ assertThat(friend.getName()).isEqualTo("John"); }
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ collection.save(new People("John", "22 Wall Street Avenue")); /* when */ People people = collection.findOne("{name:'John'}").as(People.class); /* then */ assertThat(people.getName()).isEqualTo("John"); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); }
#vulnerable code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String readFile(final String path) throws FileNotFoundException { try (Scanner scanner = new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8")) { return scanner.useDelimiter("\\Z").next().toString(); } }
#vulnerable code @Override public String readFile(final String path) throws FileNotFoundException { return new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8").useDelimiter("\\Z").next().toString(); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void createJarFromClassPathResources(final FileOutputStream fos, final String location) throws IOException { final Manifest m = new Manifest(); m.clear(); final Attributes global = m.getMainAttributes(); if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); } final File mylocation = new File(location); global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); global.putValue(AGENT_CLASS, AGENT_CLASS_NAME); global.putValue(CAN_REDEFINE_CLASSES, "true"); global.putValue(CAN_RETRANSFORM_CLASSES, "true"); global.putValue(CAN_SET_NATIVE_METHOD, "true"); try(JarOutputStream jos = new JarOutputStream(fos, m)) { addClass(Agent.class, jos); addClass(CodeCoverageStore.class, jos); addClass(InvokeReceiver.class, jos); } }
#vulnerable code private void createJarFromClassPathResources(final FileOutputStream fos, final String location) throws IOException { final Manifest m = new Manifest(); m.clear(); final Attributes global = m.getMainAttributes(); if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); } final File mylocation = new File(location); global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); global.putValue(AGENT_CLASS, AGENT_CLASS_NAME); global.putValue(CAN_REDEFINE_CLASSES, "true"); global.putValue(CAN_RETRANSFORM_CLASSES, "true"); global.putValue(CAN_SET_NATIVE_METHOD, "true"); final JarOutputStream jos = new JarOutputStream(fos, m); addClass(Agent.class, jos); addClass(CodeCoverageStore.class, jos); addClass(InvokeReceiver.class, jos); jos.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); try(BufferedInputStream stream = new BufferedInputStream( resource.openStream())) { final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } }
#vulnerable code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { try { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); final BufferedInputStream stream = new BufferedInputStream( resource.openStream()); final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } stream.close(); return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Tokenizer create(Reader reader) { Seg seg_method=null; if(seg_type.equals("max_word")){ seg_method = new MaxWordSeg(dic); }else if(seg_type.equals("complex")){ seg_method = new ComplexSeg(dic); }else if(seg_type.equals("simple")){ seg_method =new SimpleSeg(dic); } return new MMSegTokenizer(seg_method,reader); }
#vulnerable code @Override public Tokenizer create(Reader reader) { logger.info(seg_type); Seg seg_method=null; if(seg_type.equals("max_word")){ seg_method = new MaxWordSeg(dic); }else if(seg_type.equals("complex")){ seg_method = new ComplexSeg(dic); }else if(seg_type.equals("simple")){ seg_method =new SimpleSeg(dic); } logger.info(seg_method.toString()); return new MMSegTokenizer(seg_method,reader); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean register(HttpServletResponse response , String userName , String passWord , String salt) { MiaoshaUser miaoShaUser = new MiaoshaUser(); miaoShaUser.setNickname(userName); String DBPassWord = MD5Utils.formPassToDBPass(passWord , salt); miaoShaUser.setPassword(DBPassWord); miaoShaUser.setRegisterDate(new Date()); miaoShaUser.setSalt(salt); miaoShaUser.setNickname(userName); try { miaoShaUserDao.insertMiaoShaUser(miaoShaUser); MiaoshaUser user = miaoShaUserDao.getById(Long.valueOf(miaoShaUser.getNickname())); if(user == null){ return false; } //生成cookie 将session返回游览器 分布式session String token= UUIDUtil.uuid(); addCookie(response, token, user); } catch (Exception e) { logger.error("注册失败",e); return false; } return true; }
#vulnerable code public boolean register(HttpServletResponse response , String userName , String passWord , String salt) { MiaoshaUser miaoShaUser = new MiaoshaUser(); miaoShaUser.setNickname(userName); String DBPassWord = MD5Utils.formPassToDBPass(passWord , salt); miaoShaUser.setPassword(DBPassWord); miaoShaUser.setRegisterDate(new Date()); miaoShaUser.setSalt(salt); miaoShaUser.setNickname(userName); try { miaoShaUserDao.insertMiaoShaUser(miaoShaUser); MiaoshaUser user = miaoShaUserDao.getById(miaoShaUser.getId()); if(user == null){ return false; } //生成cookie 将session返回游览器 分布式session String token= UUIDUtil.uuid(); addCookie(response, token, user); } catch (Exception e) { logger.error("注册失败",e); return false; } return true; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); }
#vulnerable code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); // return entityManagerFactory.createEntityManager(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); }
#vulnerable code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); // return entityManagerFactory.createEntityManager(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (!isFixed()) { String style = activator.getAttribute("style"); if (alwaysShowActivator) { activator.setAttribute("style", style + "; display: block !important"); } else { activator.setAttribute("style", style + "; display: none !important"); } activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); }
#vulnerable code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (alwaysShowActivator || !isFixed()) { String style = activator.getAttribute("style"); activator.setAttribute("style", style + "; display: block !important"); activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void add(Widget child) { super.add(wrap(child)); }
#vulnerable code @Override public void add(Widget child) { if(child instanceof MaterialImage) { child.getElement().getStyle().setProperty("border", "1px solid #e9e9e9"); child.getElement().getStyle().setProperty("textAlign", "center"); } boolean collapsible = child instanceof MaterialCollapsible; if(collapsible) { // Since the collapsible is separ ((MaterialCollapsible)child).addClearActiveHandler(new ClearActiveHandler() { @Override public void onClearActive(ClearActiveEvent event) { clearActive(); } }); } if(!(child instanceof ListItem)) { // Direct list item not collapsible final ListItem listItem = new ListItem(); if(child instanceof MaterialCollapsible) { listItem.getElement().getStyle().setBackgroundColor("transparent"); } if(child instanceof HasWaves) { listItem.setWaves(((HasWaves) child).getWaves()); ((HasWaves) child).setWaves(null); } listItem.add(child); child = listItem; } // Collapsible's should not be selectable final Widget finalChild = child; if(!collapsible) { // Active click handler finalChild.addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearActive(); finalChild.addStyleName("active"); } }, ClickEvent.getType()); } child.getElement().getStyle().setDisplay(Style.Display.BLOCK); super.add(child); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setValue(Integer value, boolean fireEvents) { try { checkRangeValue(value); setIntToRangeElement(VALUE, value); } catch(Exception e) { getLogger().log(Level.SEVERE, e.getMessage()); } super.setValue(value, fireEvents); }
#vulnerable code @Override public void setValue(Integer value, boolean fireEvents) { if (value == null) { GWT.log("Value must be null", new RuntimeException()); return; } if (value < getMin()) { GWT.log("Value must not be less than the minimum range value.", new RuntimeException()); return; } if (value > getMax()) { GWT.log("Value must not be greater than the maximum range value", new RuntimeException()); return; } setIntToRangeElement(VALUE, value); super.setValue(value, fireEvents); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void applyOverlayType() { setShowOnAttach(false); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); }
#vulnerable code protected void applyOverlayType() { setShowOnAttach(false); getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void add(Widget child) { super.add(wrap(child)); }
#vulnerable code @Override public void add(Widget child) { if(child instanceof MaterialImage) { child.getElement().getStyle().setProperty("border", "1px solid #e9e9e9"); child.getElement().getStyle().setProperty("textAlign", "center"); } boolean collapsible = child instanceof MaterialCollapsible; if(collapsible) { // Since the collapsible is separ ((MaterialCollapsible)child).addClearActiveHandler(new ClearActiveHandler() { @Override public void onClearActive(ClearActiveEvent event) { clearActive(); } }); } if(!(child instanceof ListItem)) { // Direct list item not collapsible final ListItem listItem = new ListItem(); if(child instanceof MaterialCollapsible) { listItem.getElement().getStyle().setBackgroundColor("transparent"); } if(child instanceof HasWaves) { listItem.setWaves(((HasWaves) child).getWaves()); ((HasWaves) child).setWaves(null); } listItem.add(child); child = listItem; } // Collapsible's should not be selectable final Widget finalChild = child; if(!collapsible) { // Active click handler finalChild.addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearActive(); finalChild.addStyleName("active"); } }, ClickEvent.getType()); } child.getElement().getStyle().setDisplay(Style.Display.BLOCK); super.add(child); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doRender(RunTemplate runTemplate, NumbericRenderData numbericData, XWPFTemplate template) throws Exception { NiceXWPFDocument doc = template.getXWPFDocument(); XWPFRun run = runTemplate.getRun(); List<TextRenderData> datas = numbericData.getNumbers(); Style fmtStyle = numbericData.getFmtStyle(); BigInteger numID = doc.addNewNumbericId(numbericData.getNumFmt()); XWPFParagraph paragraph; XWPFRun newRun; for (TextRenderData line : datas) { paragraph = doc.insertNewParagraph(run); paragraph.setNumID(numID); CTP ctp = paragraph.getCTP(); CTPPr pPr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr(); CTParaRPr pr = pPr.isSetRPr() ? pPr.getRPr() : pPr.addNewRPr(); StyleUtils.styleRpr(pr, fmtStyle); newRun = paragraph.createRun(); StyleUtils.styleRun(newRun, line.getStyle()); newRun.setText(line.getText()); } }
#vulnerable code @Override public void doRender(RunTemplate runTemplate, NumbericRenderData numbericData, XWPFTemplate template) throws Exception { NiceXWPFDocument doc = template.getXWPFDocument(); XWPFRun run = runTemplate.getRun(); List<TextRenderData> datas = numbericData.getNumbers(); Style fmtStyle = numbericData.getFmtStyle(); BigInteger numID = doc.addNewNumbericId(numbericData.getNumFmt()); XWPFParagraph paragraph; XWPFRun newRun; for (TextRenderData line : datas) { paragraph = doc.insertNewParagraph(run); paragraph.setNumID(numID); CTP ctp = paragraph.getCTP(); CTPPr pPr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr(); CTParaRPr pr = pPr.isSetRPr() ? pPr.getRPr() : pPr.addNewRPr(); StyleUtils.styleRpr(pr, fmtStyle); newRun = paragraph.createRun(); StyleUtils.styleRun(newRun, line.getStyle()); newRun.setText(line.getText()); } // 成功后清除标签 clearPlaceholder(run); IRunBody parent = run.getParent(); if (parent instanceof XWPFParagraph) { ((XWPFParagraph) parent).removeRun(runTemplate.getRunPos()); // To do: 更好的列表样式 // ((XWPFParagraph) parent).setSpacingBetween(0, // LineSpacingRule.AUTO); } } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void writeToFile(String path) throws IOException { FileOutputStream out = null; try { out = new FileOutputStream(path); this.write(out); out.flush(); } finally { PoitlIOUtils.closeQuietlyMulti(this.doc, out); } }
#vulnerable code public void writeToFile(String path) throws IOException { FileOutputStream out = new FileOutputStream(path); this.write(out); this.close(); out.flush(); out.close(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] getUrlByteArray(String urlPath) { try { return toByteArray(getUrlPictureStream(urlPath)); } catch (IOException e) { logger.error("getUrlPictureStream error,{},{}", urlPath, e); } return null; }
#vulnerable code public static byte[] getUrlByteArray(String urlPath) { return toByteArray(getUrlPictureStream(urlPath)); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void afterRender(RenderContext context) { clearPlaceholder(context, true); // IRunBody parent = run.getParent(); // if (parent instanceof XWPFParagraph) { // ((XWPFParagraph) parent).removeRun(((RunTemplate) context.getEleTemplate()).getRunPos()); // // To do: 更好的列表样式 // // ((XWPFParagraph) parent).setSpacingBetween(0, // // LineSpacingRule.AUTO); // } }
#vulnerable code @Override protected void afterRender(RenderContext context) { XWPFRun run = ((RunTemplate) context.getEleTemplate()).getRun(); clearPlaceholder(context); IRunBody parent = run.getParent(); if (parent instanceof XWPFParagraph) { ((XWPFParagraph) parent).removeRun(((RunTemplate) context.getEleTemplate()).getRunPos()); // To do: 更好的列表样式 // ((XWPFParagraph) parent).setSpacingBetween(0, // LineSpacingRule.AUTO); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); super.visit((IterableTemplate) iterableTemplate); }
#vulnerable code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(iterableTemplate); Object compute = renderDataCompute.compute(iterableTemplate.getStartMark().getTagName()); int times = conditionTimes(compute); if (TIMES_ONCE == times) { RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(compute); new DocumentProcessor(this.template, dataCompute).process(iterableTemplate.getTemplates()); } else if (TIMES_N == times) { RunTemplate start = iterableTemplate.getStartMark(); RunTemplate end = iterableTemplate.getEndMark(); XWPFRun startRun = start.getRun(); XWPFRun endRun = end.getRun(); XWPFParagraph currentParagraph = (XWPFParagraph) startRun.getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = start.getRunPos(); Integer endRunPos = end.getRunPos(); CTR endCtr = endRun.getCTR(); Iterable<?> model = (Iterable<?>) compute; Iterator<?> iterator = model.iterator(); while (iterator.hasNext()) { // copy position cursor int insertPostionCursor = end.getRunPos(); // copy content List<XWPFRun> runs = currentParagraph.getRuns(); List<XWPFRun> copies = new ArrayList<XWPFRun>(); for (int i = startRunPos + 1; i < endRunPos; i++) { insertPostionCursor = end.getRunPos(); XWPFRun xwpfRun = runs.get(i); XWPFRun insertNewRun = paragraphWrapper.insertNewRun(xwpfRun, insertPostionCursor); XWPFRun xwpfRun2 = paragraphWrapper.createRun(xwpfRun, (IRunBody)currentParagraph); paragraphWrapper.setAndUpdateRun(xwpfRun2, insertNewRun, insertPostionCursor); XmlCursor newCursor = endCtr.newCursor(); newCursor.toPrevSibling(); XmlObject object = newCursor.getObject(); XWPFRun copy = paragraphWrapper.createRun(object, (IRunBody)currentParagraph); copies.add(copy); paragraphWrapper.setAndUpdateRun(copy, xwpfRun2, insertPostionCursor); } // re-parse List<MetaTemplate> templates = template.getResolver().resolveXWPFRuns(copies); // render RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(iterator.next()); new DocumentProcessor(this.template, dataCompute).process(templates); } // clear self iterable template for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } else { XWPFParagraph currentParagraph = (XWPFParagraph) iterableTemplate.getStartRun().getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = iterableTemplate.getStartMark().getRunPos(); Integer endRunPos = iterableTemplate.getEndMark().getRunPos(); for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } bodyContainer.clearPlaceholder(iterableTemplate.getStartRun()); bodyContainer.clearPlaceholder(iterableTemplate.getEndRun()); } #location 65 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); super.visit((IterableTemplate) iterableTemplate); }
#vulnerable code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(iterableTemplate); Object compute = renderDataCompute.compute(iterableTemplate.getStartMark().getTagName()); int times = conditionTimes(compute); if (TIMES_ONCE == times) { RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(compute); new DocumentProcessor(this.template, dataCompute).process(iterableTemplate.getTemplates()); } else if (TIMES_N == times) { RunTemplate start = iterableTemplate.getStartMark(); RunTemplate end = iterableTemplate.getEndMark(); XWPFRun startRun = start.getRun(); XWPFRun endRun = end.getRun(); XWPFParagraph currentParagraph = (XWPFParagraph) startRun.getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = start.getRunPos(); Integer endRunPos = end.getRunPos(); CTR endCtr = endRun.getCTR(); Iterable<?> model = (Iterable<?>) compute; Iterator<?> iterator = model.iterator(); while (iterator.hasNext()) { // copy position cursor int insertPostionCursor = end.getRunPos(); // copy content List<XWPFRun> runs = currentParagraph.getRuns(); List<XWPFRun> copies = new ArrayList<XWPFRun>(); for (int i = startRunPos + 1; i < endRunPos; i++) { insertPostionCursor = end.getRunPos(); XWPFRun xwpfRun = runs.get(i); XWPFRun insertNewRun = paragraphWrapper.insertNewRun(xwpfRun, insertPostionCursor); XWPFRun xwpfRun2 = paragraphWrapper.createRun(xwpfRun, (IRunBody)currentParagraph); paragraphWrapper.setAndUpdateRun(xwpfRun2, insertNewRun, insertPostionCursor); XmlCursor newCursor = endCtr.newCursor(); newCursor.toPrevSibling(); XmlObject object = newCursor.getObject(); XWPFRun copy = paragraphWrapper.createRun(object, (IRunBody)currentParagraph); copies.add(copy); paragraphWrapper.setAndUpdateRun(copy, xwpfRun2, insertPostionCursor); } // re-parse List<MetaTemplate> templates = template.getResolver().resolveXWPFRuns(copies); // render RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(iterator.next()); new DocumentProcessor(this.template, dataCompute).process(templates); } // clear self iterable template for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } else { XWPFParagraph currentParagraph = (XWPFParagraph) iterableTemplate.getStartRun().getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = iterableTemplate.getStartMark().getRunPos(); Integer endRunPos = iterableTemplate.getEndMark().getRunPos(); for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } bodyContainer.clearPlaceholder(iterableTemplate.getStartRun()); bodyContainer.clearPlaceholder(iterableTemplate.getEndRun()); } #location 65 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); validate(chartSeries, data); int totalSeriesCount = ensureSeriesCount(chart, chartSeries); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> currentSeriesData = null; if (chartSeries.size() <= 1) { // ignore combo type currentSeriesData = data.getSeriesDatas(); } else { currentSeriesData = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(currentSeriesData); int currentSeriesSize = currentSeriesData.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < currentSeriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, currentSeriesData.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = currentSeriesData.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, currentSeriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); }
#vulnerable code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { if (null == data) return; XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); // validate combo if (chartSeries.size() >= 2) { long nullCount = data.getSeriesDatas().stream().filter(d -> null == d.getComboType()).count(); if (nullCount > 0) throw new RenderException("Combo chart must set comboType field of series!"); } // hack for poi 4.1.1+: repair seriesCount value, int totalSeriesCount = chartSeries.stream().mapToInt(XDDFChartData::getSeriesCount).sum(); Field field = ReflectionUtils.findField(XDDFChart.class, "seriesCount"); field.setAccessible(true); field.set(chart, totalSeriesCount); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> seriesDatas = null; if (chartSeries.size() <= 1) { // ignore combo type seriesDatas = data.getSeriesDatas(); } else { seriesDatas = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(seriesDatas); int seriesSize = seriesDatas.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < seriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, seriesDatas.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = seriesDatas.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, seriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<NiceXWPFDocument> getMergedDocxs(DocxRenderData data, Configure configure) throws IOException { List<NiceXWPFDocument> docs = new ArrayList<NiceXWPFDocument>(); byte[] docx = data.getDocx(); List<?> dataList = data.getDataList(); if (null == dataList || dataList.isEmpty()) { try { // 待合并的文档不是模板 docs.add(new NiceXWPFDocument(new ByteArrayInputStream(docx))); } catch (Exception e) { logger.error("Cannot get the merged docx.", e); } } else { for (int i = 0; i < dataList.size(); i++) { XWPFTemplate temp = XWPFTemplate.compile(new ByteArrayInputStream(docx) , configure); temp.render(dataList.get(i)); docs.add(temp.getXWPFDocument()); } } return docs; }
#vulnerable code private List<NiceXWPFDocument> getMergedDocxs(DocxRenderData data, Configure configure) { List<NiceXWPFDocument> docs = new ArrayList<NiceXWPFDocument>(); File docx = data.getDocx(); List<?> dataList = data.getDataList(); if (null == dataList || dataList.isEmpty()) { try { // 待合并的文档不是模板 docs.add(new NiceXWPFDocument(new FileInputStream(docx))); } catch (Exception e) { logger.error("Cannot get the merged docx.", e); } } else { for (int i = 0; i < dataList.size(); i++) { XWPFTemplate temp = XWPFTemplate.compile(docx, configure); temp.render(dataList.get(i)); docs.add(temp.getXWPFDocument()); } } return docs; } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), is("Hello, world!")); } }
#vulnerable code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); final byte[] bytes = new byte[(int) response.getEntity().getContentLength()]; new DataInputStream(response.getEntity().getContent()).readFully(bytes); assertThat(new String(bytes, UTF_8), is("Hello, world!")); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void jdk() throws IOException, ScriptException { String script = new String(Files.readAllBytes(new File("../dist/bundle.js").toPath())); ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js"); //js.eval(script); V8 v8 = V8.createV8Runtime(); v8.registerJavaMethod(System.out,"println","print",new Class[]{Object.class}); v8.executeVoidScript("console={log:function(a){print(a);}};setTimeout=function(a){print(a);};clearTimeout=function(a){print(a);};"+ "setInterval=function(a){print(a);};clearInterval=function(a){print(a);};"+script); Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); }
#vulnerable code @Test void jdk() { Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void ex8() throws IOException { //## image Graphviz g = Graphviz.fromGraph(graph() .with(node(" ").with(Size.std().margin(.8, .7), Image.of("graphviz.png")))); g.basedir(new File("example")).render(Format.PNG).toFile(new File("example/ex8.png")); //## image }
#vulnerable code @Test void ex8() throws IOException { //## image Graphviz.useEngine(new GraphvizV8Engine()); Graphviz g = Graphviz.fromGraph(graph() .with(node(" ").with(Size.std().margin(.8, .7), Image.of("graphviz.png")))); g.basedir(new File("example")).render(Format.PNG).toFile(new File("example/ex8.png")); //## image } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void jdk() { Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); }
#vulnerable code @Test void jdk() throws IOException, ScriptException { String script = new String(Files.readAllBytes(new File("../dist/bundle.js").toPath())); ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js"); //js.eval(script); V8 v8 = V8.createV8Runtime(); v8.registerJavaMethod(System.out, "println", "print", new Class[]{Object.class}); v8.executeVoidScript("console={log:function(a){print(a);}};setTimeout=function(a){print(a);};clearTimeout=function(a){print(a);};" + "setInterval=function(a){print(a);};clearInterval=function(a){print(a);};" + script); Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void cmdLineOutputDotFile() throws IOException, InterruptedException { final File dotOutputFolder = new File(temp, "out"); dotOutputFolder.mkdir(); final String dotOutputName = "test123"; // Configure engine to output the dotFile to dotOutputFolder final GraphvizCmdLineEngine engine = new GraphvizCmdLineEngine() .searchPath(setUpFakeDotFile().getParent()) .executor(setUpFakeStubCommandExecutor()); engine.setDotOutputFile(dotOutputFolder.getAbsolutePath(), dotOutputName); Graphviz.useEngine(engine); // Do execution Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(); assertTrue(new File(dotOutputFolder.getAbsolutePath(), dotOutputName + ".dot").exists()); }
#vulnerable code @Test void cmdLineOutputDotFile() throws IOException, InterruptedException { final File dotFile = setUpFakeDotFile(); final CommandLineExecutor cmdExecutor = setUpFakeStubCommandExecutor(); final String envPath = dotFile.getParent(); final File dotOutputFolder = new File(temp, "out"); dotOutputFolder.mkdir(); final String dotOutputName = "test123"; // Configure engine to output the dotFile to dotOutputFolder final GraphvizCmdLineEngine engine = new GraphvizCmdLineEngine(envPath, cmdExecutor); engine.setDotOutputFile(dotOutputFolder.getAbsolutePath(), dotOutputName); Graphviz.useEngine(engine); // Do execution Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(); assertTrue(new File(dotOutputFolder.getAbsolutePath(), dotOutputName + ".dot").exists()); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void releaseEngine() { synchronized (Graphviz.class) { if (engine != null) { doReleaseEngine(engine); } if (engineQueue != null) { for (final GraphvizEngine engine : engineQueue) { doReleaseEngine(engine); } } } engine = null; engineQueue = null; }
#vulnerable code public static void releaseEngine() { if (engine != null) { try { engine.close(); } catch (Exception e) { throw new GraphvizException("Problem closing engine", e); } } engine = null; engineQueue = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void releaseEngine() { synchronized (Graphviz.class) { if (engine != null) { doReleaseEngine(engine); } if (engineQueue != null) { for (final GraphvizEngine engine : engineQueue) { doReleaseEngine(engine); } } } engine = null; engineQueue = null; }
#vulnerable code public static void releaseEngine() { if (engine != null) { try { engine.close(); } catch (Exception e) { throw new GraphvizException("Problem closing engine", e); } } engine = null; engineQueue = null; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void start(List<GraphvizEngine> engines) throws IOException { final String executable = SystemUtils.executableName("java"); final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); }
#vulnerable code public static void start(List<GraphvizEngine> engines) throws IOException { final boolean windows = System.getProperty("os.name").contains("windows"); final String executable = windows ? "java.exe" : "java"; final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } downloader.setThread(threadNum); }
#vulnerable code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site.toTask()); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); }
#vulnerable code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Spider thread(int threadNum) { checkIfRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } return this; }
#vulnerable code public Spider thread(int threadNum) { checkIfRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetHtmlCharset() throws Exception { HttpServer server = httpserver(12306); server.get(by(uri("/header"))).response(header("Content-Type", "text/html; charset=gbk")); server.get(by(uri("/meta4"))).response(with(text("<html>\n" + " <head>\n" + " <meta charset='gbk'/>\n" + " </head>\n" + " <body></body>\n" + "</html>")),header("Content-Type","")); server.get(by(uri("/meta5"))).response(with(text("<html>\n" + " <head>\n" + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\" />\n" + " </head>\n" + " <body></body>\n" + "</html>")),header("Content-Type","")); Runner.running(server, new Runnable() { @Override public void run() { String charset = getCharsetByUrl("http://127.0.0.1:12306/header"); assertEquals(charset, "gbk"); charset = getCharsetByUrl("http://127.0.0.1:12306/meta4"); assertEquals(charset, "gbk"); charset = getCharsetByUrl("http://127.0.0.1:12306/meta5"); assertEquals(charset, "gbk"); } private String getCharsetByUrl(String url) { HttpClientDownloader downloader = new HttpClientDownloader(); Site site = Site.me(); CloseableHttpClient httpClient = new HttpClientGenerator().getClient(site); // encoding in http header Content-Type Request requestGBK = new Request(url); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestGBK, site, null)); } catch (IOException e) { e.printStackTrace(); } String charset = null; try { byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity().getContent()); charset = downloader.getHtmlCharset(httpResponse,contentBytes); } catch (IOException e) { e.printStackTrace(); } return charset; } }); }
#vulnerable code @Test public void testGetHtmlCharset() throws IOException { HttpClientDownloader downloader = new HttpClientDownloader(); Site site = Site.me(); CloseableHttpClient httpClient = new HttpClientGenerator().getClient(site); // encoding in http header Content-Type Request requestGBK = new Request("http://sports.163.com/14/0514/13/9S7986F300051CA1.html#p=9RGQDGGH0AI90005"); CloseableHttpResponse httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestGBK, site, null)); String charset = downloader.getHtmlCharset(httpResponse); assertEquals(charset, "GBK"); // encoding in meta Request requestUTF_8 = new Request("http://preshing.com/"); httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestUTF_8, site, null)); charset = downloader.getHtmlCharset(httpResponse); assertEquals(charset, "utf-8"); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } downloader.setThread(threadNum); }
#vulnerable code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (threadNum <= 1) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (executorService == null) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); }
#vulnerable code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); Page page = null; page.getJson().jsonPath("$.name").get(); page.getJson().removePadding("callback").jsonPath("$.name").get(); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; }
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadPool.getThreadAlive() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadPool.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); onSuccess(requestFinal); } catch (Exception e) { onError(requestFinal); logger.error("process request " + requestFinal + " error", e); } finally { pageCount.incrementAndGet(); signalNewUrl(); } } }); } } stat.set(STAT_STOPPED); // release some resources if (destroyWhenExit) { close(); } }
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadPool.getThreadAlive() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadPool.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); onSuccess(requestFinal); } catch (Exception e) { onError(requestFinal); logger.error("process request " + requestFinal + " error", e); } finally { if (site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) requestFinal.getExtra(Request.PROXY), (Integer) requestFinal .getExtra(Request.STATUS_CODE)); } pageCount.incrementAndGet(); signalNewUrl(); } } }); } } stat.set(STAT_STOPPED); // release some resources if (destroyWhenExit) { close(); } } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Spider thread(int threadNum) { checkIfNotRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; }
#vulnerable code public Spider thread(int threadNum) { checkIfNotRunning(); if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (downloader==null || downloader instanceof HttpClientDownloader){ downloader = new HttpClientDownloader(threadNum); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setThread(int thread) { poolSize = thread; }
#vulnerable code @Override public void setThread(int thread) { poolSize = thread; httpClientPool = new HttpClientPool(thread); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void pushWhenNoDuplicate(Request request, Task task) { /* if (!inited.get()) { init(task); }*/ queue.add(request); fileUrlWriter.println(request.getUrl()); }
#vulnerable code @Override protected void pushWhenNoDuplicate(Request request, Task task) { if (!inited.get()) { init(task); } queue.add(request); fileUrlWriter.println(request.getUrl()); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void setThread(int thread) { httpClientGenerator.setPoolSize(thread); }
#vulnerable code @Override public void setThread(int thread) { poolSize = thread; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } }
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } if (site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) request.getExtra(Request.PROXY), (Integer) request .getExtra(Request.STATUS_CODE)); } } } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (threadNum <= 1) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (executorService == null) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.