instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap,
CurrentStateOutput currentStateOutput) {
ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name());
Map<String, Resource> restOfResources = new HashMap<>(resourceMap);
BestPossibleStateOutput output = new BestPossibleStateOutput();
final List<String> failureResources = new ArrayList<>();
// Queues only for Workflows
scheduleWorkflows(resourceMap, cache, restOfResources, failureResources);
// Current rest of resources including: jobs + only current state left over ones
Iterator<Resource> itr = restOfResources.values().iterator();
while (itr.hasNext()) {
Resource resource = itr.next();
if (!computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output)) {
failureResources.add(resource.getResourceName());
LogUtil.logWarn(logger, _eventId,
"Failed to calculate best possible states for " + resource.getResourceName());
}
}
return output;
}
|
#vulnerable code
private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap,
CurrentStateOutput currentStateOutput) {
ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name());
BestPossibleStateOutput output = new BestPossibleStateOutput();
PriorityQueue<TaskSchedulingStage.ResourcePriority> resourcePriorityQueue =
new PriorityQueue<>();
TaskDriver taskDriver = null;
HelixManager helixManager = event.getAttribute(AttributeName.helixmanager.name());
if (helixManager != null) {
taskDriver = new TaskDriver(helixManager);
}
for (Resource resource : resourceMap.values()) {
resourcePriorityQueue.add(new TaskSchedulingStage.ResourcePriority(resource,
cache.getIdealState(resource.getResourceName()), taskDriver));
}
// TODO: Replace this looping available resources with Workflow Queues
for (Iterator<TaskSchedulingStage.ResourcePriority> itr = resourcePriorityQueue.iterator();
itr.hasNext(); ) {
Resource resource = itr.next().getResource();
if (!computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output)) {
LogUtil
.logWarn(logger, _eventId, "Failed to assign tasks for " + resource.getResourceName());
}
}
return output;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override public void process(ClusterEvent event) throws Exception {
LOG.info("START PersistAssignmentStage.process()");
long startTime = System.currentTimeMillis();
ClusterDataCache cache = event.getAttribute("ClusterDataCache");
ClusterConfig clusterConfig = cache.getClusterConfig();
if (clusterConfig.isPersistBestPossibleAssignment()) {
HelixManager helixManager = event.getAttribute("helixmanager");
HelixDataAccessor accessor = helixManager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
BestPossibleStateOutput bestPossibleAssignments =
event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString());
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.toString());
for (String resourceId : bestPossibleAssignments.resourceSet()) {
Resource resource = resourceMap.get(resourceId);
if (resource != null) {
boolean changed = false;
Map<Partition, Map<String, String>> bestPossibleAssignment =
bestPossibleAssignments.getResourceMap(resourceId);
IdealState idealState = cache.getIdealState(resourceId);
if (idealState == null) {
LOG.warn("IdealState not found for resource " + resourceId);
continue;
}
IdealState.RebalanceMode mode = idealState.getRebalanceMode();
if (!mode.equals(IdealState.RebalanceMode.SEMI_AUTO) && !mode
.equals(IdealState.RebalanceMode.FULL_AUTO)) {
// do not persist assignment for resource in neither semi or full auto.
continue;
}
//TODO: temporary solution for Espresso/Dbus backcompatible, should remove this.
Map<Partition, Map<String, String>> assignmentToPersist =
convertAssignmentPersisted(resource, idealState, bestPossibleAssignment);
for (Partition partition : resource.getPartitions()) {
Map<String, String> instanceMap = assignmentToPersist.get(partition);
Map<String, String> existInstanceMap =
idealState.getInstanceStateMap(partition.getPartitionName());
if (instanceMap == null && existInstanceMap == null) {
continue;
}
if (instanceMap == null || existInstanceMap == null || !instanceMap
.equals(existInstanceMap)) {
changed = true;
break;
}
}
if (changed) {
for (Partition partition : assignmentToPersist.keySet()) {
Map<String, String> instanceMap = assignmentToPersist.get(partition);
idealState.setInstanceStateMap(partition.getPartitionName(), instanceMap);
}
accessor.setProperty(keyBuilder.idealStates(resourceId), idealState);
}
}
}
}
long endTime = System.currentTimeMillis();
LOG.info("END PersistAssignmentStage.process(), took " + (endTime - startTime) + " ms");
}
|
#vulnerable code
@Override public void process(ClusterEvent event) throws Exception {
LOG.info("START PersistAssignmentStage.process()");
long startTime = System.currentTimeMillis();
ClusterDataCache cache = event.getAttribute("ClusterDataCache");
ClusterConfig clusterConfig = cache.getClusterConfig();
if (clusterConfig.isPersistBestPossibleAssignment()) {
HelixManager helixManager = event.getAttribute("helixmanager");
HelixDataAccessor accessor = helixManager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
BestPossibleStateOutput assignments =
event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString());
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.toString());
for (String resourceId : assignments.resourceSet()) {
Resource resource = resourceMap.get(resourceId);
if (resource != null) {
boolean changed = false;
Map<Partition, Map<String, String>> assignment = assignments.getResourceMap(resourceId);
IdealState idealState = cache.getIdealState(resourceId);
if (idealState == null) {
LOG.warn("IdealState not found for resource " + resourceId);
continue;
}
IdealState.RebalanceMode mode = idealState.getRebalanceMode();
if (!mode.equals(IdealState.RebalanceMode.SEMI_AUTO) && !mode
.equals(IdealState.RebalanceMode.FULL_AUTO)) {
// do not persist assignment for resource in neither semi or full auto.
continue;
}
for (Partition partition : resource.getPartitions()) {
Map<String, String> instanceMap = assignment.get(partition);
Map<String, String> existInstanceMap =
idealState.getInstanceStateMap(partition.getPartitionName());
if (instanceMap == null && existInstanceMap == null) {
continue;
}
if (instanceMap == null || existInstanceMap == null || !instanceMap
.equals(existInstanceMap)) {
changed = true;
break;
}
}
if (changed) {
for (Partition partition : assignment.keySet()) {
Map<String, String> instanceMap = assignment.get(partition);
idealState.setInstanceStateMap(partition.getPartitionName(), instanceMap);
}
accessor.setProperty(keyBuilder.idealStates(resourceId), idealState);
}
}
}
}
long endTime = System.currentTimeMillis();
LOG.info("END PersistAssignmentStage.process(), took " + (endTime - startTime) + " ms");
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void disconnect() {
if (_zkclient == null || _zkclient.isClosed()) {
LOG.info("instanceName: " + _instanceName + " already disconnected");
return;
}
LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName);
try {
/**
* stop all timer tasks
*/
stopTimerTasks();
/**
* shutdown thread pool first to avoid reset() being invoked in the middle of state
* transition
*/
_messagingService.getExecutor().shutdown();
// TODO reset user defined handlers only
// TODO Fix the issue that when connection disconnected, reset handlers will be blocked. -- JJ
// This is because reset logic contains ZK operations.
resetHandlers(true);
if (_leaderElectionHandler != null) {
_leaderElectionHandler.reset(true);
}
} finally {
GenericHelixController controller = _controller;
if (controller != null) {
try {
controller.shutdown();
} catch (InterruptedException e) {
LOG.info("Interrupted shutting down GenericHelixController", e);
}
}
ParticipantManager participantManager = _participantManager;
if (participantManager != null) {
participantManager.disconnect();
}
for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) {
callbackMonitor.unregister();
}
_helixPropertyStore = null;
synchronized (this) {
if (_controller != null) {
_controller = null;
_leaderElectionHandler = null;
}
if (_participantManager != null) {
_participantManager = null;
}
if (_zkclient != null) {
_zkclient.close();
}
}
_sessionStartTime = null;
LOG.info("Cluster manager: " + _instanceName + " disconnected");
}
}
|
#vulnerable code
@Override
public void disconnect() {
if (_zkclient == null || _zkclient.isClosed()) {
LOG.info("instanceName: " + _instanceName + " already disconnected");
return;
}
LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName);
try {
/**
* stop all timer tasks
*/
stopTimerTasks();
/**
* shutdown thread pool first to avoid reset() being invoked in the middle of state
* transition
*/
_messagingService.getExecutor().shutdown();
// TODO reset user defined handlers only
// TODO Fix the issue that when connection disconnected, reset handlers will be blocked. -- JJ
// This is because reset logic contains ZK operations.
resetHandlers();
if (_leaderElectionHandler != null) {
_leaderElectionHandler.reset();
}
} finally {
GenericHelixController controller = _controller;
if (controller != null) {
try {
controller.shutdown();
} catch (InterruptedException e) {
LOG.info("Interrupted shutting down GenericHelixController", e);
}
}
ParticipantManager participantManager = _participantManager;
if (participantManager != null) {
participantManager.disconnect();
}
for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) {
callbackMonitor.unregister();
}
_helixPropertyStore = null;
synchronized (this) {
if (_controller != null) {
_controller = null;
_leaderElectionHandler = null;
}
if (_participantManager != null) {
_participantManager = null;
}
if (_zkclient != null) {
_zkclient.close();
}
}
_sessionStartTime = null;
LOG.info("Cluster manager: " + _instanceName + " disconnected");
}
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void close() {
if (_zkClient != null) {
_zkClient.close();
}
}
|
#vulnerable code
@Override
public void close() {
if (_zkclient != null) {
_zkclient.close();
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void checkConnected() {
checkConnected(-1);
}
|
#vulnerable code
void createClient() throws Exception {
PathBasedZkSerializer zkSerializer =
ChainedPathZkSerializer.builder(new ZNRecordSerializer()).build();
HelixZkClient.ZkConnectionConfig connectionConfig = new HelixZkClient.ZkConnectionConfig(_zkAddress);
connectionConfig.setSessionTimeout(_sessionTimeout);
HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig();
clientConfig
.setZkSerializer(zkSerializer)
.setConnectInitTimeout(_connectionInitTimeout)
.setMonitorType(_instanceType.name())
.setMonitorKey(_clusterName)
.setMonitorInstanceName(_instanceName)
.setMonitorRootPathOnly(!_instanceType.equals(InstanceType.CONTROLLER) && !_instanceType
.equals(InstanceType.CONTROLLER_PARTICIPANT));
HelixZkClient newClient;
switch (_instanceType) {
case ADMINISTRATOR:
newClient = SharedZkClientFactory.getInstance().buildZkClient(connectionConfig, clientConfig);
break;
default:
newClient = DedicatedZkClientFactory
.getInstance().buildZkClient(connectionConfig, clientConfig);
break;
}
synchronized (this) {
if (_zkclient != null) {
_zkclient.close();
}
_zkclient = newClient;
_baseDataAccessor = createBaseDataAccessor();
_dataAccessor = new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor);
_configAccessor = new ConfigAccessor(_zkclient);
if (_instanceType == InstanceType.CONTROLLER
|| _instanceType == InstanceType.CONTROLLER_PARTICIPANT) {
addBuiltInStateModelDefinitions();
}
}
// subscribe to state change
_zkclient.subscribeStateChanges(this);
int retryCount = 0;
while (retryCount < 3) {
try {
_zkclient.waitUntilConnected(_connectionInitTimeout, TimeUnit.MILLISECONDS);
handleStateChanged(KeeperState.SyncConnected);
handleNewSession();
break;
} catch (HelixException e) {
LOG.error("fail to createClient.", e);
throw e;
} catch (Exception e) {
retryCount++;
LOG.error("fail to createClient. retry " + retryCount, e);
if (retryCount == 3) {
throw e;
}
}
}
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override public void process(ClusterEvent event) throws Exception {
LOG.info("START PersistAssignmentStage.process()");
long startTime = System.currentTimeMillis();
ClusterDataCache cache = event.getAttribute("ClusterDataCache");
ClusterConfig clusterConfig = cache.getClusterConfig();
if (!clusterConfig.isPersistBestPossibleAssignment()) {
return;
}
BestPossibleStateOutput bestPossibleAssignment =
event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.name());
HelixManager helixManager = event.getAttribute("helixmanager");
HelixDataAccessor accessor = helixManager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.name());
for (String resourceId : bestPossibleAssignment.resourceSet()) {
Resource resource = resourceMap.get(resourceId);
if (resource != null) {
final IdealState idealState = cache.getIdealState(resourceId);
if (idealState == null) {
LOG.warn("IdealState not found for resource " + resourceId);
continue;
}
IdealState.RebalanceMode mode = idealState.getRebalanceMode();
if (!mode.equals(IdealState.RebalanceMode.SEMI_AUTO) && !mode
.equals(IdealState.RebalanceMode.FULL_AUTO)) {
// do not persist assignment for resource in neither semi or full auto.
continue;
}
boolean needPersist = false;
if (mode.equals(IdealState.RebalanceMode.FULL_AUTO)) {
// persist preference list in ful-auto mode.
Map<String, List<String>> newLists =
bestPossibleAssignment.getPreferenceLists(resourceId);
if (newLists != null && hasPreferenceListChanged(newLists, idealState)) {
idealState.setPreferenceLists(newLists);
needPersist = true;
}
}
Map<Partition, Map<String, String>> bestPossibleAssignements =
bestPossibleAssignment.getResourceMap(resourceId);
if (bestPossibleAssignements != null && hasInstanceMapChanged(bestPossibleAssignements,
idealState)) {
for (Partition partition : bestPossibleAssignements.keySet()) {
Map<String, String> instanceMap = bestPossibleAssignements.get(partition);
idealState.setInstanceStateMap(partition.getPartitionName(), instanceMap);
}
needPersist = true;
}
if (needPersist) {
accessor.setProperty(keyBuilder.idealStates(resourceId), idealState);
}
}
}
long endTime = System.currentTimeMillis();
LOG.info("END PersistAssignmentStage.process(), took " + (endTime - startTime) + " ms");
}
|
#vulnerable code
@Override public void process(ClusterEvent event) throws Exception {
LOG.info("START PersistAssignmentStage.process()");
long startTime = System.currentTimeMillis();
ClusterDataCache cache = event.getAttribute("ClusterDataCache");
ClusterConfig clusterConfig = cache.getClusterConfig();
if (clusterConfig.isPersistBestPossibleAssignment()) {
HelixManager helixManager = event.getAttribute("helixmanager");
HelixDataAccessor accessor = helixManager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
BestPossibleStateOutput bestPossibleAssignments =
event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString());
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.toString());
for (String resourceId : bestPossibleAssignments.resourceSet()) {
Resource resource = resourceMap.get(resourceId);
if (resource != null) {
boolean changed = false;
Map<Partition, Map<String, String>> bestPossibleAssignment =
bestPossibleAssignments.getResourceMap(resourceId);
IdealState idealState = cache.getIdealState(resourceId);
if (idealState == null) {
LOG.warn("IdealState not found for resource " + resourceId);
continue;
}
IdealState.RebalanceMode mode = idealState.getRebalanceMode();
if (!mode.equals(IdealState.RebalanceMode.SEMI_AUTO) && !mode
.equals(IdealState.RebalanceMode.FULL_AUTO)) {
// do not persist assignment for resource in neither semi or full auto.
continue;
}
//TODO: temporary solution for Espresso/Dbus backcompatible, should remove this.
Map<Partition, Map<String, String>> assignmentToPersist =
convertAssignmentPersisted(resource, idealState, bestPossibleAssignment);
for (Partition partition : resource.getPartitions()) {
Map<String, String> instanceMap = assignmentToPersist.get(partition);
Map<String, String> existInstanceMap =
idealState.getInstanceStateMap(partition.getPartitionName());
if (instanceMap == null && existInstanceMap == null) {
continue;
}
if (instanceMap == null || existInstanceMap == null || !instanceMap
.equals(existInstanceMap)) {
changed = true;
break;
}
}
if (changed) {
for (Partition partition : assignmentToPersist.keySet()) {
Map<String, String> instanceMap = assignmentToPersist.get(partition);
idealState.setInstanceStateMap(partition.getPartitionName(), instanceMap);
}
accessor.setProperty(keyBuilder.idealStates(resourceId), idealState);
}
}
}
}
long endTime = System.currentTimeMillis();
LOG.info("END PersistAssignmentStage.process(), took " + (endTime - startTime) + " ms");
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ClusterEvent event) throws Exception {
long startTime = System.currentTimeMillis();
LOG.info("START ExternalViewComputeStage.process()");
HelixManager manager = event.getAttribute(AttributeName.helixmanager.name());
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.name());
ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name());
if (manager == null || resourceMap == null || cache == null) {
throw new StageException("Missing attributes in event:" + event
+ ". Requires ClusterManager|RESOURCES|DataCache");
}
HelixDataAccessor dataAccessor = manager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder();
CurrentStateOutput currentStateOutput =
event.getAttribute(AttributeName.CURRENT_STATE.name());
List<ExternalView> newExtViews = new ArrayList<ExternalView>();
Map<String, ExternalView> curExtViews =
dataAccessor.getChildValuesMap(keyBuilder.externalViews());
for (String resourceName : resourceMap.keySet()) {
ExternalView view = new ExternalView(resourceName);
// view.setBucketSize(currentStateOutput.getBucketSize(resourceName));
// if resource ideal state has bucket size, set it
// otherwise resource has been dropped, use bucket size from current state instead
Resource resource = resourceMap.get(resourceName);
if (resource.getBucketSize() > 0) {
view.setBucketSize(resource.getBucketSize());
} else {
view.setBucketSize(currentStateOutput.getBucketSize(resourceName));
}
for (Partition partition : resource.getPartitions()) {
Map<String, String> currentStateMap =
currentStateOutput.getCurrentStateMap(resourceName, partition);
if (currentStateMap != null && currentStateMap.size() > 0) {
// Set<String> disabledInstances
// = cache.getDisabledInstancesForResource(resource.toString());
for (String instance : currentStateMap.keySet()) {
// if (!disabledInstances.contains(instance))
// {
view.setState(partition.getPartitionName(), instance, currentStateMap.get(instance));
// }
}
}
}
// Update cluster status monitor mbean
IdealState idealState = cache.getIdealState(resourceName);
if (!cache.isTaskCache()) {
ClusterStatusMonitor clusterStatusMonitor =
event.getAttribute(AttributeName.clusterStatusMonitor.name());
ResourceConfig resourceConfig = cache.getResourceConfig(resourceName);
if (idealState != null && (resourceConfig == null || !resourceConfig
.isMonitoringDisabled())) {
if (clusterStatusMonitor != null && !idealState.getStateModelDefRef()
.equalsIgnoreCase(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) {
StateModelDefinition stateModelDef =
cache.getStateModelDef(idealState.getStateModelDefRef());
clusterStatusMonitor
.setResourceStatus(view, cache.getIdealState(view.getResourceName()),
stateModelDef);
}
} else {
// Drop the metrics if the resource is dropped, or the MonitorDisabled is changed to true.
clusterStatusMonitor.unregisterResource(view.getResourceName());
}
}
ExternalView curExtView = curExtViews.get(resourceName);
// copy simplefields from IS, in cases where IS is deleted copy it from existing ExternalView
if (idealState != null) {
view.getRecord().getSimpleFields().putAll(idealState.getRecord().getSimpleFields());
} else if (curExtView != null) {
view.getRecord().getSimpleFields().putAll(curExtView.getRecord().getSimpleFields());
}
// compare the new external view with current one, set only on different
if (curExtView == null || !curExtView.getRecord().equals(view.getRecord())) {
// Add external view to the list which will be written to ZK later.
newExtViews.add(view);
// For SCHEDULER_TASK_RESOURCE resource group (helix task queue), we need to find out which
// task partitions are finished (COMPLETED or ERROR), update the status update of the original
// scheduler message, and then remove the partitions from the ideal state
if (idealState != null
&& idealState.getStateModelDefRef().equalsIgnoreCase(
DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) {
updateScheduledTaskStatus(view, manager, idealState);
}
}
}
// TODO: consider not setting the externalview of SCHEDULER_TASK_QUEUE at all.
// Are there any entity that will be interested in its change?
// For the resource with DisableExternalView option turned on in IdealState
// We will not actually create or write the externalView to ZooKeeper.
List<PropertyKey> keys = new ArrayList<PropertyKey>();
for(Iterator<ExternalView> it = newExtViews.iterator(); it.hasNext(); ) {
ExternalView view = it.next();
String resourceName = view.getResourceName();
IdealState idealState = cache.getIdealState(resourceName);
if (idealState != null && idealState.isExternalViewDisabled()) {
it.remove();
// remove the external view if the external view exists
if (curExtViews.containsKey(resourceName)) {
LOG.info("Remove externalView for resource: " + resourceName);
dataAccessor.removeProperty(keyBuilder.externalView(resourceName));
}
} else {
keys.add(keyBuilder.externalView(resourceName));
}
}
// add/update external-views
if (newExtViews.size() > 0) {
dataAccessor.setChildren(keys, newExtViews);
}
// remove dead external-views
for (String resourceName : curExtViews.keySet()) {
if (!resourceMap.keySet().contains(resourceName)) {
LOG.info("Remove externalView for resource: " + resourceName);
dataAccessor.removeProperty(keyBuilder.externalView(resourceName));
}
}
long endTime = System.currentTimeMillis();
LOG.info("END " + GenericHelixController.getPipelineType(cache.isTaskCache())
+ " ExternalViewComputeStage.process() for cluster " + cache.getClusterName() + ". took: "
+ (endTime - startTime) + " ms");
}
|
#vulnerable code
@Override
public void process(ClusterEvent event) throws Exception {
long startTime = System.currentTimeMillis();
LOG.info("START ExternalViewComputeStage.process()");
HelixManager manager = event.getAttribute(AttributeName.helixmanager.name());
Map<String, Resource> resourceMap = event.getAttribute(AttributeName.RESOURCES.name());
ClusterDataCache cache = event.getAttribute(AttributeName.ClusterDataCache.name());
if (manager == null || resourceMap == null || cache == null) {
throw new StageException("Missing attributes in event:" + event
+ ". Requires ClusterManager|RESOURCES|DataCache");
}
HelixDataAccessor dataAccessor = manager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder();
CurrentStateOutput currentStateOutput =
event.getAttribute(AttributeName.CURRENT_STATE.name());
List<ExternalView> newExtViews = new ArrayList<ExternalView>();
Map<String, ExternalView> curExtViews =
dataAccessor.getChildValuesMap(keyBuilder.externalViews());
for (String resourceName : resourceMap.keySet()) {
ExternalView view = new ExternalView(resourceName);
// view.setBucketSize(currentStateOutput.getBucketSize(resourceName));
// if resource ideal state has bucket size, set it
// otherwise resource has been dropped, use bucket size from current state instead
Resource resource = resourceMap.get(resourceName);
if (resource.getBucketSize() > 0) {
view.setBucketSize(resource.getBucketSize());
} else {
view.setBucketSize(currentStateOutput.getBucketSize(resourceName));
}
for (Partition partition : resource.getPartitions()) {
Map<String, String> currentStateMap =
currentStateOutput.getCurrentStateMap(resourceName, partition);
if (currentStateMap != null && currentStateMap.size() > 0) {
// Set<String> disabledInstances
// = cache.getDisabledInstancesForResource(resource.toString());
for (String instance : currentStateMap.keySet()) {
// if (!disabledInstances.contains(instance))
// {
view.setState(partition.getPartitionName(), instance, currentStateMap.get(instance));
// }
}
}
}
// Update cluster status monitor mbean
IdealState idealState = cache.getIdealState(resourceName);
if (!cache.isTaskCache()) {
ClusterStatusMonitor clusterStatusMonitor =
event.getAttribute(AttributeName.clusterStatusMonitor.name());
ResourceConfig resourceConfig = cache.getResourceConfig(resourceName);
if (idealState != null && (resourceConfig == null || !resourceConfig
.isMonitoringDisabled())) {
if (clusterStatusMonitor != null && !idealState.getStateModelDefRef()
.equalsIgnoreCase(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) {
StateModelDefinition stateModelDef =
cache.getStateModelDef(idealState.getStateModelDefRef());
clusterStatusMonitor
.setResourceStatus(view, cache.getIdealState(view.getResourceName()),
stateModelDef);
}
} else {
// Drop the metrics if the resource is dropped, or the MonitorDisabled is changed to true.
clusterStatusMonitor.unregisterResource(view.getResourceName());
}
}
ExternalView curExtView = curExtViews.get(resourceName);
// copy simplefields from IS, in cases where IS is deleted copy it from existing ExternalView
if (idealState != null) {
view.getRecord().getSimpleFields().putAll(idealState.getRecord().getSimpleFields());
} else if (curExtView != null) {
view.getRecord().getSimpleFields().putAll(curExtView.getRecord().getSimpleFields());
}
// compare the new external view with current one, set only on different
if (curExtView == null || !curExtView.getRecord().equals(view.getRecord())) {
// Add external view to the list which will be written to ZK later.
newExtViews.add(view);
// For SCHEDULER_TASK_RESOURCE resource group (helix task queue), we need to find out which
// task partitions are finished (COMPLETED or ERROR), update the status update of the original
// scheduler message, and then remove the partitions from the ideal state
if (idealState != null
&& idealState.getStateModelDefRef().equalsIgnoreCase(
DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) {
updateScheduledTaskStatus(view, manager, idealState);
}
}
}
// TODO: consider not setting the externalview of SCHEDULER_TASK_QUEUE at all.
// Are there any entity that will be interested in its change?
// For the resource with DisableExternalView option turned on in IdealState
// We will not actually create or write the externalView to ZooKeeper.
List<PropertyKey> keys = new ArrayList<PropertyKey>();
for(Iterator<ExternalView> it = newExtViews.iterator(); it.hasNext(); ) {
ExternalView view = it.next();
String resourceName = view.getResourceName();
IdealState idealState = cache.getIdealState(resourceName);
if (idealState != null && idealState.isExternalViewDisabled()) {
it.remove();
// remove the external view if the external view exists
if (curExtViews.containsKey(resourceName)) {
LOG.info("Remove externalView for resource: " + resourceName);
dataAccessor.removeProperty(keyBuilder.externalView(resourceName));
}
} else {
keys.add(keyBuilder.externalView(resourceName));
}
}
// add/update external-views
if (newExtViews.size() > 0) {
dataAccessor.setChildren(keys, newExtViews);
}
// remove dead external-views
for (String resourceName : curExtViews.keySet()) {
if (!resourceMap.keySet().contains(resourceName)) {
LOG.info("Remove externalView for resource: " + resourceName);
dataAccessor.removeProperty(keyBuilder.externalView(resourceName));
}
}
long endTime = System.currentTimeMillis();
LOG.info("END ExternalViewComputeStage.process() for cluster " + cache.getClusterName()
+ ". took: " + (endTime - startTime) + " ms");
}
#location 35
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public PropertyStore<ZNRecord> getPropertyStore()
{
checkConnected();
synchronized (_propertyStoreRef)
{
if (_propertyStoreRef.get() == null)
{
String path =
PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _clusterName);
// property store uses a different serializer
ZkClient zkClient = new ZkClient(_zkConnectString, CONNECTIONTIMEOUT);
PropertyStore<ZNRecord>_propertyStore =
new ZKPropertyStore<ZNRecord>(zkClient, new ZNRecordJsonSerializer(), path);
_propertyStoreRef.set(_propertyStore);
}
}
return _propertyStoreRef.get();
}
|
#vulnerable code
@Override
public PropertyStore<ZNRecord> getPropertyStore()
{
checkConnected();
synchronized (_propertyStore)
{
if (_propertyStore == null)
{
String path =
PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _clusterName);
// property store uses a different serializer
ZkClient zkClient = new ZkClient(_zkConnectString, CONNECTIONTIMEOUT);
_propertyStore =
new ZKPropertyStore<ZNRecord>(zkClient, new ZNRecordJsonSerializer(), path);
}
}
return _propertyStore;
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ClusterEvent event) throws Exception
{
ClusterManager manager = event.getAttribute("clustermanager");
if (manager == null)
{
throw new StageException("ClusterManager attribute value is null");
}
log.info("START ExternalViewComputeStage.process()");
ClusterDataAccessor dataAccessor = manager.getDataAccessor();
Map<String, ResourceGroup> resourceGroupMap = event
.getAttribute(AttributeName.RESOURCE_GROUPS.toString());
if (resourceGroupMap == null)
{
throw new StageException("ResourceGroupMap attribute value is null");
}
CurrentStateOutput currentStateOutput = event
.getAttribute(AttributeName.CURRENT_STATE.toString());
for (String resourceGroupName : resourceGroupMap.keySet())
{
ZNRecord viewRecord = new ZNRecord();
viewRecord.setId(resourceGroupName);
ExternalView view = new ExternalView(viewRecord);
ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName);
for (ResourceKey resource : resourceGroup.getResourceKeys())
{
Map<String, String> currentStateMap = currentStateOutput
.getCurrentStateMap(resourceGroupName, resource);
if (currentStateMap != null && currentStateMap.size() > 0)
{
view.setStateMap(resource.getResourceKeyName(), currentStateMap);
}
}
dataAccessor.setClusterProperty(ClusterPropertyType.EXTERNALVIEW,
resourceGroupName, view.getRecord());
}
log.info("START ExternalViewComputeStage.process()");
}
|
#vulnerable code
@Override
public void process(ClusterEvent event) throws Exception
{
ClusterManager manager = event.getAttribute("clustermanager");
if (manager == null)
{
throw new StageException("ClusterManager attribute value is null");
}
log.info("START ExternalViewComputeStage.process()");
ClusterDataAccessor dataAccessor = manager.getDataAccessor();
Map<String, ResourceGroup> resourceGroupMap = event
.getAttribute(AttributeName.RESOURCE_GROUPS.toString());
CurrentStateOutput currentStateOutput = event
.getAttribute(AttributeName.CURRENT_STATE.toString());
for (String resourceGroupName : resourceGroupMap.keySet())
{
ZNRecord viewRecord = new ZNRecord();
viewRecord.setId(resourceGroupName);
ExternalView view = new ExternalView(viewRecord);
ResourceGroup resourceGroup = resourceGroupMap.get(resourceGroupName);
for (ResourceKey resource : resourceGroup.getResourceKeys())
{
Map<String, String> currentStateMap = currentStateOutput
.getCurrentStateMap(resourceGroupName, resource);
if (currentStateMap != null && currentStateMap.size() > 0)
{
view.setStateMap(resource.getResourceKeyName(), currentStateMap);
}
}
dataAccessor.setClusterProperty(ClusterPropertyType.EXTERNALVIEW,
resourceGroupName, view.getRecord());
}
log.info("START ExternalViewComputeStage.process()");
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void handleDataChange(String dataPath, Object data) {
if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) {
return;
}
resetZkResources();
}
|
#vulnerable code
@Override
public void handleDataChange(String dataPath, Object data) {
if (_zkClientForListener == null || _zkClientForListener.isClosed()) {
return;
}
resetZkResources();
}
#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 handleNewSession(String sessionId) {
if (_zkClientForRoutingDataListener == null || _zkClientForRoutingDataListener.isClosed()) {
return;
}
// Resubscribe
_zkClientForRoutingDataListener.unsubscribeAll();
_zkClientForRoutingDataListener.subscribeRoutingDataChanges(this, this);
resetZkResources();
}
|
#vulnerable code
@Override
public void handleNewSession(String sessionId) {
if (_zkClientForListener == null || _zkClientForListener.isClosed()) {
return;
}
// Resubscribe
_zkClientForListener.unsubscribeAll();
_zkClientForListener.subscribeRoutingDataChanges(this, this);
resetZkResources();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void preHandleMessage() throws Exception {
if (!_message.isValid()) {
String errorMessage = "Invalid Message, ensure that message: " + _message
+ " has all the required fields: " + Arrays.toString(Message.Attributes.values());
_statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, errorMessage,
_manager);
logger.error(errorMessage);
throw new HelixException(errorMessage);
}
logger.info("handling message: " + _message.getMsgId() + " transit "
+ _message.getResourceName() + "." + _message.getPartitionName() + "|"
+ _message.getPartitionNames() + " from:" + _message.getFromState() + " to:"
+ _message.getToState() + ", relayedFrom: " + _message.getRelaySrcHost());
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
String partitionName = _message.getPartitionName();
// Set start time right before invoke client logic
_currentStateDelta.setStartTime(_message.getPartitionName(), System.currentTimeMillis());
StaleMessageValidateResult err = staleMessageValidator();
if (!err.isValid) {
_statusUpdateUtil
.logError(_message, HelixStateTransitionHandler.class, err.exception.getMessage(),
_manager);
logger.error(err.exception.getMessage());
throw err.exception;
}
// Reset the REQUESTED_STATE property if it exists.
try {
String instance = _manager.getInstanceName();
String sessionId = _message.getTgtSessionId();
String resource = _message.getResourceName();
ZNRecordBucketizer bucketizer = new ZNRecordBucketizer(_message.getBucketSize());
PropertyKey key = accessor.keyBuilder().currentState(instance, sessionId, resource,
bucketizer.getBucketName(partitionName));
ZNRecord rec = new ZNRecord(resource);
Map<String, String> map = new TreeMap<String, String>();
map.put(CurrentState.CurrentStateProperty.REQUESTED_STATE.name(), null);
rec.getMapFields().put(partitionName, map);
ZNRecordDelta delta = new ZNRecordDelta(rec, ZNRecordDelta.MergeOperation.SUBTRACT);
List<ZNRecordDelta> deltaList = new ArrayList<ZNRecordDelta>();
deltaList.add(delta);
CurrentState currStateUpdate = new CurrentState(resource);
currStateUpdate.setDeltaList(deltaList);
// Update the ZK current state of the node
if (!accessor.updateProperty(key, currStateUpdate)) {
logger.error("Fails to persist current state back to ZK for resource " + resource
+ " partition: " + partitionName);
}
} catch (Exception e) {
logger.error("Error when removing " + CurrentState.CurrentStateProperty.REQUESTED_STATE.name()
+ " from current state.", e);
StateTransitionError error =
new StateTransitionError(ErrorType.FRAMEWORK, ErrorCode.ERROR, e);
_stateModel.rollbackOnError(_message, _notificationContext, error);
_statusUpdateUtil.logError(
_message, HelixStateTransitionHandler.class, e, "Error when removing "
+ CurrentState.CurrentStateProperty.REQUESTED_STATE.name() + " from current state.",
_manager);
}
}
|
#vulnerable code
void preHandleMessage() throws Exception {
if (!_message.isValid()) {
String errorMessage = "Invalid Message, ensure that message: " + _message
+ " has all the required fields: " + Arrays.toString(Message.Attributes.values());
_statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, errorMessage,
_manager);
logger.error(errorMessage);
throw new HelixException(errorMessage);
}
logger.info("handling message: " + _message.getMsgId() + " transit "
+ _message.getResourceName() + "." + _message.getPartitionName() + "|"
+ _message.getPartitionNames() + " from:" + _message.getFromState() + " to:"
+ _message.getToState() + ", relayedFrom: " + _message.getRelaySrcHost());
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
String partitionName = _message.getPartitionName();
String fromState = _message.getFromState();
String toState = _message.getToState();
// Verify the fromState and current state of the stateModel
// getting current state from state model will provide most up-to-date
// current state. In case current state is null, partition is in initial
// state and we are setting it in current state
String state = _stateModel.getCurrentState() != null ? _stateModel.getCurrentState()
: _currentStateDelta.getState(partitionName);
// Set start time right before invoke client logic
_currentStateDelta.setStartTime(_message.getPartitionName(), System.currentTimeMillis());
Exception err = null;
if (toState.equalsIgnoreCase(state)) {
// To state equals current state, we can just ignore the message
err = new HelixDuplicatedStateTransitionException(
String.format("Partition %s current state is same as toState (%s->%s) from message.",
partitionName, fromState, toState));
} else if (fromState != null && !fromState.equals("*") && !fromState.equalsIgnoreCase(state)) {
// If current state is neither toState nor fromState in message, there is a problem
err = new HelixStateMismatchException(String.format(
"Current state of stateModel does not match the fromState in Message, CurrentState: %s, Message: %s->%s, Partition: %s, from: %s, to: %s",
state, fromState, toState, partitionName, _message.getMsgSrc(), _message.getTgtName()));
}
if (err != null) {
_statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, err.getMessage(),
_manager);
logger.error(err.getMessage());
throw err;
}
// Reset the REQUESTED_STATE property if it exists.
try {
String instance = _manager.getInstanceName();
String sessionId = _message.getTgtSessionId();
String resource = _message.getResourceName();
ZNRecordBucketizer bucketizer = new ZNRecordBucketizer(_message.getBucketSize());
PropertyKey key = accessor.keyBuilder().currentState(instance, sessionId, resource,
bucketizer.getBucketName(partitionName));
ZNRecord rec = new ZNRecord(resource);
Map<String, String> map = new TreeMap<String, String>();
map.put(CurrentState.CurrentStateProperty.REQUESTED_STATE.name(), null);
rec.getMapFields().put(partitionName, map);
ZNRecordDelta delta = new ZNRecordDelta(rec, ZNRecordDelta.MergeOperation.SUBTRACT);
List<ZNRecordDelta> deltaList = new ArrayList<ZNRecordDelta>();
deltaList.add(delta);
CurrentState currStateUpdate = new CurrentState(resource);
currStateUpdate.setDeltaList(deltaList);
// Update the ZK current state of the node
if (!accessor.updateProperty(key, currStateUpdate)) {
logger.error("Fails to persist current state back to ZK for resource " + resource
+ " partition: " + partitionName);
}
} catch (Exception e) {
logger.error("Error when removing " + CurrentState.CurrentStateProperty.REQUESTED_STATE.name()
+ " from current state.", e);
StateTransitionError error =
new StateTransitionError(ErrorType.FRAMEWORK, ErrorCode.ERROR, e);
_stateModel.rollbackOnError(_message, _notificationContext, error);
_statusUpdateUtil.logError(
_message, HelixStateTransitionHandler.class, e, "Error when removing "
+ CurrentState.CurrentStateProperty.REQUESTED_STATE.name() + " from current state.",
_manager);
}
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
String messageId = commandLine.getOptionValue('i').trim();
try {
System.out.printf("ip=%s", MessageClientIDSetter.getIPStrFromID(messageId));
} catch (Exception e) {
e.printStackTrace();
}
try {
String date = UtilAll.formatDate(MessageClientIDSetter.getNearlyTimeFromID(messageId), UtilAll.YYYY_MM_DD_HH_MM_SS_SSS);
System.out.printf("date=%s", date);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
}
}
|
#vulnerable code
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
String messageId = commandLine.getOptionValue('i').trim();
try {
System.out.printf("ip=" + MessageClientIDSetter.getIPStrFromID(messageId));
} catch (Exception e) {
e.printStackTrace();
}
try {
String date = UtilAll.formatDate(MessageClientIDSetter.getNearlyTimeFromID(messageId), UtilAll.YYYY_MM_DD_HH_MM_SS_SSS);
System.out.printf("date=" + date);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
}
}
#location 7
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void executeSendMessageHookBefore(final ChannelHandlerContext ctx, final RemotingCommand request,
SendMessageContext context) {
if (hasSendMessageHook()) {
for (SendMessageHook hook : this.sendMessageHookList) {
try {
final SendMessageRequestHeader requestHeader = parseRequestHeader(request);
if (null != requestHeader) {
context.setProducerGroup(requestHeader.getProducerGroup());
context.setTopic(requestHeader.getTopic());
context.setBodyLength(request.getBody().length);
context.setMsgProps(requestHeader.getProperties());
context.setBornHost(RemotingHelper.parseChannelRemoteAddr(ctx.channel()));
context.setBrokerAddr(this.brokerController.getBrokerAddr());
context.setQueueId(requestHeader.getQueueId());
}
hook.sendMessageBefore(context);
if (requestHeader != null) {
requestHeader.setProperties(context.getMsgProps());
}
} catch (Throwable e) {
// Ignore
}
}
}
}
|
#vulnerable code
public void executeSendMessageHookBefore(final ChannelHandlerContext ctx, final RemotingCommand request,
SendMessageContext context) {
if (hasSendMessageHook()) {
for (SendMessageHook hook : this.sendMessageHookList) {
try {
final SendMessageRequestHeader requestHeader = parseRequestHeader(request);
if (null != requestHeader) {
context.setProducerGroup(requestHeader.getProducerGroup());
context.setTopic(requestHeader.getTopic());
context.setBodyLength(request.getBody().length);
context.setMsgProps(requestHeader.getProperties());
context.setBornHost(RemotingHelper.parseChannelRemoteAddr(ctx.channel()));
context.setBrokerAddr(this.brokerController.getBrokerAddr());
context.setQueueId(requestHeader.getQueueId());
}
hook.sendMessageBefore(context);
requestHeader.setProperties(context.getMsgProps());
} catch (Throwable e) {
}
}
}
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetHalfMessageNull() {
when(messageStore
.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class)))
.thenReturn(null);
PullResult result = transactionBridge.getHalfMessage(0, 0, 1);
assertThat(result).isNull();
}
|
#vulnerable code
@Test
public void testGetHalfMessageNull() {
when(messageStore
.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class)))
.thenReturn(null);
PullResult result = transactionBridge.getHalfMessage(0, 0, 1);
assertThat(result.getPullStatus()).isNull();
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetHalfMessageNull() {
when(messageStore
.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class)))
.thenReturn(null);
PullResult result = transactionBridge.getHalfMessage(0, 0, 1);
assertThat(result).isNull();
}
|
#vulnerable code
@Test
public void testGetHalfMessageNull() {
when(messageStore
.getMessage(anyString(), anyString(), anyInt(), anyLong(), anyInt(), ArgumentMatchers.nullable(MessageFilter.class)))
.thenReturn(null);
PullResult result = transactionBridge.getHalfMessage(0, 0, 1);
assertThat(result.getPullStatus()).isNull();
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTwoConsumerWithSameGroup() {
int msgSize = 20;
String originMsgDCName = RandomUtils.getStringByUUID();
String msgBodyDCName = RandomUtils.getStringByUUID();
RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
getConsumer(nsAddr, consumer1.getConsumerGroup(), tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
producer.send(tag, msgSize);
Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size());
consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer1.getListner().getAllMsgBody()))
.containsExactlyElementsIn(producer.getAllMsgBody());
}
|
#vulnerable code
@Test
public void testTwoConsumerWithSameGroup() {
String tag = "jueyin";
int msgSize = 20;
String originMsgDCName = RandomUtils.getStringByUUID();
String msgBodyDCName = RandomUtils.getStringByUUID();
RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
RMQNormalConsumer consumer2 = getConsumer(nsAddr, consumer1.getConsumerGroup(), tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
producer.send(tag, msgSize);
Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size());
consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer1.getListner().getAllMsgBody()))
.containsExactlyElementsIn(producer.getAllMsgBody());
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static NamesrvController main0(String[] args) {
System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
try {
//PackageConflictDetect.detectFastjson();
Options options = ServerUtil.buildCommandlineOptions(new Options());
commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
if (null == commandLine) {
System.exit(-1);
return null;
}
final NamesrvConfig namesrvConfig = new NamesrvConfig();
final NettyServerConfig nettyServerConfig = new NettyServerConfig();
nettyServerConfig.setListenPort(9876);
if (commandLine.hasOption('c')) {
String file = commandLine.getOptionValue('c');
if (file != null) {
InputStream in = new BufferedInputStream(new FileInputStream(file));
properties = new Properties();
properties.load(in);
MixAll.properties2Object(properties, namesrvConfig);
MixAll.properties2Object(properties, nettyServerConfig);
namesrvConfig.setConfigStorePath(file);
System.out.printf("load config properties file OK, %s%n", file);
in.close();
}
}
if (commandLine.hasOption('p')) {
MixAll.printObjectProperties(null, namesrvConfig);
MixAll.printObjectProperties(null, nettyServerConfig);
System.exit(0);
}
MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
if (null == namesrvConfig.getRocketmqHome()) {
System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
System.exit(-2);
}
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");
final Logger log = LoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
MixAll.printObjectProperties(log, namesrvConfig);
MixAll.printObjectProperties(log, nettyServerConfig);
final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);
// remember all configs to prevent discard
controller.getConfiguration().registerConfig(properties);
boolean initResult = controller.initialize();
if (!initResult) {
controller.shutdown();
System.exit(-3);
}
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
@Override
public Void call() throws Exception {
controller.shutdown();
return null;
}
}));
controller.start();
String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
log.info(tip);
System.out.printf("%s%n", tip);
return controller;
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
|
#vulnerable code
public static NamesrvController main0(String[] args) {
System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
try {
//PackageConflictDetect.detectFastjson();
Options options = ServerUtil.buildCommandlineOptions(new Options());
commandLine = ServerUtil.parseCmdLine("mqnamesrv", args, buildCommandlineOptions(options), new PosixParser());
if (null == commandLine) {
System.exit(-1);
return null;
}
final NamesrvConfig namesrvConfig = new NamesrvConfig();
final NettyServerConfig nettyServerConfig = new NettyServerConfig();
nettyServerConfig.setListenPort(9876);
if (commandLine.hasOption('c')) {
String file = commandLine.getOptionValue('c');
if (file != null) {
InputStream in = new BufferedInputStream(new FileInputStream(file));
properties = new Properties();
properties.load(in);
MixAll.properties2Object(properties, namesrvConfig);
MixAll.properties2Object(properties, nettyServerConfig);
namesrvConfig.setConfigStorePath(file);
System.out.printf("load config properties file OK, " + file + "%n");
in.close();
}
}
if (commandLine.hasOption('p')) {
MixAll.printObjectProperties(null, namesrvConfig);
MixAll.printObjectProperties(null, nettyServerConfig);
System.exit(0);
}
MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), namesrvConfig);
if (null == namesrvConfig.getRocketmqHome()) {
System.out.printf("Please set the %s variable in your environment to match the location of the RocketMQ installation%n", MixAll.ROCKETMQ_HOME_ENV);
System.exit(-2);
}
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(namesrvConfig.getRocketmqHome() + "/conf/logback_namesrv.xml");
final Logger log = LoggerFactory.getLogger(LoggerName.NAMESRV_LOGGER_NAME);
MixAll.printObjectProperties(log, namesrvConfig);
MixAll.printObjectProperties(log, nettyServerConfig);
final NamesrvController controller = new NamesrvController(namesrvConfig, nettyServerConfig);
// remember all configs to prevent discard
controller.getConfiguration().registerConfig(properties);
boolean initResult = controller.initialize();
if (!initResult) {
controller.shutdown();
System.exit(-3);
}
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(log, new Callable<Void>() {
@Override
public Void call() throws Exception {
controller.shutdown();
return null;
}
}));
controller.start();
String tip = "The Name Server boot success. serializeType=" + RemotingCommand.getSerializeTypeConfigInThisServer();
log.info(tip);
System.out.printf(tip + "%n");
return controller;
} catch (Throwable e) {
e.printStackTrace();
System.exit(-1);
}
return null;
}
#location 78
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Before
public void init() throws NoSuchFieldException, SecurityException, IOException {
Yaml ymal = new Yaml();
String home = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
InputStream fis = null;
if (home == null) {
URL url = PlainAclPlugEngineTest.class.getResource("/");
home = url.toString();
home = home.substring(0, home.length() - 1).replace("file:/", "").replace("target/test-classes", "");
home = home + "src/test/resources";
String filePath = home + "/conf/transport.yml";
fis = new FileInputStream(new File(filePath));
} else {
String filePath = home + "/conf/transport.yml";
fis = new FileInputStream(new File(filePath));
}
transport = ymal.loadAs(fis, BorkerAccessControlTransport.class);
ControllerParameters controllerParametersEntity = new ControllerParameters();
controllerParametersEntity.setFileHome(home);
plainAclPlugEngine = new PlainAclPlugEngine(controllerParametersEntity);
accessControl = new BorkerAccessControl();
accessControl.setAccount("rokcetmq");
accessControl.setPassword("aliyun11");
accessControl.setNetaddress("127.0.0.1");
accessControl.setRecognition("127.0.0.1:1");
accessControlTwo = new BorkerAccessControl();
accessControlTwo.setAccount("rokcet1");
accessControlTwo.setPassword("aliyun1");
accessControlTwo.setNetaddress("127.0.0.1");
accessControlTwo.setRecognition("127.0.0.1:2");
loginInfoMap = new ConcurrentHashMap<>();
FieldSetter.setField(plainAclPlugEngine, plainAclPlugEngine.getClass().getSuperclass().getDeclaredField("loginInfoMap"), loginInfoMap);
}
|
#vulnerable code
@Before
public void init() throws NoSuchFieldException, SecurityException, IOException {
Yaml ymal = new Yaml();
String home = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
InputStream fis=null;
if(home == null){
URL url = PlainAclPlugEngineTest.class.getResource("/conf/transport.yml");
if(url == null) {
url = PlainAclPlugEngineTest.class.getResource("/");
home = url.toString();
home = home.substring(0, home.length()-1).replace("file:/", "").replace("target/test-classes", "");
home = home+"src/test/resources";
String filePath = home+"/conf/transport.yml";
fis = new FileInputStream(new File(filePath));
}else {
fis = url.openStream();
url = PlainAclPlugEngineTest.class.getResource("/");
home = url.toString();
home = home.substring(0, home.length()-1).replace("file:/", "");
}
}else {
String filePath = home + "/conf/transport.yml";
fis = new FileInputStream(new File(filePath));
}
transport = ymal.loadAs(fis, BorkerAccessControlTransport.class);
ControllerParameters controllerParametersEntity = new ControllerParameters();
controllerParametersEntity.setFileHome(home);
plainAclPlugEngine = new PlainAclPlugEngine(controllerParametersEntity);
accessControl = new BorkerAccessControl();
accessControl.setAccount("rokcetmq");
accessControl.setPassword("aliyun11");
accessControl.setNetaddress("127.0.0.1");
accessControl.setRecognition("127.0.0.1:1");
accessControlTwo = new BorkerAccessControl();
accessControlTwo.setAccount("rokcet1");
accessControlTwo.setPassword("aliyun1");
accessControlTwo.setNetaddress("127.0.0.1");
accessControlTwo.setRecognition("127.0.0.1:2");
loginInfoMap = new ConcurrentHashMap<>();
FieldSetter.setField(plainAclPlugEngine, plainAclPlugEngine.getClass().getSuperclass().getDeclaredField("loginInfoMap"), loginInfoMap);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
TopicConfig topicConfig = new TopicConfig();
topicConfig.setReadQueueNums(8);
topicConfig.setWriteQueueNums(8);
topicConfig.setTopicName(commandLine.getOptionValue('t').trim());
// readQueueNums
if (commandLine.hasOption('r')) {
topicConfig.setReadQueueNums(Integer.parseInt(commandLine.getOptionValue('r').trim()));
}
// writeQueueNums
if (commandLine.hasOption('w')) {
topicConfig.setWriteQueueNums(Integer.parseInt(commandLine.getOptionValue('w').trim()));
}
// perm
if (commandLine.hasOption('p')) {
topicConfig.setPerm(Integer.parseInt(commandLine.getOptionValue('p').trim()));
}
boolean isUnit = false;
if (commandLine.hasOption('u')) {
isUnit = Boolean.parseBoolean(commandLine.getOptionValue('u').trim());
}
boolean isCenterSync = false;
if (commandLine.hasOption('s')) {
isCenterSync = Boolean.parseBoolean(commandLine.getOptionValue('s').trim());
}
int topicCenterSync = TopicSysFlag.buildSysFlag(isUnit, isCenterSync);
topicConfig.setTopicSysFlag(topicCenterSync);
boolean isOrder = false;
if (commandLine.hasOption('o')) {
isOrder = Boolean.parseBoolean(commandLine.getOptionValue('o').trim());
}
topicConfig.setOrder(isOrder);
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
if (isOrder) {
String brokerName = CommandUtil.fetchBrokerNameByAddr(defaultMQAdminExt, addr);
String orderConf = brokerName + ":" + topicConfig.getWriteQueueNums();
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(), orderConf, false);
System.out.printf("%s", String.format("set broker orderConf. isOrder=%s, orderConf=[%s]",
isOrder, orderConf.toString()));
}
System.out.printf("create topic to %s success.%n", addr);
System.out.printf("%s", topicConfig);
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> masterSet =
CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
for (String addr : masterSet) {
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
System.out.printf("create topic to %s success.%n", addr);
}
if (isOrder) {
Set<String> brokerNameSet =
CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExt, clusterName);
StringBuilder orderConf = new StringBuilder();
String splitor = "";
for (String s : brokerNameSet) {
orderConf.append(splitor).append(s).append(":")
.append(topicConfig.getWriteQueueNums());
splitor = ";";
}
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(),
orderConf.toString(), true);
System.out.printf("set cluster orderConf. isOrder=%s, orderConf=[%s]", isOrder, orderConf);
}
System.out.printf("%s", topicConfig);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
|
#vulnerable code
@Override
public void execute(final CommandLine commandLine, final Options options,
RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
TopicConfig topicConfig = new TopicConfig();
topicConfig.setReadQueueNums(8);
topicConfig.setWriteQueueNums(8);
topicConfig.setTopicName(commandLine.getOptionValue('t').trim());
// readQueueNums
if (commandLine.hasOption('r')) {
topicConfig.setReadQueueNums(Integer.parseInt(commandLine.getOptionValue('r').trim()));
}
// writeQueueNums
if (commandLine.hasOption('w')) {
topicConfig.setWriteQueueNums(Integer.parseInt(commandLine.getOptionValue('w').trim()));
}
// perm
if (commandLine.hasOption('p')) {
topicConfig.setPerm(Integer.parseInt(commandLine.getOptionValue('p').trim()));
}
boolean isUnit = false;
if (commandLine.hasOption('u')) {
isUnit = Boolean.parseBoolean(commandLine.getOptionValue('u').trim());
}
boolean isCenterSync = false;
if (commandLine.hasOption('s')) {
isCenterSync = Boolean.parseBoolean(commandLine.getOptionValue('s').trim());
}
int topicCenterSync = TopicSysFlag.buildSysFlag(isUnit, isCenterSync);
topicConfig.setTopicSysFlag(topicCenterSync);
boolean isOrder = false;
if (commandLine.hasOption('o')) {
isOrder = Boolean.parseBoolean(commandLine.getOptionValue('o').trim());
}
topicConfig.setOrder(isOrder);
if (commandLine.hasOption('b')) {
String addr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
if (isOrder) {
String brokerName = CommandUtil.fetchBrokerNameByAddr(defaultMQAdminExt, addr);
String orderConf = brokerName + ":" + topicConfig.getWriteQueueNums();
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(), orderConf, false);
System.out.printf(String.format("set broker orderConf. isOrder=%s, orderConf=[%s]",
isOrder, orderConf.toString()));
}
System.out.printf("create topic to %s success.%n", addr);
System.out.printf("%s", topicConfig);
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> masterSet =
CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
for (String addr : masterSet) {
defaultMQAdminExt.createAndUpdateTopicConfig(addr, topicConfig);
System.out.printf("create topic to %s success.%n", addr);
}
if (isOrder) {
Set<String> brokerNameSet =
CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExt, clusterName);
StringBuilder orderConf = new StringBuilder();
String splitor = "";
for (String s : brokerNameSet) {
orderConf.append(splitor).append(s).append(":")
.append(topicConfig.getWriteQueueNums());
splitor = ";";
}
defaultMQAdminExt.createOrUpdateOrderConf(topicConfig.getTopicName(),
orderConf.toString(), true);
System.out.printf("set cluster orderConf. isOrder=%s, orderConf=[%s]", isOrder, orderConf);
}
System.out.printf("%s", topicConfig);
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
#location 57
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void requestThenAssertResponse() throws Exception {
requestThenAssertResponse(remotingClient);
}
|
#vulnerable code
private void requestThenAssertResponse() throws Exception {
RemotingCommand response = remotingClient.invokeSync("localhost:8888", createRequest(), 1000 * 3);
assertTrue(response != null);
assertThat(response.getLanguage()).isEqualTo(LanguageCode.JAVA);
assertThat(response.getExtFields()).hasSize(2);
assertThat(response.getExtFields().get("messageTitle")).isEqualTo("Welcome");
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public LocalTransactionState checkLocalTransactionState(MessageExt msg) {
System.out.printf("server checking TrMsg %s%n", msg);
int value = transactionIndex.getAndIncrement();
if ((value % 6) == 0) {
throw new RuntimeException("Could not find db");
} else if ((value % 5) == 0) {
return LocalTransactionState.ROLLBACK_MESSAGE;
} else if ((value % 4) == 0) {
return LocalTransactionState.COMMIT_MESSAGE;
}
return LocalTransactionState.UNKNOW;
}
|
#vulnerable code
@Override
public LocalTransactionState checkLocalTransactionState(MessageExt msg) {
System.out.printf("server checking TrMsg " + msg.toString() + "%n");
int value = transactionIndex.getAndIncrement();
if ((value % 6) == 0) {
throw new RuntimeException("Could not find db");
} else if ((value % 5) == 0) {
return LocalTransactionState.ROLLBACK_MESSAGE;
} else if ((value % 4) == 0) {
return LocalTransactionState.COMMIT_MESSAGE;
}
return LocalTransactionState.UNKNOW;
}
#location 3
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void should_get_consume_queue_offset_successfully_when_timestamp_is_skewing() throws InterruptedException {
final int totalCount = 10;
int queueId = 0;
String topic = "FooBar";
AppendMessageResult[] appendMessageResults = putMessages(totalCount, topic, queueId, true);
//Thread.sleep(10);
StoreTestUtil.waitCommitLogReput((DefaultMessageStore) messageStore);
int skewing = 2;
ConsumeQueue consumeQueue = getDefaultMessageStore().findConsumeQueue(topic, queueId);
for (AppendMessageResult appendMessageResult : appendMessageResults) {
long offset = messageStore.getOffsetInQueueByTime(topic, queueId, appendMessageResult.getStoreTimestamp() + skewing);
long offset2 = messageStore.getOffsetInQueueByTime(topic, queueId, appendMessageResult.getStoreTimestamp() - skewing);
SelectMappedBufferResult indexBuffer = consumeQueue.getIndexBuffer(offset);
SelectMappedBufferResult indexBuffer2 = consumeQueue.getIndexBuffer(offset2);
assertThat(indexBuffer.getByteBuffer().getLong()).isEqualTo(appendMessageResult.getWroteOffset());
assertThat(indexBuffer.getByteBuffer().getInt()).isEqualTo(appendMessageResult.getWroteBytes());
assertThat(indexBuffer2.getByteBuffer().getLong()).isEqualTo(appendMessageResult.getWroteOffset());
assertThat(indexBuffer2.getByteBuffer().getInt()).isEqualTo(appendMessageResult.getWroteBytes());
indexBuffer.release();
indexBuffer2.release();
}
}
|
#vulnerable code
@Test
public void should_get_consume_queue_offset_successfully_when_timestamp_is_skewing() throws InterruptedException {
final int totalCount = 10;
int queueId = 0;
String topic = "FooBar";
AppendMessageResult[] appendMessageResults = putMessages(totalCount, topic, queueId, true);
Thread.sleep(10);
int skewing = 2;
ConsumeQueue consumeQueue = getDefaultMessageStore().findConsumeQueue(topic, queueId);
for (AppendMessageResult appendMessageResult : appendMessageResults) {
long offset = messageStore.getOffsetInQueueByTime(topic, queueId, appendMessageResult.getStoreTimestamp() + skewing);
long offset2 = messageStore.getOffsetInQueueByTime(topic, queueId, appendMessageResult.getStoreTimestamp() - skewing);
SelectMappedBufferResult indexBuffer = consumeQueue.getIndexBuffer(offset);
SelectMappedBufferResult indexBuffer2 = consumeQueue.getIndexBuffer(offset2);
assertThat(indexBuffer.getByteBuffer().getLong()).isEqualTo(appendMessageResult.getWroteOffset());
assertThat(indexBuffer.getByteBuffer().getInt()).isEqualTo(appendMessageResult.getWroteBytes());
assertThat(indexBuffer2.getByteBuffer().getLong()).isEqualTo(appendMessageResult.getWroteOffset());
assertThat(indexBuffer2.getByteBuffer().getInt()).isEqualTo(appendMessageResult.getWroteBytes());
indexBuffer.release();
indexBuffer2.release();
}
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(MixAll.TOOLS_CONSUMER_GROUP, rpcHook);
try {
String topic = commandLine.getOptionValue('t').trim();
String charsetName =
!commandLine.hasOption('c') ? "UTF-8" : commandLine.getOptionValue('c').trim();
String subExpression =
!commandLine.hasOption('s') ? "*" : commandLine.getOptionValue('s').trim();
boolean printBody = !commandLine.hasOption('d') || Boolean.parseBoolean(commandLine.getOptionValue('d').trim());
consumer.start();
Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues(topic);
for (MessageQueue mq : mqs) {
long minOffset = consumer.minOffset(mq);
long maxOffset = consumer.maxOffset(mq);
if (commandLine.hasOption('b')) {
String timestampStr = commandLine.getOptionValue('b').trim();
long timeValue = timestampFormat(timestampStr);
minOffset = consumer.searchOffset(mq, timeValue);
}
if (commandLine.hasOption('e')) {
String timestampStr = commandLine.getOptionValue('e').trim();
long timeValue = timestampFormat(timestampStr);
maxOffset = consumer.searchOffset(mq, timeValue);
}
System.out.printf("minOffset=%s, maxOffset=%s, %s", minOffset, maxOffset, mq);
READQ:
for (long offset = minOffset; offset < maxOffset; ) {
try {
PullResult pullResult = consumer.pull(mq, subExpression, offset, 32);
offset = pullResult.getNextBeginOffset();
switch (pullResult.getPullStatus()) {
case FOUND:
printMessage(pullResult.getMsgFoundList(), charsetName, printBody);
break;
case NO_MATCHED_MSG:
System.out.printf("%s no matched msg. status=%s, offset=%s", mq, pullResult.getPullStatus(), offset);
break;
case NO_NEW_MSG:
case OFFSET_ILLEGAL:
System.out.printf("%s print msg finished. status=%s, offset=%s", mq, pullResult.getPullStatus(), offset);
break READQ;
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
consumer.shutdown();
}
}
|
#vulnerable code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQPullConsumer consumer = new DefaultMQPullConsumer(MixAll.TOOLS_CONSUMER_GROUP, rpcHook);
try {
String topic = commandLine.getOptionValue('t').trim();
String charsetName =
!commandLine.hasOption('c') ? "UTF-8" : commandLine.getOptionValue('c').trim();
String subExpression =
!commandLine.hasOption('s') ? "*" : commandLine.getOptionValue('s').trim();
boolean printBody = !commandLine.hasOption('d') || Boolean.parseBoolean(commandLine.getOptionValue('d').trim());
consumer.start();
Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues(topic);
for (MessageQueue mq : mqs) {
long minOffset = consumer.minOffset(mq);
long maxOffset = consumer.maxOffset(mq);
if (commandLine.hasOption('b')) {
String timestampStr = commandLine.getOptionValue('b').trim();
long timeValue = timestampFormat(timestampStr);
minOffset = consumer.searchOffset(mq, timeValue);
}
if (commandLine.hasOption('e')) {
String timestampStr = commandLine.getOptionValue('e').trim();
long timeValue = timestampFormat(timestampStr);
maxOffset = consumer.searchOffset(mq, timeValue);
}
System.out.printf("minOffset=%s, maxOffset=%s, %s", minOffset, maxOffset, mq);
READQ:
for (long offset = minOffset; offset < maxOffset; ) {
try {
PullResult pullResult = consumer.pull(mq, subExpression, offset, 32);
offset = pullResult.getNextBeginOffset();
switch (pullResult.getPullStatus()) {
case FOUND:
printMessage(pullResult.getMsgFoundList(), charsetName, printBody);
break;
case NO_MATCHED_MSG:
System.out.printf(mq + " no matched msg. status=%s, offset=%s", pullResult.getPullStatus(), offset);
break;
case NO_NEW_MSG:
case OFFSET_ILLEGAL:
System.out.printf(mq + " print msg finished. status=%s, offset=%s", pullResult.getPullStatus(), offset);
break READQ;
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
consumer.shutdown();
}
}
#location 47
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer,
final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
try {
MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
if (msg != null) {
// resend msg by id
System.out.printf("prepare resend msg. originalMsgId=%s", msgId);
SendResult result = defaultMQProducer.send(msg);
System.out.printf("%s", result);
} else {
System.out.printf("no message. msgId=%s", msgId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
#vulnerable code
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer,
final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
try {
MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
if (msg != null) {
// resend msg by id
System.out.printf("prepare resend msg. originalMsgId=" + msgId);
SendResult result = defaultMQProducer.send(msg);
System.out.printf("%s", result);
} else {
System.out.printf("no message. msgId=" + msgId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#location 7
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testIPv6Check() throws UnknownHostException {
InetAddress nonInternal = InetAddress.getByName("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A");
InetAddress internal = InetAddress.getByName("FE80:0000:0000:0000:0000:0000:0000:FFFF");
assertThat(UtilAll.isInternalV6IP(nonInternal)).isFalse();
assertThat(UtilAll.isInternalV6IP(internal)).isTrue();
assertThat(UtilAll.ipToIPv6Str(nonInternal.getAddress()).toUpperCase()).isEqualTo("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A");
}
|
#vulnerable code
@Test
public void testIPv6Check() {
byte[] nonInternalIp = UtilAll.string2bytes("24084004018081003FAA1DDE2B3F898A");
byte[] internalIp = UtilAll.string2bytes("FEC0000000000000000000000000FFFF");
assertThat(UtilAll.isInternalV6IP(nonInternalIp)).isFalse();
assertThat(UtilAll.isInternalV6IP(internalIp)).isTrue();
assertThat(UtilAll.ipToIPv6Str(nonInternalIp).toUpperCase()).isEqualTo("2408:4004:0180:8100:3FAA:1DDE:2B3F:898A");
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void initialize() {
JSONObject accessControlTransport = AclUtils.getYamlDataObject(fileHome + fileName,
JSONObject.class);
if (accessControlTransport == null || accessControlTransport.isEmpty()) {
throw new AclException(String.format("%s file is not data", fileHome + fileName));
}
log.info("BorkerAccessControlTransport data is : ", accessControlTransport.toString());
JSONArray globalWhiteRemoteAddressesList = accessControlTransport.getJSONArray("globalWhiteRemoteAddresses");
if (globalWhiteRemoteAddressesList != null && !globalWhiteRemoteAddressesList.isEmpty()) {
for (int i = 0; i < globalWhiteRemoteAddressesList.size(); i++) {
addGlobalWhiteRemoteAddress(globalWhiteRemoteAddressesList.getString(i));
}
}
JSONArray accounts = accessControlTransport.getJSONArray("accounts");
if (accounts != null && !accounts.isEmpty()) {
List<PlainAccessConfig> plainAccessList = accounts.toJavaList(PlainAccessConfig.class);
for (PlainAccessConfig plainAccess : plainAccessList) {
this.addPlainAccessResource(getPlainAccessResource(plainAccess));
}
}
}
|
#vulnerable code
public void initialize() {
JSONObject accessControlTransport = AclUtils.getYamlDataObject(fileHome + fileName,
JSONObject.class);
if (accessControlTransport == null || accessControlTransport.isEmpty()) {
throw new AclException(String.format("%s file is not data", fileHome + fileName));
}
log.info("BorkerAccessControlTransport data is : ", accessControlTransport.toString());
JSONArray globalWhiteRemoteAddressesList = accessControlTransport.getJSONArray("globalWhiteRemoteAddresses");
if (globalWhiteRemoteAddressesList != null && !globalWhiteRemoteAddressesList.isEmpty()) {
for (int i = 0; i < globalWhiteRemoteAddressesList.size(); i++) {
addGlobalWhiteRemoteAddress(globalWhiteRemoteAddressesList.getString(i));
}
}
JSONArray accounts = accessControlTransport.getJSONArray("accounts");
List<PlainAccessConfig> plainAccessList = accounts.toJavaList(PlainAccessConfig.class);
if (plainAccessList != null && !plainAccessList.isEmpty()) {
for (PlainAccessConfig plainAccess : plainAccessList) {
this.addPlainAccessResource(getPlainAccessResource(plainAccess));
}
}
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String group = commandLine.getOptionValue('g').trim();
ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group);
boolean jstack = commandLine.hasOption('s');
if (!commandLine.hasOption('i')) {
int i = 1;
long now = System.currentTimeMillis();
final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable =
new TreeMap<String, ConsumerRunningInfo>();
for (Connection conn : cc.getConnectionSet()) {
try {
ConsumerRunningInfo consumerRunningInfo =
defaultMQAdminExt.getConsumerRunningInfo(group, conn.getClientId(), jstack);
if (consumerRunningInfo != null) {
criTable.put(conn.getClientId(), consumerRunningInfo);
String filePath = now + "/" + conn.getClientId();
MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath);
System.out.printf("%03d %-40s %-20s %s%n",
i++,
conn.getClientId(),
MQVersion.getVersionDesc(conn.getVersion()),
filePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!criTable.isEmpty()) {
boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable);
boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable);
if (subSame) {
System.out.printf("%n%nSame subscription in the same group of consumer");
System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed");
Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ConsumerRunningInfo> next = it.next();
String result =
ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
if (result.length() > 0) {
System.out.printf("%s", result);
}
}
} else {
System.out.printf("%n%nWARN: Different subscription in the same group of consumer!!!");
}
}
} else {
String clientId = commandLine.getOptionValue('i').trim();
ConsumerRunningInfo consumerRunningInfo =
defaultMQAdminExt.getConsumerRunningInfo(group, clientId, jstack);
if (consumerRunningInfo != null) {
System.out.printf("%s", consumerRunningInfo.formatString());
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
|
#vulnerable code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
String group = commandLine.getOptionValue('g').trim();
ConsumerConnection cc = defaultMQAdminExt.examineConsumerConnectionInfo(group);
boolean jstack = commandLine.hasOption('s');
if (!commandLine.hasOption('i')) {
int i = 1;
long now = System.currentTimeMillis();
final TreeMap<String/* clientId */, ConsumerRunningInfo> criTable =
new TreeMap<String, ConsumerRunningInfo>();
for (Connection conn : cc.getConnectionSet()) {
try {
ConsumerRunningInfo consumerRunningInfo =
defaultMQAdminExt.getConsumerRunningInfo(group, conn.getClientId(), jstack);
if (consumerRunningInfo != null) {
criTable.put(conn.getClientId(), consumerRunningInfo);
String filePath = now + "/" + conn.getClientId();
MixAll.string2FileNotSafe(consumerRunningInfo.formatString(), filePath);
System.out.printf("%03d %-40s %-20s %s%n",
i++,
conn.getClientId(),
MQVersion.getVersionDesc(conn.getVersion()),
filePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!criTable.isEmpty()) {
boolean subSame = ConsumerRunningInfo.analyzeSubscription(criTable);
boolean rebalanceOK = subSame && ConsumerRunningInfo.analyzeRebalance(criTable);
if (subSame) {
System.out.printf("%n%nSame subscription in the same group of consumer");
System.out.printf("%n%nRebalance %s%n", rebalanceOK ? "OK" : "Failed");
Iterator<Entry<String, ConsumerRunningInfo>> it = criTable.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ConsumerRunningInfo> next = it.next();
String result =
ConsumerRunningInfo.analyzeProcessQueue(next.getKey(), next.getValue());
if (result.length() > 0) {
System.out.printf("%s", result);
}
}
} else {
System.out.printf("%n%nWARN: Different subscription in the same group of consumer!!!");
}
}
} else {
String clientId = commandLine.getOptionValue('i').trim();
ConsumerRunningInfo consumerRunningInfo =
defaultMQAdminExt.getConsumerRunningInfo(group, clientId, jstack);
if (consumerRunningInfo != null) {
System.out.printf(consumerRunningInfo.formatString());
}
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
#location 64
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer,
final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
try {
MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
if (msg != null) {
// resend msg by id
System.out.printf("prepare resend msg. originalMsgId=%s", msgId);
SendResult result = defaultMQProducer.send(msg);
System.out.printf("%s", result);
} else {
System.out.printf("no message. msgId=%s", msgId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
#vulnerable code
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer,
final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
try {
MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
if (msg != null) {
// resend msg by id
System.out.printf("prepare resend msg. originalMsgId=" + msgId);
SendResult result = defaultMQProducer.send(msg);
System.out.printf("%s", result);
} else {
System.out.printf("no message. msgId=" + msgId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#location 11
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void unregisterProducer() throws Exception {
producerManager.registerProducer(group, clientInfo);
Map<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group);
assertThat(channelMap).isNotNull();
assertThat(channelMap.get(channel)).isEqualTo(clientInfo);
Channel channel1 = producerManager.findChannel("clientId");
assertThat(channel1).isNotNull();
assertThat(channel1).isEqualTo(channel);
producerManager.unregisterProducer(group, clientInfo);
channelMap = producerManager.getGroupChannelTable().get(group);
channel1 = producerManager.findChannel("clientId");
assertThat(channelMap).isNull();
assertThat(channel1).isNull();
}
|
#vulnerable code
@Test
public void unregisterProducer() throws Exception {
producerManager.registerProducer(group, clientInfo);
HashMap<Channel, ClientChannelInfo> channelMap = producerManager.getGroupChannelTable().get(group);
assertThat(channelMap).isNotNull();
assertThat(channelMap.get(channel)).isEqualTo(clientInfo);
Channel channel1 = producerManager.findChannel("clientId");
assertThat(channel1).isNotNull();
assertThat(channel1).isEqualTo(channel);
producerManager.unregisterProducer(group, clientInfo);
channelMap = producerManager.getGroupChannelTable().get(group);
channel1 = producerManager.findChannel("clientId");
assertThat(channelMap).isNull();
assertThat(channel1).isNull();
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
DefaultMQProducer producer = new DefaultMQProducer(rpcHook);
producer.setProducerGroup(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
producer.start();
ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();
HashMap<String, Set<String>> clusterAddr = clusterInfoSerializeWrapper
.getClusterAddrTable();
Set<String> clusterNames = null;
long amount = !commandLine.hasOption('a') ? 50 : Long.parseLong(commandLine
.getOptionValue('a').trim());
long size = !commandLine.hasOption('s') ? 128 : Long.parseLong(commandLine
.getOptionValue('s').trim());
long interval = !commandLine.hasOption('i') ? 10 : Long.parseLong(commandLine
.getOptionValue('i').trim());
boolean printAsTlog = commandLine.hasOption('p') && Boolean.parseBoolean(commandLine.getOptionValue('p').trim());
String machineRoom = !commandLine.hasOption('m') ? "noname" : commandLine
.getOptionValue('m').trim();
if (commandLine.hasOption('c')) {
clusterNames = new TreeSet<String>();
clusterNames.add(commandLine.getOptionValue('c').trim());
} else {
clusterNames = clusterAddr.keySet();
}
if (!printAsTlog) {
System.out.printf("%-24s %-24s %-4s %-8s %-8s%n",
"#Cluster Name",
"#Broker Name",
"#RT",
"#successCount",
"#failCount"
);
}
while (true) {
for (String clusterName : clusterNames) {
Set<String> brokerNames = clusterAddr.get(clusterName);
if (brokerNames == null) {
System.out.printf("cluster [%s] not exist", clusterName);
break;
}
for (String brokerName : brokerNames) {
Message msg = new Message(brokerName, getStringBySize(size).getBytes(MixAll.DEFAULT_CHARSET));
long start = 0;
long end = 0;
long elapsed = 0;
int successCount = 0;
int failCount = 0;
for (int i = 0; i < amount; i++) {
start = System.currentTimeMillis();
try {
producer.send(msg);
successCount++;
end = System.currentTimeMillis();
} catch (Exception e) {
failCount++;
end = System.currentTimeMillis();
}
if (i != 0) {
elapsed += end - start;
}
}
double rt = (double) elapsed / (amount - 1);
if (!printAsTlog) {
System.out.printf("%-24s %-24s %-8s %-16s %-16s%n",
clusterName,
brokerName,
String.format("%.2f", rt),
successCount,
failCount
);
} else {
System.out.printf("%s", String.format("%s|%s|%s|%s|%s%n", getCurTime(),
machineRoom, clusterName, brokerName,
new BigDecimal(rt).setScale(0, BigDecimal.ROUND_HALF_UP)));
}
}
}
Thread.sleep(interval * 1000);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
producer.shutdown();
}
}
|
#vulnerable code
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
DefaultMQProducer producer = new DefaultMQProducer(rpcHook);
producer.setProducerGroup(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
producer.start();
ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();
HashMap<String, Set<String>> clusterAddr = clusterInfoSerializeWrapper
.getClusterAddrTable();
Set<String> clusterNames = null;
long amount = !commandLine.hasOption('a') ? 50 : Long.parseLong(commandLine
.getOptionValue('a').trim());
long size = !commandLine.hasOption('s') ? 128 : Long.parseLong(commandLine
.getOptionValue('s').trim());
long interval = !commandLine.hasOption('i') ? 10 : Long.parseLong(commandLine
.getOptionValue('i').trim());
boolean printAsTlog = commandLine.hasOption('p') && Boolean.parseBoolean(commandLine.getOptionValue('p').trim());
String machineRoom = !commandLine.hasOption('m') ? "noname" : commandLine
.getOptionValue('m').trim();
if (commandLine.hasOption('c')) {
clusterNames = new TreeSet<String>();
clusterNames.add(commandLine.getOptionValue('c').trim());
} else {
clusterNames = clusterAddr.keySet();
}
if (!printAsTlog) {
System.out.printf("%-24s %-24s %-4s %-8s %-8s%n",
"#Cluster Name",
"#Broker Name",
"#RT",
"#successCount",
"#failCount"
);
}
while (true) {
for (String clusterName : clusterNames) {
Set<String> brokerNames = clusterAddr.get(clusterName);
if (brokerNames == null) {
System.out.printf("cluster [%s] not exist", clusterName);
break;
}
for (String brokerName : brokerNames) {
Message msg = new Message(brokerName, getStringBySize(size).getBytes(MixAll.DEFAULT_CHARSET));
long start = 0;
long end = 0;
long elapsed = 0;
int successCount = 0;
int failCount = 0;
for (int i = 0; i < amount; i++) {
start = System.currentTimeMillis();
try {
producer.send(msg);
successCount++;
end = System.currentTimeMillis();
} catch (Exception e) {
failCount++;
end = System.currentTimeMillis();
}
if (i != 0) {
elapsed += end - start;
}
}
double rt = (double) elapsed / (amount - 1);
if (!printAsTlog) {
System.out.printf("%-24s %-24s %-8s %-16s %-16s%n",
clusterName,
brokerName,
String.format("%.2f", rt),
successCount,
failCount
);
} else {
System.out.printf(String.format("%s|%s|%s|%s|%s%n", getCurTime(),
machineRoom, clusterName, brokerName,
new BigDecimal(rt).setScale(0, BigDecimal.ROUND_HALF_UP)));
}
}
}
Thread.sleep(interval * 1000);
}
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
producer.shutdown();
}
}
#location 92
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTwoConsumerWithSameGroup() {
int msgSize = 20;
String originMsgDCName = RandomUtils.getStringByUUID();
String msgBodyDCName = RandomUtils.getStringByUUID();
RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
getConsumer(nsAddr, consumer1.getConsumerGroup(), tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
producer.send(tag, msgSize);
Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size());
consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer1.getListner().getAllMsgBody()))
.containsExactlyElementsIn(producer.getAllMsgBody());
}
|
#vulnerable code
@Test
public void testTwoConsumerWithSameGroup() {
String tag = "jueyin";
int msgSize = 20;
String originMsgDCName = RandomUtils.getStringByUUID();
String msgBodyDCName = RandomUtils.getStringByUUID();
RMQNormalConsumer consumer1 = getConsumer(nsAddr, topic, tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
RMQNormalConsumer consumer2 = getConsumer(nsAddr, consumer1.getConsumerGroup(), tag,
new RMQNormalListner(originMsgDCName, msgBodyDCName));
producer.send(tag, msgSize);
Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size());
consumer1.getListner().waitForMessageConsume(producer.getAllMsgBody(), consumeTime);
assertThat(VerifyUtils.getFilterdMessage(producer.getAllMsgBody(),
consumer1.getListner().getAllMsgBody()))
.containsExactlyElementsIn(producer.getAllMsgBody());
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetGroupChannelTable() throws Exception {
producerManager.registerProducer(group, clientInfo);
Map<Channel, ClientChannelInfo> oldMap = producerManager.getGroupChannelTable().get(group);
producerManager.unregisterProducer(group, clientInfo);
assertThat(oldMap.size()).isEqualTo(0);
}
|
#vulnerable code
@Test
public void testGetGroupChannelTable() throws Exception {
producerManager.registerProducer(group, clientInfo);
HashMap<Channel, ClientChannelInfo> oldMap = producerManager.getGroupChannelTable().get(group);
producerManager.unregisterProducer(group, clientInfo);
assertThat(oldMap.size()).isNotEqualTo(0);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws SQLException, Exception {
AllBenchmark.runBenchmark(DbHelper.getConnection(args), DynamicJdbcMapperForEachBenchmark.class);
}
|
#vulnerable code
public static void main(String[] args) throws SQLException, Exception {
AllBenchmark.runBenchmark(DbHelper.mockDb(), SmallBenchmarkObject.class, DynamicJdbcMapperForEachBenchmark.class, BenchmarkConstants.SINGLE_QUERY_SIZE, BenchmarkConstants.SINGLE_NB_ITERATION);
}
#location 2
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public <T> CsvMapperBuilder<T> newBuilder(final Class<T> target) {
ClassMeta<T> classMeta = getClassMeta(target);
CsvMapperBuilder<T> builder = new CsvMapperBuilder<T>(target, classMeta, aliases, customReaders, propertyNameMatcherFactory);
builder.fieldMapperErrorHandler(fieldMapperErrorHandler);
builder.mapperBuilderErrorHandler(mapperBuilderErrorHandler);
builder.setDefaultDateFormat(defaultDateFormat);
return builder;
}
|
#vulnerable code
public <T> CsvMapperBuilder<T> newBuilder(final Class<T> target) {
CsvMapperBuilder<T> builder = new CsvMapperBuilder<T>(target, getClassMeta(target), aliases, customReaders, propertyNameMatcherFactory);
builder.fieldMapperErrorHandler(fieldMapperErrorHandler);
builder.mapperBuilderErrorHandler(mapperBuilderErrorHandler);
builder.setDefaultDateFormat(defaultDateFormat);
return builder;
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ResultSetMapperBuilder<T> addMapping(String property, String column) {
Setter<T, Object> setter = setterFactory.getSetter(target, property);
addMapping(setter, column);
return this;
}
|
#vulnerable code
public ResultSetMapperBuilder<T> addMapping(String property, String column) {
Setter<T, Object> setter = setterFactory.getSetter(target, property);
Mapper<ResultSet, T> fieldMapper;
if (setter.getPropertyType().isPrimitive()) {
fieldMapper = primitiveFieldMapper(column, setter);
} else {
fieldMapper = objectFieldMapper(column, setter);
}
fields.add(fieldMapper);
return this;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testComposition() {
CsvColumnDefinition compose = CsvColumnDefinition.dateFormatDefinition("yyyyMM").addRename("blop").addCustomReader(
new CellValueReader<Integer>() {
@Override
public Integer read(char[] chars, int offset, int length, ParsingContext parsingContext) {
return 3;
}
});
assertEquals("blop", compose.rename(new CsvColumnKey("bar", -1)).getName());
assertEquals("yyyyMM", compose.dateFormat());
assertEquals(new Integer(3), compose.getCustomReader().read(null, 0, 0 , null));
assertTrue(compose.hasCustomSource());
assertEquals(Integer.class, compose.getCustomSourceReturnType());
}
|
#vulnerable code
@Test
public void testComposition() {
CsvColumnDefinition compose = CsvColumnDefinition.compose(CsvColumnDefinition.compose(CsvColumnDefinition.dateFormatDefinition("yyyyMM"), CsvColumnDefinition.renameDefinition("blop")),
CsvColumnDefinition.customReaderDefinition(new CellValueReader<Integer>() {
@Override
public Integer read(char[] chars, int offset, int length, ParsingContext parsingContext) {
return 3;
}
}));
assertEquals("blop", compose.rename(new CsvColumnKey("bar", -1)).getName());
assertEquals("yyyyMM", compose.dateFormat());
assertEquals(new Integer(3), compose.getCustomReader().read(null, 0, 0 , null));
assertTrue(compose.hasCustomSource());
assertEquals(Integer.class, compose.getCustomSourceReturnType());
}
#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 testFindElementOnArray() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getRootClassMeta(DbObject[].class);
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("elt0_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(1, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(3, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("name"));
assertNotNull(propEltId);
assertEquals(0, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
|
#vulnerable code
@Test
public void testFindElementOnArray() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getClassMeta(DbObject[].class);
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("elt0_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(1, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(3, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("name"));
assertNotNull(propEltId);
assertEquals(0, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testPrimitiveField() {
ClassMeta<DbObject> classMeta = ReflectionService.newInstance(true, false).getRootClassMeta(DbObject.class);
PropertyMeta<DbObject, Long> id = classMeta.newPropertyFinder().<Long>findProperty(new DefaultPropertyNameMatcher("id"));
FieldMapperColumnDefinition<JdbcColumnKey, ResultSet> identity = FieldMapperColumnDefinition.identity();
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 1), identity);
FieldMapper<ResultSet, DbObject> fieldMapper = factory.newFieldMapper(
propertyMapping, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping1 = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 0), identity);
fieldMapper = factory.newFieldMapper(propertyMapping1, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
}
|
#vulnerable code
@Test
public void testPrimitiveField() {
ClassMeta<DbObject> classMeta = ReflectionService.newInstance(true, false).getClassMeta(DbObject.class);
PropertyMeta<DbObject, Long> id = classMeta.newPropertyFinder().<Long>findProperty(new DefaultPropertyNameMatcher("id"));
FieldMapperColumnDefinition<JdbcColumnKey, ResultSet> identity = FieldMapperColumnDefinition.identity();
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 1), identity);
FieldMapper<ResultSet, DbObject> fieldMapper = factory.newFieldMapper(
propertyMapping, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping1 = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 0), identity);
fieldMapper = factory.newFieldMapper(propertyMapping1, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
}
#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 testFindElementOnTuple() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getRootClassMeta(Tuples.typeDef(String.class, DbObject.class, DbObject.class));
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("element2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("element1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("elt1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("4_id"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
|
#vulnerable code
@Test
public void testFindElementOnTuple() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getClassMeta(Tuples.typeDef(String.class, DbObject.class, DbObject.class));
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("element2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("element1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("elt1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("4_id"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public UserDTO getUser(@PathVariable("id") Long id) {
User user = accountService.getUser(id);
if (user == null) {
String message = "用户不存在(id:" + id + ")";
logger.warn(message);
throw new RestException(HttpStatus.NOT_FOUND, message);
}
// 使用Dozer转换DTO类,并补充Dozer不能自动绑定的属性
UserDTO dto = BeanMapper.map(user, UserDTO.class);
dto.setTeamId(user.getTeam().getId());
return dto;
}
|
#vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public UserDTO getUser(@PathVariable("id") Long id) {
User user = accountService.getUser(id);
// 使用Dozer转换DTO类,并补充Dozer不能自动绑定的属性
UserDTO dto = BeanMapper.map(user, UserDTO.class);
dto.setTeamId(user.getTeam().getId());
return dto;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void reportExecution(String name, ExecutionMetric execution, long timestamp) throws IOException {
send(MetricRegistry.name(prefix, name, "count"), format(execution.counterMetric.lastCount), timestamp);
send(MetricRegistry.name(prefix, name, "min"), format(execution.histogramMetric.min), timestamp);
send(MetricRegistry.name(prefix, name, "max"), format(execution.histogramMetric.max), timestamp);
send(MetricRegistry.name(prefix, name, "mean"), format(execution.histogramMetric.mean), timestamp);
for (Entry<Double, Long> pct : execution.histogramMetric.pcts.entrySet()) {
send(MetricRegistry.name(prefix, name, format(pct.getKey()).replace('.', '_')), format(pct.getValue()),
timestamp);
}
}
|
#vulnerable code
private void reportExecution(String name, ExecutionMetric execution, long timestamp) throws IOException {
send(MetricRegistry.name(prefix, name, "count"), format(execution.counter.count), timestamp);
send(MetricRegistry.name(prefix, name, "min"), format(execution.histogram.min), timestamp);
send(MetricRegistry.name(prefix, name, "max"), format(execution.histogram.max), timestamp);
send(MetricRegistry.name(prefix, name, "mean"), format(execution.histogram.mean), timestamp);
for (Entry<Double, Long> pct : execution.histogram.pcts.entrySet()) {
send(MetricRegistry.name(prefix, name, format(pct.getKey()).replace('.', '_')), format(pct.getValue()),
timestamp);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %d%n", counter.lastRate);
output.printf(" mean rate = %d%n", counter.meanRate);
}
|
#vulnerable code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %2.2f/s%n", counter.lastRate);
output.printf(" mean rate = %2.2f/s%n", counter.meanRate);
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %d%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %d%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
}
|
#vulnerable code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %2.2f/s%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %2.2f/s%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
}
#location 3
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void printHistogram(HistogramMetric histogram) {
output.printf(" min = %d%n", histogram.min);
output.printf(" max = %d%n", histogram.max);
output.printf(" mean = %2.2f%n", histogram.mean);
for (Entry<Double, Long> pct : histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d %n", pct.getKey(), pct.getValue());
}
}
|
#vulnerable code
private void printHistogram(HistogramMetric histogram) {
output.printf(" min = %d%n", histogram.min);
output.printf(" max = %d%n", histogram.max);
output.printf(" mean = %2.2f%n", histogram.mean);
for (Entry<Double, Long> pct : histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d %n", pct.getKey() * 100, pct.getValue());
}
}
#location 6
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
VideoInfo vi = new VideoInfo(new FileInputStream(input).available());
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
FFmpegUtils.regInfo(runProcess(commands, null), vi);
return vi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
}
|
#vulnerable code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
VideoInfo mi = FFmpegUtils.regInfo(runProcess(commands, null));
mi.setSize(new FileInputStream(input).available());
return mi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
}
#location 29
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
PdfObject refersTo = indirect.getRefersTo();
if (refersTo.getObjectStream() != null) {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(refersTo.getObjectStream().getIndirectReference().getObjNr()));
stream.getOutputStream().write(shortToBytes(refersTo.getOffset()));
} else {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(refersTo.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getRefersTo().getOffset())).
writeBytes(endXRefEntry);
}
}
return strtxref;
}
|
#vulnerable code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
PdfObject refersTo = indirect.getRefersTo();
if (refersTo.getObjectStream() != null) {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(refersTo.getObjectStream().getIndirectReference().getObjNr()));
stream.getOutputStream().write(shortToBytes(refersTo.getOffset()));
} else {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(refersTo.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getRefersTo().getOffset())).
writeString(" 00000 n \n");
}
}
return strtxref;
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
Map<String, PdfFormField> fields = getFormFields();
PdfPage page = null;
for (Map.Entry<String, PdfFormField> entry : fields.entrySet()) {
PdfFormField field = entry.getValue();
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
page = getPage(pageDic);
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page != null && page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
}
|
#vulnerable code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
List<PdfFormField> fields = getFormFields();
PdfPage page = null;
for (PdfFormField field : fields) {
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
for (int i = 1; i <= document.getNumOfPages(); i++) {
page = document.getPage(i);
if (page.getPdfObject() == pageDic) {
break;
}
}
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
}
#location 64
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest03() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest03.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest03.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setRotateAngle(Math.PI/6);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest03() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest03.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest03.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setRotateAngle(Math.PI/6);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotationAngle(Math.PI / 6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotationAngle(Math.PI / 6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 28
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public PdfObject getDestinationPage(HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString());
return array != null ? array.get(0, false) : null;
}
|
#vulnerable code
@Override
public PdfObject getDestinationPage(HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString());
return array.get(0, false);
}
#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 formFieldTest01() throws IOException {
PdfReader reader = new PdfReader(sourceFolder + "formFieldFile.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);
Map<String, PdfFormField> fields = form.getFormFields();
PdfFormField field = fields.get("Text1");
Assert.assertTrue(fields.size() == 6);
Assert.assertTrue(field.getFieldName().toUnicodeString().equals("Text1"));
Assert.assertTrue(field.getValue().toString().equals("TestField"));
}
|
#vulnerable code
@Test
public void formFieldTest01() throws IOException {
PdfReader reader = new PdfReader(sourceFolder + "formFieldFile.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);
ArrayList<PdfFormField> fields = (ArrayList<PdfFormField>) form.getFormFields();
PdfFormField field = fields.get(3);
Assert.assertTrue(fields.size() == 6);
Assert.assertTrue(field.getFieldName().toUnicodeString().equals("Text1"));
Assert.assertTrue(field.getValue().toString().equals("TestField"));
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void justify(float width) {
float ratio = getPropertyAsFloat(Property.SPACING_RATIO);
float freeWidth = occupiedArea.getBBox().getX() + width -
getLastChildRenderer().getOccupiedArea().getBBox().getX() - getLastChildRenderer().getOccupiedArea().getBBox().getWidth();
int numberOfSpaces = getNumberOfSpaces();
int lineLength = length();
float baseFactor = freeWidth / (ratio * numberOfSpaces + (1 - ratio) * (lineLength - 1));
float wordSpacing = ratio * baseFactor;
float characterSpacing = (1 - ratio) * baseFactor;
float lastRightPos = occupiedArea.getBBox().getX();
for (IRenderer child : childRenderers) {
float childX = child.getOccupiedArea().getBBox().getX();
child.move(lastRightPos - childX, 0);
childX = lastRightPos;
if (child instanceof TextRenderer) {
float childHSCale = child.getProperty(Property.HORIZONTAL_SCALING);
child.setProperty(Property.CHARACTER_SPACING, characterSpacing / childHSCale);
child.setProperty(Property.WORD_SPACING, wordSpacing / childHSCale);
child.getOccupiedArea().getBBox().setWidth(child.getOccupiedArea().getBBox().getWidth() +
characterSpacing * ((TextRenderer) child).length() + wordSpacing * ((TextRenderer) child).getNumberOfSpaces());
}
lastRightPos = childX + child.getOccupiedArea().getBBox().getWidth();
}
getOccupiedArea().getBBox().setWidth(width);
}
|
#vulnerable code
protected void justify(float width) {
float ratio = .5f;
float freeWidth = occupiedArea.getBBox().getX() + width -
getLastChildRenderer().getOccupiedArea().getBBox().getX() - getLastChildRenderer().getOccupiedArea().getBBox().getWidth();
int numberOfSpaces = getNumberOfSpaces();
int lineLength = length();
float baseFactor = freeWidth / (ratio * numberOfSpaces + lineLength - 1);
float wordSpacing = ratio * baseFactor;
float characterSpacing = baseFactor;
float lastRightPos = occupiedArea.getBBox().getX();
for (IRenderer child : childRenderers) {
float childX = child.getOccupiedArea().getBBox().getX();
child.move(lastRightPos - childX, 0);
childX = lastRightPos;
if (child instanceof TextRenderer) {
float childHSCale = child.getProperty(Property.HORIZONTAL_SCALING);
child.setProperty(Property.CHARACTER_SPACING, characterSpacing / childHSCale);
child.setProperty(Property.WORD_SPACING, wordSpacing / childHSCale);
child.getOccupiedArea().getBBox().setWidth(child.getOccupiedArea().getBBox().getWidth() +
characterSpacing * ((TextRenderer) child).length() + wordSpacing * ((TextRenderer) child).getNumberOfSpaces());
}
lastRightPos = childX + child.getOccupiedArea().getBBox().getWidth();
}
getOccupiedArea().getBBox().setWidth(width);
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void buildResources(PdfDictionary dictionary) throws PdfException {
for (PdfName resourceType : dictionary.keySet()) {
if (nameToResource.get(resourceType) == null) {
nameToResource.put(resourceType, new HashMap<PdfName, PdfObject>());
}
PdfDictionary resources = dictionary.getAsDictionary(resourceType);
if (resources == null)
continue;
for (PdfName resourceName : resources.keySet()) {
PdfObject resource = resources.get(resourceName, false);
resourceToName.put(resource, resourceName);
nameToResource.get(resourceType).put(resourceName, resource);
}
}
Set<PdfName> names = getResourceNames();
fontNumber = getAvailableNumber(names, F);
imageNumber = getAvailableNumber(names, Im);
formNumber = getAvailableNumber(names, Fm);
egsNumber = getAvailableNumber(names, Gs);
propNumber = getAvailableNumber(names, Pr);
csNumber = getAvailableNumber(names, Cs);
}
|
#vulnerable code
protected void buildResources(PdfDictionary dictionary) throws PdfException {
for (PdfName resourceType : dictionary.keySet()) {
if (nameToResource.get(resourceType) == null) {
nameToResource.put(resourceType, new HashMap<PdfName, PdfObject>());
}
PdfDictionary resources = dictionary.getAsDictionary(resourceType);
for (PdfName resourceName : resources.keySet()) {
PdfObject resource = resources.get(resourceName, false);
resourceToName.put(resource, resourceName);
nameToResource.get(resourceType).put(resourceName, resource);
}
}
Set<PdfName> names = getResourceNames();
fontNumber = getAvailableNumber(names, F);
imageNumber = getAvailableNumber(names, Im);
formNumber = getAvailableNumber(names, Fm);
egsNumber = getAvailableNumber(names, Gs);
propNumber = getAvailableNumber(names, Pr);
csNumber = getAvailableNumber(names, Cs);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 23
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
imageWidth = xObject.getWidth();
imageHeight = xObject.getHeight();
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
|
#vulnerable code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
if (xObject instanceof PdfImageXObject) {
imageWidth = ((PdfImageXObject)xObject).getWidth();
imageHeight = ((PdfImageXObject)xObject).getHeight();
} else {
imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2);
imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3);
}
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfFormXObject xObject = new PdfFormXObject(document, null);
Rectangle rect = placeBarcode(new PdfCanvas(xObject), barColor, textColor);
xObject.setBBox(rect.toPdfArray());
return xObject;
}
|
#vulnerable code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfStream stream = new PdfStream(document);
PdfCanvas canvas = new PdfCanvas(stream, new PdfResources());
Rectangle rect = placeBarcode(canvas, barColor, textColor);
PdfFormXObject xObject = new PdfFormXObject(document, rect);
xObject.getPdfObject().getOutputStream().writeBytes(stream.getBytes());
return xObject;
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
Map<String, PdfFormField> fields = getFormFields();
PdfPage page = null;
for (Map.Entry<String, PdfFormField> entry : fields.entrySet()) {
PdfFormField field = entry.getValue();
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
page = getPage(pageDic);
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page != null && page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
}
|
#vulnerable code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
List<PdfFormField> fields = getFormFields();
PdfPage page = null;
for (PdfFormField field : fields) {
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
for (int i = 1; i <= document.getNumOfPages(); i++) {
page = document.getPage(i);
if (page.getPdfObject() == pageDic) {
break;
}
}
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
}
#location 46
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
|
#vulnerable code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 28
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public OutputStream writeInteger(int value) throws IOException {
writeInteger(value, 8);
return this;
}
|
#vulnerable code
public OutputStream writeInteger(int value) throws IOException {
write(getIsoBytes(String.valueOf(value)));
return this;
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
if(!result){
log.warn("项目访问权限不通过,被访项目ID:{},用户项目权限列表:{}",projectId,JSON.toJSONString(projectIDList));
}
return result;
}
|
#vulnerable code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getSysUser().getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
return result;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
ByteArrayInputStream stream = new ByteArrayInputStream(qrData);
String qrUrl = QRCodeUtils.decode(stream);
stream.close();
String qr = QRCodeUtils.generateQR(qrUrl, 40, 40);
System.out.println(qr);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
} catch (NotFoundException ex) {
throw new WechatException(ex);
} catch (WriterException ex) {
throw new WechatException(ex);
}
}
|
#vulnerable code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
String path = "E://qr//qr.jpg";
OutputStream out = new FileOutputStream(path);
out.write(qrData);
out.flush();
out.close();
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c start " + path);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
}
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
ByteArrayInputStream stream = new ByteArrayInputStream(qrData);
String qrUrl = QRCodeUtils.decode(stream);
stream.close();
String qr = QRCodeUtils.generateQR(qrUrl, 40, 40);
System.out.println(qr);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
} catch (NotFoundException ex) {
throw new WechatException(ex);
} catch (WriterException ex) {
throw new WechatException(ex);
}
}
|
#vulnerable code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
String path = "E://qr//qr.jpg";
OutputStream out = new FileOutputStream(path);
out.write(qrData);
out.flush();
out.close();
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c start " + path);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
}
}
#location 115
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static void initDocBuilder() throws ParserConfigurationException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringComments(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
if (publicId.equals("-//Apple Computer//DTD PLIST 1.0//EN") || // older publicId
publicId.equals("-//Apple//DTD PLIST 1.0//EN")) { // newer publicId
// return a dummy, zero length DTD so we don't have to fetch
// it from the network.
return new InputSource(new ByteArrayInputStream(new byte[0]));
}
return null;
}
});
}
|
#vulnerable code
private static void initDocBuilder() throws ParserConfigurationException {
boolean offline = false;
try {
URL dtdUrl = new URL("http://www.apple.com/DTDs/PropertyList-1.0.dtd");
InputStream dtdIs = dtdUrl.openStream();
dtdIs.read();
dtdIs.close();
//If we came this far the DTD is accessible
} catch (Exception ex) {
System.out.println("DTD is not accessible: "+ex.getLocalizedMessage());
System.out.println("Switching to offline parsing");
offline = true;
}
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
if(System.getProperty("java.vendor").toLowerCase().contains("android")) {
//The Android parser works differently
//See discussion around issue 13 (https://code.google.com/p/plist/issues/detail?id=13)
docBuilderFactory.setValidating(false);
skipTextNodes = true;
} else {
if(offline) {
docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
docBuilderFactory.setValidating(false);
skipTextNodes = true;
} else {
docBuilderFactory.setValidating(true);
docBuilderFactory.setIgnoringElementContentWhitespace(true);
skipTextNodes = false;
}
}
docBuilderFactory.setIgnoringComments(true);
docBuilder = docBuilderFactory.newDocumentBuilder();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void saveAsXML(NSObject root, File out) throws IOException {
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(out), "UTF-8");
w.write(root.toXMLPropertyList());
w.close();
}
|
#vulnerable code
public static void saveAsXML(NSObject root, File out) throws IOException {
FileWriter fw = new FileWriter(out);
fw.write(root.toXMLPropertyList());
fw.close();
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
return parse(fis);
}
|
#vulnerable code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
byte[] magic = new byte[8];
fis.read(magic);
String magic_string = new String(magic);
fis.close();
if (magic_string.startsWith("bplist00")) {
return BinaryPropertyListParser.parse(f);
} else if (magic_string.startsWith("<?xml")) {
return XMLPropertyListParser.parse(f);
} else {
throw new UnsupportedOperationException("The given file is neither a binary nor a XML property list. ASCII property lists are not supported.");
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void runTagger() throws IOException, ClassNotFoundException {
tagger = new Tagger();
if (!justTokenize) {
tagger.loadModel(modelFilename);
}
if (inputFormat.equals("conll")) {
runTaggerInEvalMode();
return;
}
assert (inputFormat.equals("json") || inputFormat.equals("text"));
JsonTweetReader jsonTweetReader = new JsonTweetReader();
LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename));
String line;
long currenttime = System.currentTimeMillis();
int numtoks = 0;
while ( (line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String tweetData = parts[inputField-1];
if (reader.getLineNumber()==1) {
if (inputFormat.equals("auto")) {
detectAndSetInputFormat(tweetData);
}
}
String text;
if (inputFormat.equals("json")) {
text = jsonTweetReader.getText(tweetData);
if (text==null) {
System.err.println("Warning, null text (JSON parse error?), using blank string instead");
text = "";
}
} else {
text = tweetData;
}
Sentence sentence = new Sentence();
sentence.tokens = Twokenize.tokenizeRawTweetText(text);
ModelSentence modelSentence = null;
if (sentence.T() > 0 && !justTokenize) {
modelSentence = new ModelSentence(sentence.T());
tagger.featureExtractor.computeFeatures(sentence, modelSentence);
goDecode(modelSentence);
}
if (outputFormat.equals("conll")) {
outputJustTagging(sentence, modelSentence);
} else {
outputPrependedTagging(sentence, modelSentence, justTokenize, line);
}
numtoks += sentence.T();
}
long finishtime = System.currentTimeMillis();
System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n",
justTokenize ? "" : " and tagged",
reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0,
reader.getLineNumber() / ((finishtime-currenttime)/1000.0),
numtoks / ((finishtime-currenttime)/1000.0)
);
reader.close();
}
|
#vulnerable code
public void runTagger() throws IOException, ClassNotFoundException {
tagger = new Tagger();
if (!justTokenize) {
tagger.loadModel(modelFilename);
}
if (inputFormat.equals("conll")) {
runTaggerInEvalMode();
return;
}
assert (inputFormat.equals("json") || inputFormat.equals("text"));
JsonTweetReader jsonTweetReader = new JsonTweetReader();
LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename));
String line;
long currenttime = System.currentTimeMillis();
int numtoks = 0;
while ( (line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String tweetData = parts[inputField-1];
String text;
if (inputFormat.equals("json")) {
text = jsonTweetReader.getText(tweetData);
} else {
text = tweetData;
}
Sentence sentence = new Sentence();
sentence.tokens = Twokenize.tokenizeRawTweetText(text);
ModelSentence modelSentence = null;
if (sentence.T() > 0 && !justTokenize) {
modelSentence = new ModelSentence(sentence.T());
tagger.featureExtractor.computeFeatures(sentence, modelSentence);
goDecode(modelSentence);
}
if (outputFormat.equals("conll")) {
outputJustTagging(sentence, modelSentence);
} else {
outputPrependedTagging(sentence, modelSentence, justTokenize, tweetData);
}
numtoks += sentence.T();
}
long finishtime = System.currentTimeMillis();
System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n",
justTokenize ? "" : " and tagged",
reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0,
reader.getLineNumber() / ((finishtime-currenttime)/1000.0),
numtoks / ((finishtime-currenttime)/1000.0)
);
reader.close();
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ArrayList<Sentence> readFile(String filename) throws IOException {
BufferedReader reader = BasicFileIO.openFileToReadUTF8(filename);
ArrayList sentences = new ArrayList<String>();
ArrayList<String> curLines = new ArrayList<String>();
String line;
while ( (line = reader.readLine()) != null ) {
if (line.matches("^\\s*$")) {
if (curLines.size() > 0) {
// Flush
sentences.add(sentenceFromLines(curLines));
curLines.clear();
}
} else {
curLines.add(line);
}
}
if (curLines.size() > 0) {
sentences.add(sentenceFromLines(curLines));
}
return sentences;
}
|
#vulnerable code
public static ArrayList<Sentence> readFile(String filename) throws IOException {
BufferedReader reader = BasicFileIO.openFileToRead(filename);
ArrayList sentences = new ArrayList<String>();
ArrayList<String> curLines = new ArrayList<String>();
String line;
while ( (line = reader.readLine()) != null ) {
if (line.matches("^\\s*$")) {
if (curLines.size() > 0) {
// Flush
sentences.add(sentenceFromLines(curLines));
curLines.clear();
}
} else {
curLines.add(line);
}
}
if (curLines.size() > 0) {
sentences.add(sentenceFromLines(curLines));
}
return sentences;
}
#location 21
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Transactional
public Operation save(Long apiId, Long resourceId, Operation operation) {
Resource resource = resourceRepository.findByApiIdAndId(apiId, resourceId);
HeimdallException.checkThrow(resource == null, GLOBAL_RESOURCE_NOT_FOUND);
Operation resData = operationRepository.findByResourceApiIdAndMethodAndPath(apiId, operation.getMethod(), operation.getPath());
HeimdallException.checkThrow(resData != null &&
Objects.equals(resData.getResource().getId(), resource.getId()), ONLY_ONE_OPERATION_PER_RESOURCE);
boolean patternExists = operationJDBCRepository.countPattern(resource.getApi().getBasePath() + "/" + operation.getPath());
HeimdallException.checkThrow(patternExists, OPERATION_ROUTE_ALREADY_EXISTS);
operation.setResource(resource);
operation.setPath(StringUtils.removeMultipleSlashes(operation.getPath()));
HeimdallException.checkThrow(validateSingleWildCardOperationPath(operation), OPERATION_CANT_HAVE_SINGLE_WILDCARD);
HeimdallException.checkThrow(validateDoubleWildCardOperationPath(operation), OPERATION_CANT_HAVE_DOUBLE_WILDCARD_NOT_AT_THE_END);
operation = operationRepository.save(operation);
amqpRoute.dispatchRoutes();
return operation;
}
|
#vulnerable code
@Transactional
public Operation save(Long apiId, Long resourceId, Operation operation) {
Resource resource = resourceRepository.findByApiIdAndId(apiId, resourceId);
HeimdallException.checkThrow(resource == null, GLOBAL_RESOURCE_NOT_FOUND);
Operation resData = operationRepository.findByResourceApiIdAndMethodAndPath(apiId, operation.getMethod(), operation.getPath());
HeimdallException.checkThrow(resData != null &&
Objects.equals(resData.getResource().getId(), resource.getId()), ONLY_ONE_OPERATION_PER_RESOURCE);
operation.setResource(resource);
operation.setPath(StringUtils.removeMultipleSlashes(operation.getPath()));
HeimdallException.checkThrow(validateSingleWildCardOperationPath(operation), OPERATION_CANT_HAVE_SINGLE_WILDCARD);
HeimdallException.checkThrow(validateDoubleWildCardOperationPath(operation), OPERATION_CANT_HAVE_DOUBLE_WILDCARD_NOT_AT_THE_END);
operation = operationRepository.save(operation);
amqpRoute.dispatchRoutes();
return operation;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "creationDate"));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit(), sort);
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
}
|
#vulnerable code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit());
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (entry.getKey() != null) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (operations != null && !operations.isEmpty()) {
operation = operations.stream().filter(o -> o.getMethod().equals(HttpMethod.ALL) || method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (operation != null) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put(PATTERN, org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
ctx.put(API_NAME, operation.getResource().getApi().getName());
ctx.put(API_ID, operation.getResource().getApi().getId());
ctx.put(RESOURCE_ID, operation.getResource().getId());
ctx.put(OPERATION_ID, operation.getId());
ctx.put("scopes", operation.getScopesIds());
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (environments != null) {
String host = ctx.getRequest().getHeader("Host");
Optional<Environment> environment;
if (host != null && !host.isEmpty()) {
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(host.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();
traceContextHolder.getActualTrace().setApiId(operation.getResource().getApi().getId());
traceContextHolder.getActualTrace().setApiName(operation.getResource().getApi().getName());
traceContextHolder.getActualTrace().setResourceId(operation.getResource().getId());
traceContextHolder.getActualTrace().setOperationId(operation.getId());
traceContextHolder.getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
}
|
#vulnerable code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (entry.getKey() != null) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (operations != null && !operations.isEmpty()) {
operation = operations.stream().filter(o -> o.getMethod().equals(HttpMethod.ALL) || method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (operation != null) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put(PATTERN, org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
ctx.put(API_NAME, operation.getResource().getApi().getName());
ctx.put(API_ID, operation.getResource().getApi().getId());
ctx.put(RESOURCE_ID, operation.getResource().getId());
ctx.put(OPERATION_ID, operation.getId());
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (environments != null) {
String host = ctx.getRequest().getHeader("Host");
Optional<Environment> environment;
if (host != null && !host.isEmpty()) {
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(host.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();
traceContextHolder.getActualTrace().setApiId(operation.getResource().getApi().getId());
traceContextHolder.getActualTrace().setApiName(operation.getResource().getApi().getName());
traceContextHolder.getActualTrace().setResourceId(operation.getResource().getId());
traceContextHolder.getActualTrace().setOperationId(operation.getId());
traceContextHolder.getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
}
#location 50
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void execute() throws Throwable {
RequestContext ctx = RequestContext.getCurrentContext();
RequestResponseParser r = new RequestResponseParser();
r.setUri(UrlUtil.getCurrentUrl(ctx.getRequest()));
Map<String, String> headers = ResponseHandler.getResponseHeaders(ctx);
r.setHeaders(headers);
String body = ResponseHandler.getResponseBody(ctx, headers, helper);
r.setBody(body);
TraceContextHolder.getInstance().getActualTrace().setResponse(r);
}
|
#vulnerable code
private void execute() throws Throwable {
RequestContext ctx = RequestContext.getCurrentContext();
RequestResponseParser r = new RequestResponseParser();
r.setUri(UrlUtil.getCurrentUrl(ctx.getRequest()));
Map<String, String> headers = getResponseHeaders(ctx);
r.setHeaders(headers);
String content = headers.get(HttpHeaders.CONTENT_TYPE);
// if the content type is not defined by api server then permit to read the body. Prevent NPE
if (Objeto.isBlank(content)) content = "";
String[] types = content.split(";");
if (!ContentTypeUtils.belongsToBlackList(types)) {
@Cleanup
InputStream stream = ctx.getResponseDataStream();
String body;
body = StreamUtils.copyToString(stream, StandardCharsets.UTF_8);
if (body.isEmpty() && helper.call().response().getBody() != null) {
body = helper.call().response().getBody();
}
if (Objects.nonNull(body) && !body.isEmpty()) {
r.setBody(body);
}
ctx.setResponseDataStream(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
}
TraceContextHolder.getInstance().getActualTrace().setResponse(r);
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void execute() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
RequestResponseParser r = new RequestResponseParser();
r.setHeaders(getRequestHeadersInfo(request));
r.setBody(helper.call().request().getBody());
r.setUri(UrlUtil.getCurrentUrl(request));
TraceContextHolder.getInstance().getActualTrace().setRequest(r);
}
|
#vulnerable code
private void execute() {
Helper helper = new HelperImpl();
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
RequestResponseParser r = new RequestResponseParser();
r.setHeaders(getRequestHeadersInfo(request));
r.setBody(helper.call().request().getBody());
r.setUri(UrlUtil.getCurrentUrl(request));
TraceContextHolder.getInstance().getActualTrace().setRequest(r);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void execute(Integer status, String body) {
RequestContext ctx = RequestContext.getCurrentContext();
String response;
if (helper.json().isJson(body)) {
response = helper.json().parse(body);
helper.call().response().header().add("Content-Type", "application/json");
} else {
response = body;
helper.call().response().header().add("Content-Type", "text/plain");
}
helper.call().response().setBody(response);
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(status);
TraceContextHolder.getInstance().getActualTrace().trace(ConstantsInterceptors.GLOBAL_MOCK_INTERCEPTOR_LOCALIZED, response);
}
|
#vulnerable code
public void execute(Integer status, String body) {
Helper helper = new HelperImpl();
RequestContext ctx = RequestContext.getCurrentContext();
String response;
if (helper.json().isJson(body)) {
response = helper.json().parse(body);
helper.call().response().header().add("Content-Type", "application/json");
} else {
response = body;
helper.call().response().header().add("Content-Type", "text/plain");
}
helper.call().response().setBody(response);
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(status);
TraceContextHolder.getInstance().getActualTrace().trace(ConstantsInterceptors.GLOBAL_MOCK_INTERCEPTOR_LOCALIZED, response);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private MongoDatabase database() {
return this.mongoClient.getDatabase(databaseName);
}
|
#vulnerable code
private MongoDatabase database() {
return createMongoClient().getDatabase(databaseName);
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
try {
this.lock.writeLock().lock();
this.stop = true;
this.torrentFileProvider.unRegisterListener(this);
this.thread.interrupt();
try {
this.thread.join();
} catch (final InterruptedException ignored) {
}
this.delayQueue.drainAll().stream()
.filter(req -> req.getEvent() != RequestEvent.STARTED)
.map(AnnounceRequest::getAnnouncer)
.map(AnnounceRequest::createStop)
.forEach(this.announcerExecutor::execute);
this.announcerExecutor.awaitForRunningTasks();
} finally {
this.lock.writeLock().unlock();
}
}
|
#vulnerable code
@Override
public void stop() {
this.stop = true;
this.torrentFileProvider.unRegisterListener(this);
this.thread.interrupt();
try {
this.thread.join();
} catch (final InterruptedException ignored) {
}
this.delayQueue.drainAll().stream()
.filter(req -> req.getEvent() != RequestEvent.STARTED)
.map(AnnounceRequest::getAnnouncer)
.map(AnnounceRequest::createStop)
.forEach(this.announcerExecutor::execute);
this.announcerExecutor.awaitForRunningTasks();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
ResultCursor result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
|
#vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
Result result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
ResultCursor result = builder.build();
result.first();
// WHEN
List<Pair<String, Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalPair.of( "k1", 42 ) ) ) );
}
|
#vulnerable code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
ResultCursor result = builder.build();
result.first();
// WHEN
List<Entry<Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalEntry.of( "k1", 42 ) ) ) );
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean serverResponds() throws IOException, InterruptedException
{
try
{
URI uri = URI.create( DEFAULT_URL );
SocketClient client = new SocketClient( uri.getHost(), uri.getPort() );
client.start();
client.stop();
return true;
}
catch ( ClientException e )
{
return false;
}
}
|
#vulnerable code
private boolean serverResponds() throws IOException, InterruptedException
{
try
{
URI uri = URI.create( DEFAULT_URL );
SocketClient client = new SocketClient( uri.getHost(), uri.getPort(), new DevNullLogger() );
client.start();
client.stop();
return true;
}
catch ( ClientException e )
{
return false;
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static String resource( String fileName )
{
File resource = new File( TestNeo4j.TEST_RESOURCE_FOLDER_PATH, fileName );
if ( !resource.exists() )
{
fail( fileName + " does not exists" );
}
return resource.getAbsolutePath();
}
|
#vulnerable code
private static String resource( String fileName )
{
URL resource = StubServer.class.getClassLoader().getResource( fileName );
if ( resource == null )
{
fail( fileName + " does not exists" );
}
return resource.getFile();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
try ( BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ) )
{
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
}
}
|
#vulnerable code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) );
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
reader.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Make sure we have some configuration to play with
config = config == null ? Config.defaultConfig() : config;
return new DriverFactory().newInstance( uri, authToken, config.routingSettings(), config );
}
|
#vulnerable code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Break down the URI into its constituent parts
String scheme = uri.getScheme();
BoltServerAddress address = BoltServerAddress.from( uri );
// Make sure we have some configuration to play with
if ( config == null )
{
config = Config.defaultConfig();
}
// Construct security plan
SecurityPlan securityPlan;
try
{
securityPlan = createSecurityPlan( address, config );
}
catch ( GeneralSecurityException | IOException ex )
{
throw new ClientException( "Unable to establish SSL parameters", ex );
}
ConnectionPool connectionPool = createConnectionPool( authToken, securityPlan, config );
switch ( scheme.toLowerCase() )
{
case "bolt":
return new DirectDriver( address, connectionPool, securityPlan, config.logging() );
case "bolt+routing":
return new RoutingDriver(
config.routingSettings(),
address,
connectionPool,
securityPlan,
Clock.SYSTEM,
config.logging() );
default:
throw new ClientException( format( "Unsupported URI scheme: %s", scheme ) );
}
}
#location 39
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
ResultCursor result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
|
#vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
Result result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
void shouldSaveNewCert() throws Throwable
{
// Given
int newPort = 200;
BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort );
Logger logger = mock(Logger.class);
TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger );
String fingerprint = fingerprint( knownCertificate );
// When
manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null );
// Then no exception should've been thrown, and we should've logged that we now trust this certificate
verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" );
// And the file should contain the right info
try ( Scanner reader = new Scanner( knownCertsFile ) )
{
String line1 = nextLine( reader );
assertEquals( knownServer + " " + fingerprint, line1 );
assertTrue( reader.hasNextLine() );
String line2 = nextLine( reader );
assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line2 );
}
}
|
#vulnerable code
@Test
void shouldSaveNewCert() throws Throwable
{
// Given
int newPort = 200;
BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort );
Logger logger = mock(Logger.class);
TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger );
String fingerprint = fingerprint( knownCertificate );
// When
manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null );
// Then no exception should've been thrown, and we should've logged that we now trust this certificate
verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" );
// And the file should contain the right info
Scanner reader = new Scanner( knownCertsFile );
String line;
line = nextLine( reader );
assertEquals( knownServer + " " + fingerprint, line );
assertTrue( reader.hasNextLine() );
line = nextLine( reader );
assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line );
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
}
|
#vulnerable code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
try
{
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
}
catch ( Throwable initError )
{
connection.close();
throw initError;
}
return connection;
}
|
#vulnerable code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
return connection;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldBeAbleToUseSessionAgainWhenTransactionIsClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction().close();
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
}
|
#vulnerable code
@Test
public void shouldBeAbleToUseSessionAgainWhenTransactionIsClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction().close();
// When
sess.run( "whatever" );
// Then
verify( mock ).sync();
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Driver driverWithPool( ConnectionPool pool )
{
Logging logging = DEV_NULL_LOGGING;
RoutingSettings settings = new RoutingSettings( 10, 5_000, null );
AsyncConnectionPool asyncConnectionPool = mock( AsyncConnectionPool.class );
when( asyncConnectionPool.close() ).thenReturn( completedFuture( null ) );
LoadBalancingStrategy loadBalancingStrategy = new LeastConnectedLoadBalancingStrategy( pool,
asyncConnectionPool, logging );
ConnectionProvider connectionProvider = new LoadBalancer( SEED, settings, pool, asyncConnectionPool,
GlobalEventExecutor.INSTANCE, clock, logging, loadBalancingStrategy );
Config config = Config.build().withLogging( logging ).toConfig();
SessionFactory sessionFactory = new NetworkSessionWithAddressFactory( connectionProvider, config );
return new InternalDriver( insecure(), sessionFactory, logging );
}
|
#vulnerable code
private Driver driverWithPool( ConnectionPool pool )
{
Logging logging = DEV_NULL_LOGGING;
RoutingSettings settings = new RoutingSettings( 10, 5_000, null );
AsyncConnectionPool asyncConnectionPool = mock( AsyncConnectionPool.class );
LoadBalancingStrategy loadBalancingStrategy = new LeastConnectedLoadBalancingStrategy( pool,
asyncConnectionPool, logging );
ConnectionProvider connectionProvider = new LoadBalancer( SEED, settings, pool, asyncConnectionPool,
GlobalEventExecutor.INSTANCE, clock, logging, loadBalancingStrategy );
Config config = Config.build().withLogging( logging ).toConfig();
SessionFactory sessionFactory = new NetworkSessionWithAddressFactory( connectionProvider, config );
return new InternalDriver( insecure(), sessionFactory, logging );
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
try( Driver driver = GraphDatabase.driver( URI.create( Neo4jRunner.DEFAULT_URL ), config );
Session session = driver.session() )
{
StatementResult result = session.run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
}
}
|
#vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
StatementResult result = driver.session().run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
driver.close();
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings( "ConstantConditions" )
@Test
public void shouldHandleNullAuthToken() throws Throwable
{
// Given
AuthToken token = null;
try ( Driver driver = GraphDatabase.driver( neo4j.address(), token ) )
{
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
}
|
#vulnerable code
@SuppressWarnings( "ConstantConditions" )
@Test
public void shouldHandleNullAuthToken() throws Throwable
{
// Given
AuthToken token = null;
Driver driver = GraphDatabase.driver( neo4j.address(), token);
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
void shouldContainTimeInformation()
{
// Given
ResultSummary summary = session.run( "UNWIND range(1,1000) AS n RETURN n AS number" ).consume();
// Then
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
}
|
#vulnerable code
@Test
void shouldContainTimeInformation()
{
// Given
ResultSummary summary = session.run( "UNWIND range(1,1000) AS n RETURN n AS number" ).consume();
// Then
ServerVersion serverVersion = ServerVersion.version( summary.server().version() );
if ( STATEMENT_RESULT_TIMINGS.availableIn( serverVersion ) )
{
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), greaterThanOrEqualTo( 0L ) );
}
else
{
//Not passed through by older versions of the server
assertThat( summary.resultAvailableAfter( TimeUnit.MILLISECONDS ), equalTo( -1L ) );
assertThat( summary.resultConsumedAfter( TimeUnit.MILLISECONDS ), equalTo( -1L ) );
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldNotAllowMoreTransactionsInSessionWhileConnectionClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( false );
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
}
|
#vulnerable code
@Test
public void shouldNotAllowMoreTransactionsInSessionWhileConnectionClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( false );
InternalSession sess = new InternalSession( mock );
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
}
#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 shouldNotAllowNewTxWhileOneIsRunning() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
}
|
#vulnerable code
@Test
public void shouldNotAllowNewTxWhileOneIsRunning() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.beginTransaction();
}
#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 shouldNotPutBackPurgedConnection() throws IOException, InterruptedException, StubServer.ForceKilled
{
// Given
StubServer server = StubServer.start( resource( "not_reuse_connection.script" ), 9001 );
//START servers
StubServer readServer = StubServer.start( resource( "empty.script" ), 9002 );
StubServer writeServer1 = StubServer.start( resource( "dead_server.script" ), 9003 );
StubServer writeServer2 = StubServer.start( resource( "empty.script" ), 9006 );
URI uri = URI.create( "bolt+routing://127.0.0.1:9001" );
RoutingDriver driver = (RoutingDriver) GraphDatabase.driver( uri, config );
//Open both a read and a write session
Session readSession = driver.session( AccessMode.READ );
Session writeSession = driver.session( AccessMode.WRITE );
try
{
writeSession.run( "MATCH (n) RETURN n.name" );
writeSession.close();
fail();
}
catch (SessionExpiredException e)
{
//ignore
}
//We now lost all write servers
assertThat(driver.writeServers(), hasSize( 0 ));
//reacquiring will trow out the current read server at 9002
writeSession = driver.session( AccessMode.WRITE );
assertThat(driver.routingServers(), contains(address( 9004 )));
assertThat(driver.readServers(), contains(address( 9005 )));
assertThat(driver.writeServers(), contains(address( 9006 )));
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
// now we close the read session and the connection should not be put
// back to the pool
Connection connection = ((RoutingNetworkSession) readSession).connection;
assertTrue( connection.isOpen() );
readSession.close();
assertFalse( connection.isOpen() );
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
writeSession.close();
driver.close();
// Finally
assertThat( server.exitStatus(), equalTo( 0 ) );
assertThat( readServer.exitStatus(), equalTo( 0 ) );
assertThat( writeServer1.exitStatus(), equalTo( 0 ) );
assertThat( writeServer2.exitStatus(), equalTo( 0 ) );
}
|
#vulnerable code
@Test
public void shouldNotPutBackPurgedConnection() throws IOException, InterruptedException, StubServer.ForceKilled
{
// Given
StubServer server = StubServer.start( resource( "not_reuse_connection.script" ), 9001 );
//START servers
StubServer readServer = StubServer.start( resource( "empty.script" ), 9002 );
StubServer writeServer1 = StubServer.start( resource( "dead_server.script" ), 9003 );
StubServer writeServer2 = StubServer.start( resource( "empty.script" ), 9006 );
URI uri = URI.create( "bolt+routing://127.0.0.1:9001" );
RoutingDriver driver = (RoutingDriver) GraphDatabase.driver( uri, config );
//Open both a read and a write session
Session readSession = driver.session( AccessMode.READ );
Session writeSession = driver.session( AccessMode.WRITE );
try
{
writeSession.run( "MATCH (n) RETURN n.name" );
writeSession.close();
fail();
}
catch (SessionExpiredException e)
{
//ignore
}
//We now lost all write servers
assertThat(driver.writeServers(), hasSize( 0 ));
//reacquiring will trow out the current read server at 9002
writeSession = driver.session( AccessMode.WRITE );
assertThat(driver.routingServers(), contains(address( 9004 )));
assertThat(driver.readServers(), contains(address( 9005 )));
assertThat(driver.writeServers(), contains(address( 9006 )));
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
// now we close the read session and the connection should not be put
// back to the pool
Connection connection = ((ClusteredNetworkSession) readSession).connection;
assertTrue( connection.isOpen() );
readSession.close();
assertFalse( connection.isOpen() );
assertFalse(driver.connectionPool().hasAddress(address( 9002 ) ));
writeSession.close();
driver.close();
// Finally
assertThat( server.exitStatus(), equalTo( 0 ) );
assertThat( readServer.exitStatus(), equalTo( 0 ) );
assertThat( writeServer1.exitStatus(), equalTo( 0 ) );
assertThat( writeServer2.exitStatus(), equalTo( 0 ) );
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
{
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
{
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
}
}
|
#vulnerable code
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
{
BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) );
for ( Certificate cert : certs )
{
String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );
writer.write( BEGIN_CERT );
writer.newLine();
writer.write( certStr );
writer.newLine();
writer.write( END_CERT );
writer.newLine();
}
writer.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldKnowSessionIsClosed() throws Throwable
{
// Given
try( Driver driver = GraphDatabase.driver( neo4j.address() ) )
{
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
}
|
#vulnerable code
@Test
public void shouldKnowSessionIsClosed() throws Throwable
{
// Given
Driver driver = GraphDatabase.driver( neo4j.address() );
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldNotCloseSessionFactoryMultipleTimes()
{
SessionFactory sessionFactory = sessionFactoryMock();
InternalDriver driver = newDriver( sessionFactory );
assertNull( await( driver.closeAsync() ) );
assertNull( await( driver.closeAsync() ) );
assertNull( await( driver.closeAsync() ) );
verify( sessionFactory ).close();
}
|
#vulnerable code
@Test
public void shouldNotCloseSessionFactoryMultipleTimes()
{
SessionFactory sessionFactory = sessionFactoryMock();
InternalDriver driver = newDriver( sessionFactory );
assertNull( getBlocking( driver.closeAsync() ) );
assertNull( getBlocking( driver.closeAsync() ) );
assertNull( getBlocking( driver.closeAsync() ) );
verify( sessionFactory ).close();
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldExplainConnectionError() throws Throwable
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Unable to connect to 'localhost' on port 7777, ensure the database is running " +
"and that there is a working network connection to it." );
// When
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:7777" );
Session session = driver.session()) {}
}
|
#vulnerable code
@Test
public void shouldExplainConnectionError() throws Throwable
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Unable to connect to 'localhost' on port 7777, ensure the database is running " +
"and that there is a working network connection to it." );
// When
try ( Driver driver = GraphDatabase.driver( "bolt://localhost:7777" ) )
{
driver.session();
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.