auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void fire( final String stepName, final List<FiringGroup> firingGroups, final Collection<Unit> allEnemyUnitsAliveOrWaitingToDie, final Collection<Unit> allFriendlyUnitsAliveOrWaitingToDie, final boolean defender, final ReturnFire returnFire, final String text) { final GamePlayer firingPlayer = defender ? this.defender : attacker; final GamePlayer hitPlayer = !defender ? this.defender : attacker; for (final FiringGroup firingGroup : firingGroups) { stack.push( new Fire( firingGroup.getValidTargets(), returnFire, firingPlayer, hitPlayer, firingGroup.getFiringGroup(), stepName, text, this, defender, dependentUnits, headless, battleSite, territoryEffects, allEnemyUnitsAliveOrWaitingToDie, allFriendlyUnitsAliveOrWaitingToDie)); } }

Target:
private void fire( final String stepName, final List<FiringGroup> firingGroups, final Collection<Unit> allEnemyUnitsAliveOrWaitingToDie, final Collection<Unit> allFriendlyUnitsAliveOrWaitingToDie, final boolean defender, final ReturnFire returnFire, final String text) { final GamePlayer firingPlayer = defender ? this.defender : attacker; final GamePlayer hitPlayer = !defender ? this.defender : attacker; for (final FiringGroup firingGroup : firingGroups) { stack.push( new Fire( firingGroup, returnFire, firingPlayer, hitPlayer, stepName, text, this, defender, dependentUnits, headless, battleSite, territoryEffects, allEnemyUnitsAliveOrWaitingToDie, allFriendlyUnitsAliveOrWaitingToDie)); } }
Source:
protected void wrapUpArguments(ArgumentListBuilder args, String normalizedTarget, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { args.addTokenized(additionalProperties); ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix()); argsBuilder.append("sonar.jdbc.driver", getInstallation().getDatabaseDriver()); argsBuilder.append("sonar.jdbc.url", getInstallation().getDatabaseUrl()); argsBuilder.appendMasked("sonar.jdbc.username", getInstallation().getDatabaseLogin()); argsBuilder.appendMasked("sonar.jdbc.password", getInstallation().getDatabasePassword()); argsBuilder.append("sonar.host.url", getInstallation().getServerUrl()); argsBuilder.append("sonar.branch", publisher.getBranch()); String sonarLanguage = publisher.getLanguage(); if (StringUtils.isNotBlank(sonarLanguage)) { argsBuilder.append("sonar.language", sonarLanguage); } if (StringUtils.isNotBlank(getInstallation().getSonarLogin())) { argsBuilder.appendMasked("sonar.login", getInstallation().getSonarLogin()); argsBuilder.appendMasked("sonar.password", getInstallation().getSonarPassword()); } if (build instanceof MavenModuleSetBuild) { FilePath localRepo = locaRepository.locate((MavenModuleSetBuild) build); if (localRepo != null) { args.add("-Dmaven.repo.local=" + localRepo.getRemote()); } } else if (locaRepository instanceof PerJobLocalRepositoryLocator) { FilePath workspace = build.getWorkspace(); if (workspace != null) { args.add("-Dmaven.repo.local=" + workspace.child(".repository")); } } }

Target:
protected void wrapUpArguments(ArgumentListBuilder args, String normalizedTarget, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { args.addTokenized(additionalProperties); ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix()); argsBuilder.append("sonar.jdbc.driver", getInstallation().getDatabaseDriver()); argsBuilder.append("sonar.jdbc.url", getInstallation().getDatabaseUrl()); argsBuilder.appendMasked("sonar.jdbc.username", getInstallation().getDatabaseLogin()); argsBuilder.appendMasked("sonar.jdbc.password", getInstallation().getDatabasePassword()); argsBuilder.append("sonar.host.url", getInstallation().getServerUrl()); argsBuilder.append("sonar.branch", publisher.getBranch()); argsBuilder.append("sonar.language", publisher.getLanguage()); if (StringUtils.isNotBlank(getInstallation().getSonarLogin())) { argsBuilder.appendMasked("sonar.login", getInstallation().getSonarLogin()); argsBuilder.appendMasked("sonar.password", getInstallation().getSonarPassword()); } if (build instanceof MavenModuleSetBuild) { FilePath localRepo = locaRepository.locate((MavenModuleSetBuild) build); if (localRepo != null) { args.add("-Dmaven.repo.local=" + localRepo.getRemote()); } } else if (locaRepository instanceof PerJobLocalRepositoryLocator) { FilePath workspace = build.getWorkspace(); if (workspace != null) { args.add("-Dmaven.repo.local=" + workspace.child(".repository")); } } }
Source:
public Pod create(Pod pod) throws InfrastructureException { putLabel(pod, CHE_WORKSPACE_ID_LABEL, workspaceId); ObjectMeta metadata = pod.getMetadata(); PodSpec podSpec = pod.getSpec(); podSpec.setRestartPolicy("Always"); try { Deployment deployment = clientFactory .create(workspaceId) .extensions() .deployments() .createNew() .withMetadata(metadata) .withNewSpec() .withReplicas(1) .withNewTemplate() .withMetadata(metadata) .withSpec(podSpec) .endTemplate() .endSpec() .done(); return awaitAndGetPod(deployment); } catch (KubernetesClientException e) { throw new KubernetesInfrastructureException(e); } }

Target:
public Pod create(Pod pod) throws InfrastructureException { putLabel(pod, CHE_WORKSPACE_ID_LABEL, workspaceId); try { return clientFactory.create(workspaceId).pods().inNamespace(namespace).create(pod); } catch (KubernetesClientException e) { throw new KubernetesInfrastructureException(e); } }
Source:
public boolean isParentOf(Beacon other) { return FastByteComparisons.equal(this.getHash(), other.getHash()); }

Target:
public boolean isParentOf(Beacon other) { return FastByteComparisons.equal(this.getParentHash(), other.getHash()); }
Source:
private void checkText(Node textNode) { NodeList childNodes = textNode.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); if (childNode.getNodeType() != Node.TEXT_NODE) { continue; } String text = childNode.getNodeValue(); while (StringUtils.contains(text, POM_PROPERTY_PREFIX)) { String property = extractPropertyName(text); reportIssue(childNode, "Replace \"pom." + property + "\" with \"project." + property + "\"."); text = skipFirstProperty(text); } } }

Target:
private void checkText(Node textNode) { asList(textNode.getChildNodes()).stream() .filter(node -> node.getNodeType() == Node.TEXT_NODE) .forEach(node -> { String text = node.getNodeValue(); while (StringUtils.contains(text, POM_PROPERTY_PREFIX)) { String property = extractPropertyName(text); reportIssue(node, "Replace \"pom." + property + "\" with \"project." + property + "\"."); text = skipFirstProperty(text); } }); }
Source:
void warnOnPrivateHandlers(){ ModelVerifier verifier = new ModelVerifier(project); Queue<SubstituteLoggingEvent> loggedMessages = redirectLogging(); CommandHandlers model = CommandHandlers .newBuilder() .addCommandHandlingTypes(InvalidRestoreAggregate.class.getName()) .build(); verifier.verify(model); assertEquals(1, loggedMessages.size()); }

Target:
void warnOnPrivateHandlers(){ ModelVerifier verifier = new ModelVerifier(project); Queue<SubstituteLoggingEvent> loggedMessages = redirectLogging(); CommandHandlers model = CommandHandlers .newBuilder() .addCommandHandlingTypes(InvalidRestoreAggregate.class.getName()) .build(); verifier.verify(model); assertEquals(1, loggedMessages.size()); SubstituteLoggingEvent event = loggedMessages.poll(); assertEquals(event.getLevel(), Level.WARN); }
Source:
public void install() { log.info("Waiting till the database is up"); entity.getConfig(Drupal.DATABASE_UP); log.info("Database is up and running"); String version = getVersion(); List<String> commands = new LinkedList<String>(); commands.add(CommonCommands.INSTALL_TAR); commands.add(CommonCommands.INSTALL_WGET); commands.add("apt-get update"); commands.add(installPackage(of("yum", "httpd", "apt", "apache2"), null)); commands.add(installPackage(of("yum", "php", "apt", "php5"), null)); commands.add(installPackage(of("yum", "php-mysql", "apt", "php5-mysql"), null)); commands.add(installPackage(of("yum", "php-gd", "apt", "php5-gd"), null)); commands.add(installPackage(of("apt", "libapache2-mod-php5"), null)); commands.add("/etc/init.d/apache2 stop"); commands.add(format("wget <LINK_0>", version)); commands.add(format("tar -xvf drupal-%s.tar.gz", version)); commands.add(format("cp -R drupal-%s/* /var/www/", version)); commands.add("cd /var/www"); commands.add("cp sites/default/default.settings.php sites/default/settings.php"); commands.add("chmod o+w sites/default/settings.php"); commands.add("chmod o+w sites/default"); commands.add("chown -R www-data.www-data /var/www"); commands.add("rm index.html"); newScript(INSTALLING). failOnNonZeroResultCode(). body.append(commands).execute(); }

Target:
public void install() { log.info("Waiting till the database is up"); entity.getConfig(Drupal.DATABASE_UP); log.info("Database is up and running"); String version = getVersion(); List<String> commands = new LinkedList<String>(); commands.add(CommonCommands.INSTALL_TAR); commands.add(CommonCommands.INSTALL_WGET); commands.add(installPackage(of("yum", "httpd", "apt", "apache2"), null)); commands.add(installPackage(of("yum", "php", "apt", "php5"), null)); commands.add(installPackage(of("yum", "php-mysql", "apt", "php5-mysql"), null)); commands.add(installPackage(of("yum", "php-gd", "apt", "php5-gd"), null)); commands.add(installPackage(of("apt", "libapache2-mod-php5"), null)); commands.add("/etc/init.d/apache2 stop"); commands.add(format("wget <LINK_0>", version)); commands.add(format("tar -xvf drupal-%s.tar.gz", version)); commands.add(format("cp -R drupal-%s/* /var/www/", version)); commands.add("cd /var/www"); commands.add("cp sites/default/default.settings.php sites/default/settings.php"); commands.add("mkdir -p /var/www/sites/default/files"); commands.add("chmod o+w sites/default/settings.php"); commands.add("chmod o+w sites/default"); commands.add("chown -R www-data.www-data /var/www"); commands.add("chgrp -R www-data /var/www/sites/default/files"); commands.add("chmod -R g+u /var/www/sites/default/files"); commands.add("rm index.html"); newScript(INSTALLING). failOnNonZeroResultCode(). body.append(commands).execute(); }
Source:
protected void setPatterns() { String[] patterns = currentPattern.split(";"); this.validPatterns = new StringMatcher[patterns.length]; int i = 0; for (String pattern : patterns) { if (!strict) { pattern = "*" + pattern.trim() + "*"; } validPatterns[i++] = new StringMatcher(pattern, ignoreCase, false); } clearCache(); }

Target:
protected void setPatterns() { String[] patterns = currentPattern.split(SEMI_COLON); this.validPatterns = new StringMatcher[patterns.length]; int i = 0; for (String pattern : patterns) { if (!strict) { pattern = ASTERISK + pattern.trim() + ASTERISK; } validPatterns[i++] = new StringMatcher(pattern, ignoreCase, false); } clearCache(); }
Source:
public JacksonSearchSerializer build() { return (objectMapper == null) ? new JacksonSearchSerializer(new ObjectMapper()) : new JacksonSearchSerializer(objectMapper); }

Target:
public JacksonJsonSerializer build() { ObjectMapper mapper = objectMapper == null ? new ObjectMapper() : objectMapper; if (options != null && options.getJsonInclusion() == JsonInclusion.ALWAYS) { mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); } return new JacksonJsonSerializer(mapper); }
Source:
public void testImportBreakpoints() throws Exception { createProject(); contextManager.activateContext("contextWithBreakpoints"); IInteractionContext testContext = contextManager.getActiveContext(); List<IBreakpoint> breakpoints = BreakpointsContextUtil.importBreakpoints(testContext); assertTrue(breakpoints.size() == 2); assertTrue(breakpoints.get(0) instanceof JavaLineBreakpoint); assertTrue(breakpoints.get(1) instanceof JavaLineBreakpoint); }

Target:
public void testImportBreakpoints() throws Exception { BreakpointsTestUtil.createProject(); contextManager.activateContext("contextWithBreakpoints"); IInteractionContext testContext = contextManager.getActiveContext(); List<IBreakpoint> breakpoints = BreakpointsContextUtil.importBreakpoints(testContext, null); assertTrue(breakpoints.size() == 2); assertTrue(breakpoints.get(0) instanceof JavaLineBreakpoint); IMarker marker = breakpoints.get(0).getMarker(); assertEquals("test.java", marker.getResource().getName()); assertEquals(11, marker.getAttribute(IMarker.LINE_NUMBER, 0)); assertTrue(breakpoints.get(1) instanceof JavaLineBreakpoint); marker = breakpoints.get(1).getMarker(); assertEquals("test.java", marker.getResource().getName()); assertEquals(10, marker.getAttribute(IMarker.LINE_NUMBER, 0)); }
Source:
boolean isAssignmentValid(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { return (node.getMaxPartition() < 0 || node.getAssignedReplicaCount() < node.getMaxPartition()) && (replica.getResourceMaxPartitionsPerInstance() < 0 || node.getAssignedPartitionsByResource(replica.getResourceName()).size() < replica .getResourceMaxPartitionsPerInstance()); }

Target:
boolean isAssignmentValid(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { boolean exceedMaxPartitionLimit = node.getMaxPartition() < 0 || node.getAssignedReplicaCount() < node.getMaxPartition(); boolean exceedResourceMaxPartitionLimit = replica.getResourceMaxPartitionsPerInstance() < 0 || node.getAssignedPartitionsByResource(replica.getResourceName()).size() < replica .getResourceMaxPartitionsPerInstance(); return exceedMaxPartitionLimit && exceedResourceMaxPartitionLimit; }
Source:
public List<String> getVanishedPlayers() { List<String> list = new ArrayList<>(); list.addAll(vanishedPlayers); return list; }

Target:
public List<String> getVanishedPlayers() { return Collections.unmodifiableList(new ArrayList<>(vanishedPlayers)); }
Source:
private void setEnrichResultToBody(MessageContext synapseContext, SynapseJsonPath synapseJsonPath, Object sourceNode) { String expression = synapseJsonPath.getJsonPath().getPath(); if (expression.endsWith(".")) { expression = expression.substring(0, expression.length() - 1); } boolean isRootPath = "$".equals(expression); org.apache.axis2.context.MessageContext context = ((Axis2MessageContext) synapseContext) .getAxis2MessageContext(); assert JsonUtil.hasAJsonPayload(context) : "Message Context does not contain a JSON payload"; String jsonString = JsonUtil.jsonPayloadToString(context); String newJsonString = ""; if (action.equalsIgnoreCase(ACTION_REPLACE)) { if (isRootPath) { log.error("Acting replace is not supported for root path in type custom. " + "Please use type body action replace instead"); } else { newJsonString = JsonPath.parse(jsonString).set(expression, sourceNode).jsonString(); } } else if (action.equalsIgnoreCase(ACTION_ADD_CHILD)) { newJsonString = getNewJSONString(sourceNode, expression, jsonString, isRootPath); } else if (action.equalsIgnoreCase(ACTION_ADD_SIBLING)) { log.error("Action sibling is not supported. Please use child action instead"); } else { log.error("Invalid action set: " + action); } try { if (!newJsonString.trim().isEmpty()) { JsonUtil.getNewJsonPayload(context, newJsonString, true, true); } } catch (AxisFault axisFault) { log.error("Error occurred while setting new JSON payload", axisFault); } }

Target:
private void setEnrichResultToBody(MessageContext synapseContext, SynapseJsonPath synapseJsonPath, Object sourceNode) { String expression = synapseJsonPath.getJsonPath().getPath(); if (expression.endsWith(".")) { expression = expression.substring(0, expression.length() - 1); } boolean isRootPath = "$".equals(expression); org.apache.axis2.context.MessageContext context = ((Axis2MessageContext) synapseContext) .getAxis2MessageContext(); assert JsonUtil.hasAJsonPayload(context) : "Message Context does not contain a JSON payload"; String jsonString = JsonUtil.jsonPayloadToString(context); String newJsonString = ""; if (action.equalsIgnoreCase(ACTION_REPLACE)) { newJsonString = JsonPath.parse(jsonString).set(expression, sourceNode).jsonString(); } else if (action.equalsIgnoreCase(ACTION_ADD_CHILD)) { newJsonString = getNewJSONString(sourceNode, expression, jsonString, isRootPath); } else if (action.equalsIgnoreCase(ACTION_ADD_SIBLING)) { log.error("Action sibling is not supported. Please use child action instead"); } else { log.error("Invalid action set: " + action); } try { if (!newJsonString.trim().isEmpty()) { JsonUtil.getNewJsonPayload(context, newJsonString, true, true); } } catch (AxisFault axisFault) { log.error("Error occurred while setting new JSON payload", axisFault); } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Boolean isDarkTheme = SalesforceSDKManager.getInstance().isDarkTheme(getActivity()); setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, (isDarkTheme ? R.style.SalesforceSDK_Dialog_Dark : R.style.SalesforceSDK_Dialog)); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean isDarkTheme = SalesforceSDKManager.getInstance().isDarkTheme(getActivity()); setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, (isDarkTheme ? R.style.SalesforceSDK_Dialog_Dark : R.style.SalesforceSDK_Dialog)); }
Source:
private static LockAndTimestampServices createRawServicesFromTimeLock( AtlasDbConfig config, TimestampStoreInvalidator invalidator, String userAgent) { Preconditions.checkState(config.timelock().isPresent(), "Cannot create raw services from a config without a timelock block!"); TimeLockClientConfig clientConfig = config.timelock().get(); String resolvedClient = OptionalResolver.resolve(clientConfig.client(), config.namespace()); TimeLockClientConfig timeLockClientConfig = TimeLockClientConfigs.copyWithClient(config.timelock().get(), resolvedClient); TimeLockMigrator.create(timeLockClientConfig, invalidator, userAgent).migrate(); return createNamespacedRawRemoteServices(timeLockClientConfig, userAgent); }

Target:
private static LockAndTimestampServices createRawServicesFromTimeLock( AtlasDbConfig config, TimestampStoreInvalidator invalidator, String userAgent) { Preconditions.checkState(config.timelock().isPresent(), "Cannot create raw services from timelock without a timelock block!"); TimeLockClientConfig clientConfig = config.timelock().get(); String resolvedClient = OptionalResolver.resolve(clientConfig.client(), config.namespace()); TimeLockClientConfig timeLockClientConfig = TimeLockClientConfigs.copyWithClient(config.timelock().get(), resolvedClient); TimeLockMigrator.create(timeLockClientConfig, invalidator, userAgent).migrate(); return createNamespacedRawRemoteServices(timeLockClientConfig, userAgent); }
Source:
public void handleViolation(final Violation violation) { ViolationEntity entity = buildViolationEntity(violation); this.violationRepository.save(entity); this.counterService.increment(VIOLATION_PERSISTED_JPA); this.counterService.decrement(VIOLATION_EVENTBUS_QUEUED); }

Target:
public void handleViolation(final Violation violation) { this.counterService.decrement(VIOLATIONS_EVENTBUS_QUEUED); ViolationEntity entity = buildViolationEntity(violation); this.violationRepository.save(entity); this.counterService.increment(VIOLATIONS_PERSISTED_JPA); }
Source:
public void start() { if (started.compareAndSet(false, true)) { register(); scheduler = Utils.newScheduler(1, false); scheduler.scheduleAtFixedRate(new NettyMetricCollector(), 0, config.nettyMetricsRefreshIntervalSeconds, TimeUnit.SECONDS); logger.trace("Schedule netty metric collector"); } }

Target:
public void start() { if (started.compareAndSet(false, true)) { register(); scheduler = Utils.newScheduler(1, false); scheduler.scheduleAtFixedRate(new NettyMetricCollector(), 0, config.nettyMetricsRefreshIntervalSeconds, TimeUnit.SECONDS); logger.info("Schedule netty metric collector"); } }
Source:
public Long parse(String formattedTime) { try { Period period = hourFormatter.parsePeriod(formattedTime); return LocalDateTime.now().minusHours(period.getHours()).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } catch (IllegalArgumentException e) { logger.info("Could not parse period. {}", e.getMessage()); } try { return dateFormat.parse(formattedTime).toInstant().toEpochMilli(); } catch (ParseException e) { logger.info("Could not parse date. {}", e.getMessage()); } throw new IllegalArgumentException( "Could not parse given time. Available formats: period in hours (ex. \"-7h\") or date time with pattern " + dateTimeFormatPattern ); }

Target:
public Long parse(String formattedTime) { try { Period period = hourFormatter.parsePeriod(formattedTime); return LocalDateTime.now().minusHours(period.getHours()).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } catch (IllegalArgumentException e) { logger.info("Could not parse period. {}", e.getMessage()); } try { return LocalDateTime.parse(formattedTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } catch (DateTimeParseException e) { logger.info("Could not parse date. {}", e.getMessage()); } throw new IllegalArgumentException( "Could not parse given time. Available formats: period in hours (ex. \"-7h\") or ISO local date time" ); }
Source:
public void init(final int size) { this.viewpointsFromPlugin = new HashSet<Viewpoint>(size); this.viewpointsFromWorkspace = new HashSet<Viewpoint>(size); this.resourceSet = new ResourceSetImpl(); crossReferencer = new ECrossReferenceAdapter(); this.resourceSet.eAdapters().add(crossReferencer); try { final IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); } catch (IllegalStateException e) { } initViewpointsFromPlugins(); refreshComponentsFromWorkspace(); }

Target:
public void init(final int size) { this.viewpointsFromPlugin = new HashSet<Viewpoint>(size); this.viewpointsFromWorkspace = new HashSet<Viewpoint>(size); this.resourceSet = new ResourceSetImpl(); crossReferencer = new ECrossReferenceAdapter(); this.resourceSet.eAdapters().add(crossReferencer); IWorkspaceRoot workspaceRoot = EcorePlugin.getWorkspaceRoot(); if (workspaceRoot != null) { workspaceRoot.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); } initViewpointsFromPlugins(); refreshComponentsFromWorkspace(); }
Source:
public SolObject toObj(SolGame game) { Vector2 position = adjustDesiredPosition(game, myPos, mySz); return game.getAsteroidBuilder().build(game, position, myTex, mySz, myAngle, myRotSpd, mySpd, myRemoveController); }

Target:
public SolObject toObj(SolGame game) { adjustDesiredPosition(game); return game.getAsteroidBuilder().build(game, position, tex, size, angle, rotateSpeed, speed, removeController); }
Source:
public void setUp() throws Exception { aGraph = new ClassDiagramGraph(); aRootNodes = (ArrayList<Node>) aGraph.getRootNodes(); aNode = new ClassNode(); aGraph.addNode(aNode, new Point2D.Double()); aNeedsLayout = aGraph.getClass().getSuperclass().getDeclaredField("aNeedsLayout"); aNeedsLayout.setAccessible(true); aNodesToBeRemoved = aGraph.getClass().getSuperclass().getDeclaredField("aNodesToBeRemoved"); aNodesToBeRemoved.setAccessible(true); aDeleteNodeCommand = new DeleteNodeCommand(aGraph, aNode); }

Target:
public void setUp() throws Exception { aGraph = new ClassDiagramGraph(); aNode = new ClassNode(); aNodesToBeRemoved = aGraph.getClass().getSuperclass().getDeclaredField("aNodesToBeRemoved"); aNodesToBeRemoved.setAccessible(true); aDeleteNodeCommand = new DeleteNodeCommand(aGraph, aNode); }
Source:
protected boolean set(Entity dataHolder, Set<String> value) { for(String oldTag : dataHolder.getTags()) { dataHolder.removeTag(oldTag); } for(String newTag : value) { if(!dataHolder.addTag(newTag)) { return false; } } return true; }

Target:
protected boolean set(Entity dataHolder, Set<String> value) { for (String oldTag : dataHolder.getTags()) { dataHolder.removeTag(oldTag); } List<String> added = Lists.newArrayList(); for (String newTag : value) { if (!dataHolder.addTag(newTag)) { for (String tag : added) { dataHolder.removeTag(tag); } return false; } added.add(newTag); } return true; }
Source:
public void testGetDRTableNamePartitionColumnMapping() throws Exception { String schema = "CREATE TABLE A (C1 INTEGER NOT NULL, C2 TIMESTAMP NOT NULL); PARTITION TABLE A ON COLUMN C1;\n" + "CREATE TABLE B (C1 BIGINT NOT NULL, C2 SMALLINT NOT NULL); PARTITION TABLE B ON COLUMN C1;\n" + "CREATE TABLE C (C1 TINYINT NOT NULL, C2 VARCHAR(3) NOT NULL); PARTITION TABLE C ON COLUMN C1;\n" + "DR TABLE B;\n"; String testDir = BuildDirectoryUtils.getBuildDirectoryPath(); final File file = VoltFile.createTempFile("DRTableNamePartitionColumnMapping", ".jar", new File(testDir)); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema(schema); builder.compile(file.getPath()); Catalog cat = TestCatalogDiffs.catalogForJar(file.getPath()); file.delete(); Map<String, Integer> mapping = CatalogUtil.getDRTableNamePartitionColumnMapping(cat.getClusters().get("cluster").getDatabases().get("database")); assertEquals(1, mapping.size()); assertEquals(true, mapping.containsKey("B")); assertEquals(0, mapping.get("B").intValue()); }

Target:
public void testGetDRTableNamePartitionColumnMapping() throws Exception { String schema = "CREATE TABLE A (C1 INTEGER NOT NULL, C2 TIMESTAMP NOT NULL); PARTITION TABLE A ON COLUMN C1;\n" + "CREATE TABLE B (C1 BIGINT NOT NULL, C2 SMALLINT NOT NULL); PARTITION TABLE B ON COLUMN C1;\n" + "CREATE TABLE C (C1 TINYINT NOT NULL, C2 VARCHAR(3) NOT NULL);\n" + "DR TABLE B; DR TABLE C;\n"; String testDir = BuildDirectoryUtils.getBuildDirectoryPath(); final File file = VoltFile.createTempFile("DRTableNamePartitionColumnMapping", ".jar", new File(testDir)); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema(schema); builder.compile(file.getPath()); Catalog cat = TestCatalogDiffs.catalogForJar(file.getPath()); file.delete(); Map<String, Integer> mapping = CatalogUtil.getDRTableNamePartitionColumnMapping(cat.getClusters().get("cluster").getDatabases().get("database")); assertEquals(1, mapping.size()); assertEquals(true, mapping.containsKey("B")); assertEquals(0, mapping.get("B").intValue()); }
Source:
public Object adapt( Class<E> clazz, IAdaptingType entity, IResponder nextResponder ) { BackendlessCollection<?> result = null; try { BackendlessCollection<E> list = createListOfType( clazz, entity ); AnonymousObject bodyValue = (AnonymousObject) ((NamedObject) entity).getTypedObject(); ArrayType data = (ArrayType) bodyValue.getProperties().get( "data" ); if( data != null ) { Object[] dataArray = (Object[]) data.getArray(); for( int i = 0; i < dataArray.length; i++ ) { if( ((NamedObject) dataArray[ i ]).getObjectName().contains( GeoCluster.class.getSimpleName() ) ) { ((NamedObject) dataArray[ i ]).setDefaultType( GeoCluster.class ); } else { ((NamedObject) dataArray[ i ]).setDefaultType( clazz ); } } } result = (BackendlessCollection<?>) entity.adapt( list.getClass() ); if( nextResponder != null ) nextResponder.responseHandler( result ); } catch( AdaptingException e ) { Fault fault = new Fault( "Unable to adapt response to BackendlessCollection", e.getMessage() ); if( nextResponder != null ) nextResponder.errorHandler( fault ); } return result; }

Target:
public Object adapt( Class<E> clazz, IAdaptingType entity, IResponder nextResponder ) { BackendlessCollection<?> result = null; try { BackendlessCollection<E> list = createListOfType( clazz ); AnonymousObject bodyValue = (AnonymousObject) ((NamedObject) entity).getTypedObject(); ArrayType data = (ArrayType) bodyValue.getProperties().get( "data" ); if( data != null ) { Object[] dataArray = (Object[]) data.getArray(); for( int i = 0; i < dataArray.length; i++ ) { try { String expectedClassName = clazz.getCanonicalName(); String comingClassName = ((NamedObject) dataArray[ i ]).getObjectName(); ( (NamedObject) dataArray[ i ] ).setDefaultType( Class.forName( expectedClassName.substring( 0, expectedClassName.lastIndexOf( '.' ) ) + comingClassName.substring( comingClassName.lastIndexOf( '.' ) ) ) ); } catch( ClassNotFoundException e ) { ((NamedObject) dataArray[ i ]).setDefaultType( clazz ); } } } result = (BackendlessCollection<?>) entity.adapt( list.getClass() ); if( nextResponder != null ) nextResponder.responseHandler( result ); } catch( AdaptingException e ) { Fault fault = new Fault( "Unable to adapt response to BackendlessCollection", e.getMessage() ); if( nextResponder != null ) nextResponder.errorHandler( fault ); } return result; }
Source:
private GetResponseBodyResponse readResponseBody(String requestId) throws IOException, JsonRpcException { GetResponseBodyResponse response = new GetResponseBodyResponse(); ResponseBodyData bodyData; try { bodyData = mResponseBodyFileManager.readFile(requestId); } catch (OutOfMemoryError e) { throw new JsonRpcException(new JsonRpcError(JsonRpcError.ErrorCode.PARSER_ERROR, e.toString(), null )); } response.body = bodyData.data; response.base64Encoded = bodyData.base64Encoded; return response; }

Target:
private GetResponseBodyResponse readResponseBody(String requestId) throws IOException, JsonRpcException { GetResponseBodyResponse response = new GetResponseBodyResponse(); ResponseBodyData bodyData; try { bodyData = mResponseBodyFileManager.readFile(requestId); } catch (OutOfMemoryError e) { throw new JsonRpcException(new JsonRpcError(JsonRpcError.ErrorCode.INTERNAL_ERROR, e.toString(), null )); } response.body = bodyData.data; response.base64Encoded = bodyData.base64Encoded; return response; }
Source:
public MaskValidatorTest(String mask, boolean isNetmaskValidFormat, boolean isMaskValid, boolean isPrefixValid) { this.mask = mask; this.isNetmaskValidFormat = isNetmaskValidFormat; this.isMaskValid = isMaskValid; this.isPrefixValid = isPrefixValid; }

Target:
public MaskValidatorTest(String mask, boolean isNetmaskValidFormat, boolean isMaskValid, boolean isPrefixValid) { this.mask = mask; this.isNetmaskValidFormat = isNetmaskValidFormat; this.isNetmaskValidValue = isMaskValid; this.isPrefixValid = isPrefixValid; }
Source:
protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); parent.getShell().setText(UIText.CommitDialog_CommitChanges); container = toolkit.createComposite(container); GridDataFactory.fillDefaults().grab(true, true).applyTo(container); toolkit.paintBordersFor(container); GridLayoutFactory.swtDefaults().applyTo(container); final SashForm sashForm= new SashForm(container, SWT.VERTICAL | SWT.FILL); toolkit.adapt(sashForm, true, true); sashForm.setLayoutData(GridDataFactory.fillDefaults().grab(true, true) .create()); createMessageAndPersonArea(sashForm); filesSection = createFileSection(sashForm); sashForm.setWeights(new int[] { 50, 50 }); applyDialogFont(container); container.pack(); commitText.setFocus(); Image titleImage = UIIcons.WIZBAN_CONNECT_REPO.createImage(); UIUtils.hookDisposal(parent, titleImage); setTitleImage(titleImage); setTitle(UIText.CommitDialog_Title); setMessage(UIText.CommitDialog_Message, IMessageProvider.INFORMATION); filesViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { updateMessage(); } }); updateFileSectionText(); return container; }

Target:
protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); parent.getShell().setText(UIText.CommitDialog_CommitChanges); container = toolkit.createComposite(container); GridDataFactory.fillDefaults().grab(true, true).applyTo(container); toolkit.paintBordersFor(container); GridLayoutFactory.swtDefaults().applyTo(container); final SashForm sashForm= new SashForm(container, SWT.VERTICAL | SWT.FILL); toolkit.adapt(sashForm, true, true); sashForm.setLayoutData(GridDataFactory.fillDefaults().grab(true, true) .create()); createMessageAndPersonArea(sashForm); filesSection = createFileSection(sashForm); sashForm.setWeights(new int[] { 50, 50 }); applyDialogFont(container); container.pack(); commitText.setFocus(); Image titleImage = UIIcons.WIZBAN_CONNECT_REPO.createImage(); UIUtils.hookDisposal(parent, titleImage); setTitleImage(titleImage); setTitle(UIText.CommitDialog_Title); if (ignoreErrors != null) { setMessage(UIText.CommitDialog_MessageErrors, IMessageProvider.WARNING); } else { setMessage(UIText.CommitDialog_Message, IMessageProvider.INFORMATION); } filesViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { updateMessage(); } }); updateFileSectionText(); return container; }
Source:
public WorkloadClock getClock() { if (taskConfig.users != null) { return new UserClock(taskConfig, tickInterval, shutdown); } else{ if (taskConfig.tps != null){ TpsClockConfiguration tpsClockConfiguration = new TpsClockConfiguration(); tpsClockConfiguration.setTickInterval(tickInterval); tpsClockConfiguration.setTps(taskConfig.tps.value); return tpsClockConfiguration.getClock(); }else { if (taskConfig.virtualUser != null){ VirtualUsersClockConfiguration conf = new VirtualUsersClockConfiguration(); conf.setTickInterval(taskConfig.virtualUser.tickInterval); conf.setUsers(taskConfig.virtualUser.count); return conf.getClock(); }else{ return new ExactInvocationsClock(taskConfig.invocation.exactcount, taskConfig.invocation.threads, taskConfig.delay); } } } }

Target:
public WorkloadClock getClock() { if (taskConfig.users != null) { return new UserClock(taskConfig, tickInterval, shutdown); }else if (taskConfig.tps != null){ TpsClockConfiguration tpsClockConfiguration = new TpsClockConfiguration(); tpsClockConfiguration.setTickInterval(tickInterval); tpsClockConfiguration.setTps(taskConfig.tps.value); return tpsClockConfiguration.getClock(); }else if (taskConfig.virtualUser != null){ VirtualUsersClockConfiguration conf = new VirtualUsersClockConfiguration(); conf.setTickInterval(taskConfig.virtualUser.tickInterval); conf.setUsers(taskConfig.virtualUser.count); return conf.getClock(); }else if (taskConfig.invocation != null){ return new ExactInvocationsClock(taskConfig.invocation.exactcount, taskConfig.invocation.threads, taskConfig.delay); }else return null; }
Source:
public void shouldNotRewriteExistingLibraryIfThereAreNoChanges() throws Exception{ SQLiteLibraryLoader.load(); File extractedPath = SQLiteLibraryLoader.getNativeLibraryPath(); assertThat(extractedPath).exists(); long time = extractedPath.lastModified(); Thread.sleep(2); SQLiteLibraryLoader.mustReload(); SQLiteLibraryLoader.load(); extractedPath = SQLiteLibraryLoader.getNativeLibraryPath(); assertThat(extractedPath.lastModified()).isEqualTo(time); }

Target:
public void shouldNotRewriteExistingLibraryIfThereAreNoChanges() throws Exception{ loader.doLoad(); File extractedPath = loader.getNativeLibraryPath(); assertThat(extractedPath).exists(); final long resetTime = 1234L; assertThat(extractedPath.setLastModified(resetTime)).describedAs("Cannot reset modification date").isTrue(); long time = extractedPath.lastModified(); assertThat(time).isLessThanOrEqualTo(resetTime); loader.mustReload(); loader.doLoad(); extractedPath = loader.getNativeLibraryPath(); assertThat(extractedPath.lastModified()).isEqualTo(time); }
Source:
private boolean isInForeground() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ActivityManager.RunningAppProcessInfo info = new ActivityManager.RunningAppProcessInfo(); ActivityManager.getMyMemoryState(info); return info.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE; } else { return true; } }

Target:
private boolean isInForeground() { ActivityManager.RunningAppProcessInfo info = getProcessInfo(); if (info != null) { return info.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE; } else { return true; } }
Source:
private double calculateGcNormCoverage(final double meanReadsPerWindow, final int[] readsByGc, final int start, final int end) { int windowsTotal = 0; double sum = 0.0; for (int i = start; i <= end; i++) { if (windowsByGc[i] != 0) { final double norm = ((double) readsByGc[i] / windowsByGc[i]) / meanReadsPerWindow; sum = sum + (norm*windowsByGc[i]); windowsTotal = windowsTotal + windowsByGc[i]; } } if(windowsTotal == 0) { return 0.0; } else { return (sum / (double) windowsTotal); } }

Target:
private double calculateGcNormCoverage(final double meanReadsPerWindow, final int[] readsByGc, final int start, final int end) { int windowsTotal = 0; double sum = 0.0; for (int i = start; i <= end; i++) { if (windowsByGc[i] != 0) { sum += (double) readsByGc[i]; windowsTotal += windowsByGc[i]; } } if (windowsTotal == 0) { return 0.0; } else { return (sum / (windowsTotal*meanReadsPerWindow)); } }
Source:
private String chooseImageSource(String thumbUrl, Uri localUri) { String imageSource = thumbUrl; if (TextUtils.isEmpty(imageSource)) { imageSource = localUri != null ? localUri.toString() : null; } return imageSource; }

Target:
private String chooseImageSource(String thumbUrl, Uri localUri) { return !TextUtils.isEmpty(thumbUrl) ? thumbUrl : localUri != null ? localUri.toString() : null; }
Source:
public static void main(String[] args) { try { new StartMain(args).go(); System.exit(0); } catch (Throwable t) { StreamSupport.stream(exceptionHandlerLoader.spliterator(), false) .filter(eh -> eh.supports(t)) .findFirst() .orElse(new DefaultExceptionHandler()) .handle(t); System.exit(1); } }

Target:
public static void main(String[] args) { try { new StartMain(args).go(); } catch (Throwable t) { StreamSupport.stream(exceptionHandlerLoader.spliterator(), false) .filter(eh -> eh.supports(t)) .findFirst() .orElse(new DefaultExceptionHandler()) .handle(t); System.exit(1); } }
Source:
public void testTopologyWorkerCpu() throws Exception { double result = MesosCommon.topologyWorkerCpu(conf, info); double expectedResult = MesosCommon.DEFAULT_WORKER_CPU; assertEquals(result, expectedResult, 0.001); double cpuConfig = MesosCommon.MESOS_MIN_CPU; cpuConfig -= 0.001; conf.put(MesosCommon.WORKER_CPU_CONF, cpuConfig); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = MesosCommon.DEFAULT_WORKER_CPU; assertEquals(result, expectedResult, 0.0001); conf.put(MesosCommon.WORKER_CPU_CONF, 1.5); info = new TopologyDetails("t2", conf, new StormTopology(), 2); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = 1.5; assertEquals(result, expectedResult, 0.001); conf = new HashMap<>(); conf.put(MesosCommon.WORKER_CPU_CONF, "2"); info = new TopologyDetails("t3", conf, new StormTopology(), 1); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = 1; assertEquals(result, expectedResult, 0.001); Map nimbusConf = new HashMap<>(); nimbusConf.put(MesosCommon.WORKER_CPU_CONF, 2); conf = new HashMap<>(); conf.put(MesosCommon.WORKER_CPU_CONF, 1.5); info = new TopologyDetails("t4", conf, new StormTopology(), 1); result = MesosCommon.topologyWorkerCpu(nimbusConf, info); expectedResult = 1.5; assertEquals(result, expectedResult, 0.001); }

Target:
public void testTopologyWorkerCpu() throws Exception { double result = MesosCommon.topologyWorkerCpu(conf, info); double expectedResult = MesosCommon.DEFAULT_WORKER_CPU; assertEquals(result, expectedResult, DELTA); double cpuConfig = MesosCommon.MESOS_MIN_CPU; cpuConfig -= 0.001; conf.put(MesosCommon.WORKER_CPU_CONF, cpuConfig); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = MesosCommon.DEFAULT_WORKER_CPU; assertEquals(result, expectedResult, DELTA); conf.put(MesosCommon.WORKER_CPU_CONF, null); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = MesosCommon.DEFAULT_WORKER_CPU; assertEquals(result, expectedResult, DELTA); conf.put(MesosCommon.WORKER_CPU_CONF, 1.5); info = new TopologyDetails("t2", conf, new StormTopology(), 2); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = 1.5; assertEquals(result, expectedResult, DELTA); conf = new HashMap<>(); conf.put(MesosCommon.WORKER_CPU_CONF, "2"); info = new TopologyDetails("t3", conf, new StormTopology(), 1); result = MesosCommon.topologyWorkerCpu(conf, info); expectedResult = 1; assertEquals(result, expectedResult, DELTA); Map nimbusConf = new HashMap<>(); nimbusConf.put(MesosCommon.WORKER_CPU_CONF, 2); conf = new HashMap<>(); conf.put(MesosCommon.WORKER_CPU_CONF, 1.5); info = new TopologyDetails("t4", conf, new StormTopology(), 1); result = MesosCommon.topologyWorkerCpu(nimbusConf, info); expectedResult = 1.5; assertEquals(result, expectedResult, DELTA); }
Source:
public Version nextVersion() { Version result = event.context() .getVersion(); return result; }

Target:
protected Version nextVersion() { Version result = event.context() .getVersion(); return result; }
Source:
public boolean validate(Source xml, Source xsd) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsd); Validator validator = schema.newValidator(); String language = UserContext.getCurrentUser().getLang(); Locale locale = Strings.areEqual(language, "en") ? Locale.ROOT : new Locale(language); validator.setProperty("<LINK_0>", locale); XMLValidatorErrorHandler errorHandler = new XMLValidatorErrorHandler(process); validator.setErrorHandler(errorHandler); try { validator.validate(xml); } catch (SAXParseException | IOException e) { Exceptions.ignore(e); } return !errorHandler.errorOccurred(); }

Target:
public boolean validate(Source xml, Source xsd) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(xsd); Validator validator = schema.newValidator(); String language = UserContext.getCurrentUser().getLang(); Locale locale = Strings.areEqual(language, "en") ? Locale.ROOT : new Locale(language); validator.setProperty("<LINK_0>", locale); XMLValidatorErrorHandler errorHandler = new XMLValidatorErrorHandler(process); validator.setErrorHandler(errorHandler); try { validator.validate(xml); } catch (SAXParseException e) { Exceptions.ignore(e); } catch (IOException e) { process.log(ProcessLog.error().withMessage(e.getMessage())); return false; } return !errorHandler.errorOccurred(); }
Source:
private final void fireParameterTypeChanged(final ParameterTypeEvent event) { if (event == null) { throw new NullPointerException( "Cannot send a null event to listeners."); } if (!isListenerAttached()) { return; } final Object[] listeners = getListeners(); for (Object listener2 : listeners) { final IParameterTypeListener listener = (IParameterTypeListener) listener2; listener.parameterTypeChanged(event); } }

Target:
private final void fireParameterTypeChanged(final ParameterTypeEvent event) { if (event == null) { throw new NullPointerException( "Cannot send a null event to listeners."); } if (!isListenerAttached()) { return; } final Object[] listeners = getListeners(); for (Object listener : listeners) { final IParameterTypeListener parameterTypeListener = (IParameterTypeListener) listener; parameterTypeListener.parameterTypeChanged(event); } }
Source:
public ViewBinder(@NonNull final RepositoriesView view, @NonNull final RepositoriesViewModel viewModel) { this.view = view; this.viewModel = viewModel; }

Target:
public ViewBinder(@NonNull final RepositoriesView view, @NonNull final RepositoriesViewModel viewModel) { Preconditions.checkNotNull(view, "View cannot be null."); Preconditions.checkNotNull(viewModel, "ViewModel cannot be null."); this.view = view; this.viewModel = viewModel; }
Source:
public Quantity(double value) { this(value, UNKNOWN_UNITS); }

Target:
public Quantity(double value) { this.value = value; }
Source:
protected void map(AvroKey<DocumentText> key, NullWritable value, Context context) throws IOException, InterruptedException { DocumentText nlm = key.datum(); if (!StringUtils.isBlank(nlm.getText())) { final ExtractedDocumentMetadata.Builder output = ExtractedDocumentMetadata.newBuilder(); output.setId(nlm.getId()); try { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setValidating(false); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setFeature("<LINK_2>", false); reader.setFeature("<LINK_0>", false); reader.setFeature("<LINK_1>", false); PmcXmlHandler pmcXmlHandler = new PmcXmlHandler(output); saxParser.parse(new InputSource( new StringReader(nlm.getText().toString())), pmcXmlHandler); mos.write(namedOutputMeta, new AvroKey<ExtractedDocumentMetadata>(output.build())); } catch (ParserConfigurationException e) { Map<CharSequence, CharSequence> auditSupplementaryData = new HashMap<CharSequence, CharSequence>(); auditSupplementaryData.put(FAULT_TEXT, nlm.getText()); mos.write(namedOutputFault, new AvroKey<Fault>(FaultUtils.exceptionToFault(nlm.getId(), e, auditSupplementaryData))); } catch (SAXException e) { Map<CharSequence, CharSequence> auditSupplementaryData = new HashMap<CharSequence, CharSequence>(); auditSupplementaryData.put(FAULT_TEXT, nlm.getText()); mos.write(namedOutputFault, new AvroKey<Fault>(FaultUtils.exceptionToFault(nlm.getId(), e, auditSupplementaryData))); } } }

Target:
protected void map(AvroKey<DocumentText> key, NullWritable value, Context context) throws IOException, InterruptedException { DocumentText nlm = key.datum(); if (!StringUtils.isBlank(nlm.getText())) { final ExtractedDocumentMetadata.Builder output = ExtractedDocumentMetadata.newBuilder(); output.setId(nlm.getId()); try { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setValidating(false); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setFeature("<LINK_2>", false); reader.setFeature("<LINK_0>", false); reader.setFeature("<LINK_1>", false); PmcXmlHandler pmcXmlHandler = new PmcXmlHandler(output); saxParser.parse(new InputSource(new StringReader(nlm.getText().toString())), pmcXmlHandler); mos.write(namedOutputMeta, new AvroKey<ExtractedDocumentMetadata>(output.build())); } catch (ParserConfigurationException e) { handleException(nlm, e); } catch (SAXException e) { handleException(nlm, e); } } }
Source:
static List<BlackboardArtifact> getArtifacts(SleuthkitCase skCase, BlackboardArtifact.Type artifactType, DataSource dataSource, BlackboardAttribute.Type attributeType, SortOrder sortOrder, int maxCount) throws TskCoreException { if (maxCount < 1 && maxCount != -1) { throw new IllegalArgumentException("Invalid maxCount passed to getArtifacts, value must be at greater 0"); } TreeMap<BlackboardAttribute, BlackboardArtifact> sortedMap = new TreeMap<>(new AttributeComparator(sortOrder)); List<BlackboardArtifact> artifactList = skCase.getBlackboard().getArtifacts(artifactType.getTypeID(), dataSource.getId()); for (BlackboardArtifact artifact : artifactList) { BlackboardAttribute attribute = artifact.getAttribute(attributeType); if (attribute != null) { sortedMap.put(attribute, artifact); } } artifactList = new ArrayList<>(); for (BlackboardArtifact artifact : sortedMap.values()) { artifactList.add(artifact); if (maxCount != -1 && artifactList.size() == maxCount - 1) { break; } } return artifactList; }

Target:
static List<BlackboardArtifact> getArtifacts(SleuthkitCase skCase, BlackboardArtifact.Type artifactType, DataSource dataSource, BlackboardAttribute.Type attributeType, SortOrder sortOrder, int maxCount) throws TskCoreException { if (maxCount < 0) { throw new IllegalArgumentException("Invalid maxCount passed to getArtifacts, value must be equal to or greater than 0"); } return createListFromMap(getArtifactMap(skCase, artifactType, dataSource, attributeType, sortOrder), maxCount); }
Source:
private void addAgentsProvidedServers(MachineImpl machine, List<String> agentKeys) throws ServerException { for (String agentKey : agentKeys) { try { AgentImpl agent = new AgentImpl(agentRegistry.getAgent(AgentKeyImpl.parse(agentKey))); for (ServerConf2 conf2 : agent.getServers()) { Map<String, String> properties = conf2.getProperties(); ServerConfImpl conf = new ServerConfImpl(properties.get("ref"), conf2.getPort(), conf2.getProtocol(), properties.get("path")); machine.getConfig().getServers().add(conf); } } catch (AgentException e) { throw new ServerException(e); } } }

Target:
private void addAgentsProvidedServers(MachineImpl machine, List<String> agentKeys) throws ServerException { for (String agentKey : agentKeys) { try { AgentImpl agent = new AgentImpl(agentRegistry.getAgent(AgentKeyImpl.parse(agentKey))); for (Map.Entry<String, ? extends ServerConf2> entry : agent.getServers().entrySet()) { String ref = entry.getKey(); ServerConf2 conf2 = entry.getValue(); ServerConfImpl conf = new ServerConfImpl(ref, conf2.getPort(), conf2.getProtocol(), conf2.getProperties().get("path")); machine.getConfig().getServers().add(conf); } } catch (AgentException e) { throw new ServerException(e); } } }