auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Command.Parameterized createPaginationCommand() { Parameter.Value<ActivePagination> paginationIdParameter = Parameter.builder(ActivePagination.class) .parser(new ActivePaginationParser()) .setSuggestions(new ActivePaginationCompleter()) .setKey("pagination-id") .build(); Command.Parameterized next = Command.builder() .setShortDescription(TextComponent.of("Go to the next page")) .setExecutor((context) -> { context.requireOne(paginationIdParameter).nextPage(); return CommandResult.success(); }).build(); Command.Parameterized prev = Command.builder() .setShortDescription(TextComponent.of("Go to the previous page")) .setExecutor((context) -> { context.requireOne(paginationIdParameter).previousPage(); return CommandResult.success(); }).build(); Parameter.Value<Integer> pageParameter = integerNumber().setKey("page").build(); CommandExecutor pageExecutor = (context) -> { context.requireOne(paginationIdParameter).specificPage(context.requireOne(pageParameter)); return CommandResult.success(); }; Command.Parameterized page = Command.builder() .setShortDescription(TextComponent.of("Go to a specific page")) .parameter(pageParameter) .setExecutor(pageExecutor) .build(); return Command.builder() .parameters(paginationIdParameter, firstOf(pageParameter, subcommand(next, "next", "n"), subcommand(prev, "prev", "p", "previous"), subcommand(page, "page"))) .child(page, "page") .setExecutor(page) .setShortDescription(TextComponent.of("Helper command for paginations occurring")) .build(); }

Target:
public Command.Parameterized createPaginationCommand() { final Parameter.Value<ActivePagination> paginationIdParameter = Parameter.builder(ActivePagination.class) .parser(new ActivePaginationParameter()) .setKey("pagination-id") .build(); final Command.Parameterized next = Command.builder() .setShortDescription(TextComponent.of("Go to the next page")) .setExecutor((context) -> { context.requireOne(paginationIdParameter).nextPage(); return CommandResult.success(); }).build(); final Command.Parameterized prev = Command.builder() .setShortDescription(TextComponent.of("Go to the previous page")) .setExecutor((context) -> { context.requireOne(paginationIdParameter).previousPage(); return CommandResult.success(); }).build(); final Parameter.Value<Integer> pageParameter = Parameter.integerNumber().setKey("page").build(); final CommandExecutor pageExecutor = (context) -> { context.requireOne(paginationIdParameter).specificPage(context.requireOne(pageParameter)); return CommandResult.success(); }; final Command.Parameterized page = Command.builder() .setShortDescription(TextComponent.of("Go to a specific page")) .parameter(pageParameter) .setExecutor(pageExecutor) .build(); return Command.builder() .parameters(paginationIdParameter, Parameter.firstOf(pageParameter, Parameter.subcommand(next, "next", "n"), Parameter.subcommand(prev, "prev", "p", "previous"), Parameter.subcommand(page, "page"))) .child(page, "page") .setExecutor(page) .setShortDescription(TextComponent.of("Helper command for paginations occurring")) .build(); }
Source:
protected void applyProfile(ModelSet modelSet) { String profilePath = selectDiagramKindPage.getProfileURI(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.getResource(URI.createURI(profilePath), true); Profile profile = (Profile) resource.getContents().get(0); Resource myModelUMLResource = UmlUtils.getUmlResource(modelSet); org.eclipse.uml2.uml.Package manipulatedModel = (org.eclipse.uml2.uml.Package) myModelUMLResource.getContents().get(0); Iterator<Profile> iterProfiles = manipulatedModel.getAllAppliedProfiles().iterator(); while (iterProfiles.hasNext()) { Profile modelProfile = iterProfiles.next(); if (modelProfile.getURI().equals(profile.getURI())) { return; } } getCommandStack(modelSet).execute(new ApplyProfileCommand(manipulatedModel, profile, modelSet.getTransactionalEditingDomain())); }

Target:
protected void applyProfile(ModelSet modelSet) { String profilePath = selectDiagramKindPage.getProfileURI(); Resource resource = modelSet.getResource(URI.createURI(profilePath), true); Profile profileToApply = (Profile) resource.getContents().get(0); Resource myModelUMLResource = UmlUtils.getUmlResource(modelSet); org.eclipse.uml2.uml.Package manipulatedModel = (org.eclipse.uml2.uml.Package) myModelUMLResource.getContents().get(0); RecordingCommand applyProfileCommand = new ApplyProfileCommand(manipulatedModel, profileToApply, modelSet.getTransactionalEditingDomain()); getCommandStack(modelSet).execute(applyProfileCommand); }
Source:
public Map<String, ValueResolver<? extends Object>> getParameters() { return new HashMap<>(); }

Target:
public Map<String, ValueResolver<? extends Object>> getParameters() throws ValueResolvingException { HashMap<String, ValueResolver<? extends Object>> parameters = new HashMap<>(); try { addFields(getFields(object.getClass()), parameters); for (ParameterGroupModel parameterGroupModel : parameterizedModel.getParameterGroupModels()) { Optional<ParameterGroupModelProperty> modelProperty = parameterGroupModel.getModelProperty(ParameterGroupModelProperty.class); if (modelProperty.isPresent()) { ParameterGroupModelProperty property = modelProperty.get(); Field container = (Field) property.getDescriptor().getContainer(); Object parameterGroup = getFieldValue(object, container.getName(), reflectionCache); addFields(getFields(parameterGroup.getClass()), parameters); } } } catch (Exception e) { throw new ValueResolvingException("An error occurred trying to obtain the parameters."); } return unmodifiableMap(parameters); }
Source:
public String readXhtmlData(String xhtmlOutput) { InputStream is = new ByteArrayInputStream(xhtmlOutput.getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer lines = new StringBuffer(); try { while ((line = br.readLine()) != null) { lines.append(line); lines.append("\n"); } return lines.toString(); } catch (IOException e) { e.printStackTrace(); } return null; }

Target:
public String readXhtmlData(String xhtmlOutput) { try{ InputStream is = new ByteArrayInputStream(xhtmlOutput.getBytes()); return IOUtils.toString(is); } catch (IOException e) { e.printStackTrace(); } return null; }
Source:
public HandlebarsTemplateRenderer(Handlebars handlebars) { this.handlebars = handlebars; this.templateCache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(new CacheLoader<String, com.github.jknack.handlebars.Template>() { @Override public com.github.jknack.handlebars.Template load(String key) throws Exception { return HandlebarsTemplateRenderer.this.handlebars.compile(key); } }); }

Target:
public HandlebarsTemplateRenderer(Handlebars handlebars) { this.handlebars = handlebars; }
Source:
public Sequence<T> run(final Query<T> query, Map<String, Object> responseContext) { if (BaseQuery.getContextBySegment(query, false)) { final Sequence<T> baseSequence = base.run(query, responseContext); final List<T> results = Sequences.toList(baseSequence, Lists.<T>newArrayList()); return Sequences.simple( Arrays.asList( (T) new Result<BySegmentResultValueClass<T>>( timestamp, new BySegmentResultValueClass<T>( results, segmentIdentifier, Iterables.getOnlyElement( Iterables.getOnlyElement(query.getDataSources()) .getQuerySegmentSpec() .getIntervals() ) ) ) ) ); } return base.run(query, responseContext); }

Target:
public Sequence<T> run(final Query<T> query, Map<String, Object> responseContext) { if (QueryContexts.isBySegment(query)) { final Sequence<T> baseSequence = base.run(query, responseContext); final List<T> results = Sequences.toList(baseSequence, Lists.<T>newArrayList()); return Sequences.simple( Arrays.asList( (T) new Result<BySegmentResultValueClass<T>>( timestamp, new BySegmentResultValueClass<T>( results, segmentIdentifier, Iterables.getOnlyElement( Iterables.getOnlyElement(query.getDataSources()) .getQuerySegmentSpec() .getIntervals() ) ) ) ) ); } return base.run(query, responseContext); }
Source:
public void testHarness() { containsOrganizationTest(nameSpace); siteUrlBaseTest(nameSpace, EXPECTED_SIZE); }

Target:
public void testHarness() { containsOrganizationTest(nameSpace); siteUrlBaseTest(nameSpace, EXPECTED_SIZE); allYearsSummaryTest(nameSpace); fiveYearsSummaryTest(nameSpace); oneYearSummaryTest(nameSpace); }
Source:
public void setUp() throws Exception { brickPosition = 1; valToChange = 30.5f; BrickTestUtils.createProjectAndGetStartScript("changeTransparencyByNBricktest1") .addBrick(new ChangeTransparencyByNBrick()); baseActivityTestRule.launchActivity(null); }

Target:
public void setUp() throws Exception { brickPosition = 1; BrickTestUtils.createProjectAndGetStartScript("changeTransparencyByNBricktest1") .addBrick(new ChangeTransparencyByNBrick()); baseActivityTestRule.launchActivity(null); }
Source:
public void whenCreateSuccessfullyThen201() throws Exception { Mockito .doNothing() .when(eventTypeRepository) .saveEventType(any(EventType.class)); Mockito .doNothing() .when(topicRepository) .createTopic("team.event-name"); postEventType(buildEventType()) .andExpect(status().isCreated()) .andExpect(content().string("")); verify(eventTypeRepository, times(1)).saveEventType(any(EventType.class)); verify(topicRepository, times(1)).createTopic("team.event-name"); }

Target:
public void whenCreateSuccessfullyThen201() throws Exception { final EventType et = buildDefaultEventType(); Mockito.doNothing().when(eventTypeRepository).saveEventType(any(EventType.class)); Mockito.doNothing().when(topicRepository).createTopic(et.getName()); postEventType(et).andExpect(status().isCreated()).andExpect(content().string("")); verify(eventTypeRepository, times(1)).saveEventType(any(EventType.class)); verify(topicRepository, times(1)).createTopic(et.getName()); }
Source:
public void setup() { System.getProperties().put("CREDENTIALS_DIR", "k8s"); }

Target:
public void setup() { System.getProperties().put("CREDENTIALS_DIR", "fs"); }
Source:
public void stop() throws InterruptedException { helper.client.stop(true); helper.server.stop(); helper.deregisterClient(); helper.dispose(); }

Target:
public void stop() throws InterruptedException { helper.client.stop(true); helper.server.stop(); helper.dispose(); }
Source:
public SerialPortRxTx(String port, int baudRate) { super(port, baudRate, DEFAULT_PORT_TIMEOUT); this.logger = LoggerFactory.getLogger(SerialPortRxTx.class); }

Target:
public SerialPortRxTx(String port, int baudRate) { this(port, baudRate, DEFAULT_PORT_TIMEOUT); }
Source:
private void logTaskInfos(List<SqlTask> sqlTasks) { ArrayList<List<String>> taskLogInfoList = new ArrayList<List<String>>(); taskLogInfoList.add(Arrays.asList( "Task ID", "Query ID", "State", "Created Ts", "User Memory", "System Memory", "Input Bytes", "Output Bytes", "Input Row Count", "Output Row Count")); for (SqlTask task : sqlTasks) { TaskInfo taskInfo = task.getTaskInfo(); SqlTaskIoStats taskIOStats = task.getIoStats(); TaskStatus taskStatus = taskInfo.getTaskStatus(); TaskStats taskStats = taskInfo.getStats(); taskLogInfoList.add(Arrays.asList( task.getTaskId().toString(), task.getQueryContext().getQueryId().toString(), taskStatus.getState().toString(), taskStats.getCreateTime().toString(), taskStats.getUserMemoryReservation().toString(), taskStats.getSystemMemoryReservation().toString(), Long.toString(taskIOStats.getInputDataSize().getTotalCount()), Long.toString(taskIOStats.getOutputDataSize().getTotalCount()), Long.toString(taskIOStats.getInputPositions().getTotalCount()), Long.toString(taskIOStats.getOutputPositions().getTotalCount()))); } for (String row : StringTableUtils.getTableStrings(taskLogInfoList)) { log.info(row); } }

Target:
private void logTaskInfos(List<SqlTask> sqlTasks) { ArrayList<List<String>> taskLogInfoList = new ArrayList<>(); taskLogInfoList.add(Arrays.asList( "Task ID", "State", "Created Ts", "User Memory", "System Memory", "Input Bytes", "Output Bytes", "Input Row Count", "Output Row Count")); for (SqlTask task : sqlTasks) { TaskInfo taskInfo = task.getTaskInfo(); SqlTaskIoStats taskIOStats = task.getIoStats(); TaskStatus taskStatus = taskInfo.getTaskStatus(); TaskStats taskStats = taskInfo.getStats(); taskLogInfoList.add(Arrays.asList( task.getTaskId().toString(), taskStatus.getState().toString(), taskStats.getCreateTime().toString(), taskStats.getUserMemoryReservation().toString(), taskStats.getSystemMemoryReservation().toString(), Long.toString(taskIOStats.getInputDataSize().getTotalCount()), Long.toString(taskIOStats.getOutputDataSize().getTotalCount()), Long.toString(taskIOStats.getInputPositions().getTotalCount()), Long.toString(taskIOStats.getOutputPositions().getTotalCount()))); } logInfoTable(taskLogInfoList); }
Source:
private void setZeroAchievements() { AlertDialog.Builder builder=new AlertDialog.Builder(this) .setMessage(getString(R.string.achiev_activity_set_zero_achiev)) .setPositiveButton(getString(R.string.ok), (dialog, which) -> { }); AlertDialog dialog = builder.create(); dialog.show(); imagesUploadedProgressbar.setVisibility(View.INVISIBLE); imageRevertsProgressbar.setVisibility(View.INVISIBLE); imagesUsedByWikiProgressBar.setVisibility(View.INVISIBLE); imageView.setVisibility(View.INVISIBLE); imageByWikiText.setText(R.string.no_image); imageRevertedText.setText(R.string.no_image_reverted); imageUploadedText.setText(R.string.no_image_uploaded); imageView.setVisibility(View.INVISIBLE); }

Target:
private void setZeroAchievements() { AlertDialog.Builder builder=new AlertDialog.Builder(this) .setMessage(getString(R.string.no_achievements_yet)) .setPositiveButton(getString(R.string.ok), (dialog, which) -> { }); AlertDialog dialog = builder.create(); dialog.show(); imagesUploadedProgressbar.setVisibility(View.INVISIBLE); imageRevertsProgressbar.setVisibility(View.INVISIBLE); imagesUsedByWikiProgressBar.setVisibility(View.INVISIBLE); imageView.setVisibility(View.INVISIBLE); imageByWikiText.setText(R.string.no_image); imageRevertedText.setText(R.string.no_image_reverted); imageUploadedText.setText(R.string.no_image_uploaded); imageView.setVisibility(View.INVISIBLE); }
Source:
String generateOutputFileName(@NonNull Entity entity, List<String> queries) { val fname = entity.getFileName(); val extensionPos = fname.toLowerCase().indexOf(".bam"); val left = StringUtils.left(fname, extensionPos); val extension = StringUtils.right(fname, fname.length() - extensionPos); StringBuilder bob = new StringBuilder(); boolean firstValue = true; for (val q : queries) { if (!firstValue) { bob.append("__"); } bob.append(encodeQuery(q)); firstValue = false; } String fullName = String.format("%s.%s%s", left, bob.toString(), extension); return addOutputPath(handleMaxFilenameLength(fullName)); }

Target:
String generateOutputFileName(@NonNull Entity entity, List<String> queries) { val bob = new StringBuilder(); boolean firstValue = true; for (val q : queries) { if (!firstValue) { bob.append("__"); } bob.append(encodeQuery(q)); firstValue = false; } val fullName = handleMaxFilenameLength(injectFileNameModifier(entity, bob.toString()), getExtension(getSourceType(entity))); return addOutputPath(fullName); }
Source:
public FixtureConfiguration<T> registerAggregateFactory(AggregateFactory<T> aggregateFactory) { MultiParameterResolverFactory parameterResolverFactory = MultiParameterResolverFactory.ordered( new SimpleResourceParameterResolverFactory(resources), ClasspathParameterResolverFactory.forClass(aggregateType) ); return registerRepository(new EventSourcingRepository<>( aggregateFactory, eventStore, parameterResolverFactory, NoSnapshotTriggerDefinition.INSTANCE, getRepositoryProvider() )); }

Target:
public FixtureConfiguration<T> registerAggregateFactory(AggregateFactory<T> aggregateFactory) { MultiParameterResolverFactory parameterResolverFactory = MultiParameterResolverFactory.ordered( new SimpleResourceParameterResolverFactory(resources), ClasspathParameterResolverFactory.forClass(aggregateType) ); return registerRepository(new EventSourcingRepository<>(aggregateFactory, eventStore, parameterResolverFactory, handlerDefinition, NoSnapshotTriggerDefinition.INSTANCE, getRepositoryProvider())); }
Source:
public Builder addMemberForValue(String memberName, Object value) { checkArgument(memberName != null, "memberName == null"); checkArgument(value != null, "only constant non-null values are permitted (%s)", memberName); if (value instanceof Class<?>) { return addMember(memberName, "$T.class", value); } if (value instanceof Enum) { return addMember(memberName, "$T.$L", value.getClass(), ((Enum<?>) value).name()); } if (value instanceof String) { return addMember(memberName, "$S", value); } if (value instanceof Float) { return addMember(memberName, "$Lf", value); } if (value instanceof Character) { return addMember(memberName, "'$L'", characterLiteralWithoutSingleQuotes((char) value)); } return addMember(memberName, "$L", value); }

Target:
Builder addMemberForValue(String memberName, Object value) { checkNotNull(memberName, "memberName == null"); checkNotNull(value, "value == null, constant non-null value expected for %s", memberName); if (value instanceof Class<?>) { return addMember(memberName, "$T.class", value); } if (value instanceof Enum) { return addMember(memberName, "$T.$L", value.getClass(), ((Enum<?>) value).name()); } if (value instanceof String) { return addMember(memberName, "$S", value); } if (value instanceof Float) { return addMember(memberName, "$Lf", value); } if (value instanceof Character) { return addMember(memberName, "'$L'", characterLiteralWithoutSingleQuotes((char) value)); } return addMember(memberName, "$L", value); }
Source:
public MarshallableEntry loadEntry(Object key) throws PersistenceException { if (!isCacheReady()) return null; ClusteredGetCommand clusteredGetCommand = commandsFactory.buildClusteredGetCommand(key, keyPartitioner.getSegment(key), EnumUtil.bitSetOf(Flag.SKIP_OWNERSHIP_CHECK)); Collection<Response> responses; try { clusteredGetCommand.setTopologyId(rpcManager.getTopologyId()); CompletionStage<Map<Address, Response>> getAll = rpcManager.invokeCommandOnAll(clusteredGetCommand, MapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); responses = CompletionStages.join(getAll).values(); } catch (Exception e) { PERSISTENCE.errorDoingRemoteCall(e); throw new PersistenceException(e); } if (responses.isEmpty()) return null; Response response; if (responses.size() > 1) { Set<Response> setResponses = new HashSet<>(responses); if (setResponses.size() > 1) throw new PersistenceException(String.format( "Responses contains more than 1 element and these elements are not equal, so can't decide which one to use: %s", setResponses)); response = setResponses.iterator().next(); } else { response = responses.iterator().next(); } if (response.isSuccessful() && response instanceof SuccessfulResponse) { InternalCacheValue value = (InternalCacheValue) ((SuccessfulResponse) response).getResponseValue(); return value == null ? null : ctx.getMarshallableEntryFactory().create(key, value.getValue()); } PERSISTENCE.unknownResponsesFromRemoteCache(responses); throw new PersistenceException("Unknown responses"); }

Target:
public MarshallableEntry loadEntry(Object key) throws PersistenceException { if (!isCacheReady()) return null; ClusteredGetCommand clusteredGetCommand = commandsFactory.buildClusteredGetCommand(key, keyPartitioner.getSegment(key), EnumUtil.bitSetOf(Flag.SKIP_OWNERSHIP_CHECK)); Collection<Response> responses; try { clusteredGetCommand.setTopologyId(rpcManager.getTopologyId()); CompletionStage<Map<Address, Response>> getAll = rpcManager.invokeCommandOnAll(clusteredGetCommand, MapResponseCollector.ignoreLeavers(), rpcManager.getSyncRpcOptions()); responses = rpcManager.blocking(getAll).values(); } catch (Exception e) { PERSISTENCE.errorDoingRemoteCall(e); throw new PersistenceException(e); } if (responses.isEmpty()) return null; Response response; if (responses.size() > 1) { Set<Response> setResponses = new HashSet<>(responses); if (setResponses.size() > 1) throw new PersistenceException(String.format( "Responses contains more than 1 element and these elements are not equal, so can't decide which one to use: %s", setResponses)); response = setResponses.iterator().next(); } else { response = responses.iterator().next(); } if (response.isSuccessful() && response instanceof SuccessfulResponse) { InternalCacheValue value = (InternalCacheValue) ((SuccessfulResponse) response).getResponseValue(); return value == null ? null : ctx.getMarshallableEntryFactory().create(key, value.getValue()); } PERSISTENCE.unknownResponsesFromRemoteCache(responses); throw new PersistenceException("Unknown responses"); }
Source:
public void handle(final HttpServletRequest request, final HttpServletResponse response, final HandlerContext context) { String requestUri = request.getRequestURI(); if (this.enabled && isSecured(requestUri, request.getMethod())) { if (authenticationManager == null) { throw new AuthenticationException("Failed to authenticate request."); } int found = 0, failed = 0; for (CredentialsExtractor<HttpServletRequest> extractor : extractors) { Optional<Credentials> extracted = extractor.retrieveCredentials(request); if (extracted.isPresent()) { found++; Credentials credentials = extracted.get(); try { Authentication authentication = authenticationManager.authenticate(credentials); request.setAttribute(Authentication.class.getName(), authentication); context.execute(request, response); return; } catch (AuthenticationException e) { failed++; logger.info("Failed to authenticate using credentials {}", credentials, e); } } } throw new AuthenticationException("Could not authenticate request. Found " + found + " credentials in request out of which " + failed + " were invalid"); } }

Target:
public void handle(final HttpServletRequest request, final HttpServletResponse response, final HandlerContext context) throws Exception { String requestUri = request.getRequestURI(); if (this.enabled && isSecured(requestUri, request.getMethod())) { if (authenticationManager == null) { throw new AuthenticationException("Failed to authenticate request."); } int found = 0, failed = 0; for (CredentialsExtractor<HttpServletRequest> extractor : extractors) { Optional<Credentials> extracted = extractor.retrieveCredentials(request); if (extracted.isPresent()) { found++; Credentials credentials = extracted.get(); try { Authentication authentication = authenticationManager.authenticate(credentials); request.setAttribute(Authentication.class.getName(), authentication); context.execute(request, response); return; } catch (AuthenticationException e) { failed++; if (logger.isDebugEnabled()) { logger.debug("Failed to authenticate using credentials {}", credentials, e); } else { logger.info("Failed to authenticate using credentials {}", credentials); } } } } throw new AuthenticationException("Could not authenticate request. Found " + found + " credentials in request out of which " + failed + " were invalid"); } }
Source:
public void testAdHocQueryForStackOverFlowCondition() throws IOException, Exception { System.out.println("Starting testLongAdHocQuery"); VoltDB.Configuration config = setUpSPDB(); ServerThread localServer = new ServerThread(config); localServer.start(); localServer.waitForInitialization(); m_client = ClientFactory.createClient(); m_client.createConnection("localhost", config.m_port); try { for (int len = 2000; len < 100000; len += 1000) { String sql = getQueryForLongQueryTable(len); m_client.callProcedure("@AdHoc", sql); } fail("Query was expected to generate stack overflow error"); } catch (Exception exception) { final String expectedMsg = "Encountered stack overflow error. " + "Try reducing the number of predicate expressions in the query."; assertTrue("Expected text \"" + expectedMsg + "\" did not appear in exception " + "\"" + exception.getMessage() + "\"", exception.getMessage().contains(expectedMsg)); } finally { if (m_client != null) { m_client.close(); } m_client = null; localServer.shutdown(); localServer.join(); } }

Target:
public void testAdHocQueryForStackOverFlowCondition() throws Exception { System.out.println("Starting testLongAdHocQuery"); VoltDB.Configuration config = setUpSPDB(); ServerThread localServer = new ServerThread(config); localServer.start(); localServer.waitForInitialization(); m_client = ClientFactory.createClient(); m_client.createConnection("localhost", config.m_port); try { for (int len = 2000; len < 100000; len += 1000) { String sql = getQueryForLongQueryTable(len); m_client.callProcedure("@AdHoc", sql); } fail("Query was expected to generate stack overflow error"); } catch (Exception exception) { final String expectedMsg = "Encountered stack overflow error. " + "Try reducing the number of predicate expressions in the query."; assertTrue("Expected text \"" + expectedMsg + "\" did not appear in exception " + "\"" + exception.getMessage() + "\"", exception.getMessage().contains(expectedMsg)); } finally { if (m_client != null) { m_client.close(); m_client = null; } localServer.shutdown(); localServer.join(); } }
Source:
public void canValidatePomWithXpath() throws Exception { final MavenEnvironment env = new MavenEnvironmentMocker() .withAsserts( Collections.singletonList( "/pom:project/pom:dependencies/pom:dependency[pom:artifactId='commons-io']/pom:version[.='1.2.5']/text()" ) ).mock(); final String pom = IOUtils.toString( this.getClass().getResourceAsStream("PomXpathValidator/pom.xml"), Charset.defaultCharset() ); FileUtils.write( new File( String.format( "%s%spom.xml", env.basedir(), File.separator ) ), pom, Charset.defaultCharset() ); new PomXpathValidator().validate(env); }

Target:
public void canValidatePomWithXpath() throws Exception { final MavenEnvironment env = new MavenEnvironmentMocker() .withAsserts( Collections.singletonList( "/pom:project/pom:dependencies/pom:dependency[pom:artifactId='commons-io']/pom:version[.='1.2.5']/text()" ) ).mock(); final String pom = new TextOf( new ResourceOf("com/qulice/maven/PomXpathValidator/pom.xml") ).asString(); FileUtils.write( new File( String.format( "%s%spom.xml", env.basedir(), File.separator ) ), pom, StandardCharsets.UTF_8 ); new PomXpathValidator().validate(env); }
Source:
public Change perform(IProgressMonitor pm) throws CoreException { IFile modifiedResource = getModifiedResource(); assert modifiedResource.exists() : "Resource " + modifiedResource + " doesn't exists yet"; assert modifiedResource != null; IQ7NamedElement newElement = (IQ7NamedElement) RcpttCore .create(modifiedResource); if (newElement == null) { throw new RuntimeException("Failed to load RCPTT element " + modifiedResource); } IQ7NamedElement workingCopy = newElement.getWorkingCopy(pm); workingCopy.setID(EcoreUtil.generateUUID()); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); if (writeAccessChecker.makeResourceWritable(workingCopy)) { workingCopy.commitWorkingCopy(false, pm); } return null; }

Target:
public Change perform(IProgressMonitor pm) throws CoreException { IFile modifiedResource = getModifiedResource(); assert modifiedResource.exists() : "Resource " + modifiedResource + " doesn't exists yet"; assert modifiedResource != null; IQ7NamedElement newElement = (IQ7NamedElement) RcpttCore .create(modifiedResource); if (newElement == null) { throw new RuntimeException("Failed to load RCPTT element " + modifiedResource); } IQ7NamedElement workingCopy = newElement.getWorkingCopy(pm); workingCopy.setID(EcoreUtil.generateUUID()); workingCopy.commitWorkingCopy(false, pm); return null; }
Source:
SurveyReference resolveSurvey(SurveyReference surveyRef) { GuidCreatedOnVersionHolder surveyKeys = new GuidCreatedOnVersionHolderImpl(surveyRef); try { Survey survey = surveyService.getSurvey(surveyKeys); return new SurveyReference(survey.getIdentifier(), survey.getGuid(), new DateTime(survey.getCreatedOn())); } catch(EntityNotFoundException e) { return surveyRef; } }

Target:
SurveyReference resolveSurvey(SurveyReference surveyRef) { if (surveyRef.getIdentifier() != null) { return surveyRef; } try { GuidCreatedOnVersionHolder surveyKeys = new GuidCreatedOnVersionHolderImpl(surveyRef); Survey survey = surveyService.getSurvey(surveyKeys, false); return new SurveyReference(survey.getIdentifier(), survey.getGuid(), new DateTime(survey.getCreatedOn())); } catch(EntityNotFoundException e) { return surveyRef; } }
Source:
public double @NonNull getXAxis() { return fXValues; }

Target:
public double[] getXAxis() { return fXValues; }
Source:
public void setAcceptableValues(Collection<Date> values) { }

Target:
public void setAcceptableValues(Collection<Date> values) { List<Date> allowedDates = (List<Date>) values; Collections.sort(allowedDates); setDateRange(allowedDates.get(0), allowedDates.get(allowedDates.size() - 1)); }
Source:
public MethodResultCode execute(final ClientConnection conn, final Void v) throws IOException { LOGGER.info("ACTIVATING"); final MethodRequestParameter method = new MethodRequestParameter(CLASS_ID, OBIS_CODE, 1); final List<MethodResult> methodResultCode = conn.action(method); return methodResultCode.get(0).resultCode(); }

Target:
public MethodResultCode execute(final ClientConnection conn, final Void v) throws IOException { LOGGER.info("ACTIVATING"); final MethodRequestParameter method = new MethodRequestParameter(CLASS_ID, OBIS_CODE, 1); final List<MethodResult> methodResultCode = conn.action(method); if (methodResultCode == null || methodResultCode.isEmpty() || methodResultCode.get(0) == null) { throw new IOException("action method for ClientConnection should return a list with one MethodResult"); } return methodResultCode.get(0).resultCode(); }
Source:
boolean nullSavingStrategyExplicitlySet(Element methodElement, Class<?> javaClass) { Optional<AnnotationMirror> annotationMirrorForJavaClass = getAnnotationMirrorForJavaClass(methodElement, javaClass); if (annotationMirrorForJavaClass.isPresent()) { for (ExecutableElement executableElement : annotationMirrorForJavaClass.get().getElementValues().keySet()) { if (executableElement.getSimpleName().contentEquals("nullSavingStrategy")) { return true; } } } return false; }

Target:
private boolean nullSavingStrategyExplicitlySet(Element methodElement, Class<?> javaClass) { Optional<AnnotationMirror> annotationMirrorForJavaClass = getAnnotationMirrorForJavaClass(methodElement, javaClass); if (annotationMirrorForJavaClass.isPresent()) { for (ExecutableElement executableElement : annotationMirrorForJavaClass.get().getElementValues().keySet()) { if (executableElement.getSimpleName().contentEquals("nullSavingStrategy")) { return true; } } } return false; }
Source:
public Iterable<DynamicTest> verifySquares() { return Arrays.asList( testSquareAt(0, 0), testSquareAt(1, 2), testSquareAt(0, 1) ); }

Target:
Iterable<DynamicTest> verifySquares() { return Arrays.asList( testSquareAt(0, 0), testSquareAt(1, 2), testSquareAt(0, 1) ); }
Source:
public Map<String, String> getDeploymentConfiguration() { org.wso2.carbon.kernel.utils.Utils.checkSecurity(); File configFile = ConfigurationUtils.getConfigurationFileLocation(filename).toFile(); try (FileInputStream fileInputStream = new FileInputStream(configFile)) { String yamlFileString = getDeploymentContent(fileInputStream); String jsonString = ConfigResolverUtils.convertYAMLToJSON(yamlFileString); return getDeploymentConfigMap(jsonString); } catch (IOException e) { String errorMessage = "Failed populate Deployment Configuration from " + configFile.getName(); logger.error(errorMessage, e); throw new RuntimeException(errorMessage, e); } }

Target:
public Map<String, String> getDeploymentConfiguration() throws CarbonConfigurationException { org.wso2.carbon.kernel.utils.Utils.checkSecurity(); if (filename == null) { throw new CarbonConfigurationException("Error while reading the configuration file, filename is null"); } try { byte[] contentBytes = Files.readAllBytes(ConfigurationUtils.getConfigurationFileLocation(filename)); String yamlFileString = new String(contentBytes, StandardCharsets.UTF_8); return ConfigurationUtils.getDeploymentConfigMap(yamlFileString); } catch (IOException e) { String errorMessage = "Failed populate deployment configuration from " + filename; logger.error(errorMessage, e); throw new CarbonConfigurationException(errorMessage, e); } }
Source:
public Map<String, String> buildEnvFromProperties(InterpreterLaunchContext context) throws IOException { Map<String, String> envs = super.buildEnvFromProperties(context); String flinkHome = context.getProperties().getProperty("FLINK_HOME", envs.get("FLINK_HOME")); if (StringUtils.isBlank(flinkHome)) { throw new IOException("FLINK_HOME is not specified"); } File flinkHomeFile = new File(flinkHome); if (!flinkHomeFile.exists()) { throw new IOException(String.format("FLINK_HOME '%s' doesn't exist", flinkHome)); } if (flinkHomeFile.isFile()) { throw new IOException(String.format("FLINK_HOME '%s' is a file, but should be directory", flinkHome)); } envs.put("FLINK_CONF_DIR", flinkHome + "/conf"); envs.put("FLINK_LIB_DIR", flinkHome + "/lib"); envs.put("FLINK_PLUGINS_DIR", flinkHome + "/plugins"); return envs; }

Target:
public Map<String, String> buildEnvFromProperties(InterpreterLaunchContext context) throws IOException { Map<String, String> envs = super.buildEnvFromProperties(context); String flinkHome = context.getProperties().getProperty("FLINK_HOME", envs.get("FLINK_HOME")); if (StringUtils.isBlank(flinkHome)) { throw new IOException("FLINK_HOME is not specified"); } File flinkHomeFile = new File(flinkHome); if (!flinkHomeFile.exists()) { throw new IOException(String.format("FLINK_HOME '%s' doesn't exist", flinkHome)); } if (!flinkHomeFile.isDirectory()) { throw new IOException(String.format("FLINK_HOME '%s' is a file, but should be directory", flinkHome)); } envs.put("FLINK_CONF_DIR", flinkHome + "/conf"); envs.put("FLINK_LIB_DIR", flinkHome + "/lib"); envs.put("FLINK_PLUGINS_DIR", flinkHome + "/plugins"); return envs; }
Source:
public ColumnIndex readColumnIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getColumnIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); column.decryptIfNeededed(); BlockCipher.Decryptor columnIndexDecryptor = null; byte[] columnIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { columnIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); columnIndexAAD = AesCipher.createModuleAAD(fileDecryptor.getFileAAD(), ModuleType.ColumnIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), (short)-1); } } return ParquetMetadataConverter.fromParquetColumnIndex(column.getPrimitiveType(), Util.readColumnIndex(f, columnIndexDecryptor, columnIndexAAD)); }

Target:
public ColumnIndex readColumnIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getColumnIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); BlockCipher.Decryptor columnIndexDecryptor = null; byte[] columnIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { columnIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); columnIndexAAD = AesCipher.createModuleAAD(fileDecryptor.getFileAAD(), ModuleType.ColumnIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetColumnIndex(column.getPrimitiveType(), Util.readColumnIndex(f, columnIndexDecryptor, columnIndexAAD)); }
Source:
public void testDetypedMetricType() throws Exception { DetypedPathDeserializer.setCurrentCanonicalOrigin(CanonicalPath.fromString("/t;t")); MetricType mt = new MetricType(CanonicalPath.fromString("/t;t/mt;c"), MetricUnit.BYTES, GAUGE, new HashMap<String, Object>() {{ put("a", "b"); }}, 0L); testDetyped(mt, "{\"path\":\"/t;t/mt;c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\"}"); testDetyped(mt, "{\"path\":\"/t;t/c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\"}"); testDetyped(mt, "{\"path\":\"/c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\"}"); }

Target:
public void testDetypedMetricType() throws Exception { DetypedPathDeserializer.setCurrentCanonicalOrigin(CanonicalPath.fromString("/t;t")); MetricType mt = new MetricType(CanonicalPath.fromString("/t;t/mt;c"), MetricUnit.BYTES, GAUGE, new HashMap<String, Object>() {{ put("a", "b"); }}, 0L); testDetyped(mt, "{\"path\":\"/t;t/mt;c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\", " + "\"collectionInterval\":\"0\"}"); testDetyped(mt, "{\"path\":\"/t;t/c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\", " + "\"collectionInterval\":\"0\"}"); testDetyped(mt, "{\"path\":\"/c\",\"properties\":{\"a\":\"b\"},\"unit\":\"BYTES\"," + " \"collectionInterval\":\"0\"}"); }
Source:
public CorfuReplicationDiscoveryService(@Nonnull ServerContext serverContext, @Nonnull CorfuReplicationClusterManagerAdapter clusterManagerAdapter, @Nonnull CompletableFuture<CorfuInterClusterReplicationServerNode> serverCallback) throws Exception { this.clusterManagerAdapter = clusterManagerAdapter; this.logReplicationNodeId = serverContext.getNodeId(); this.serverContext = serverContext; this.localEndpoint = serverContext.getLocalEndpoint(); this.serverCallback = serverCallback; this.isLeader = new AtomicBoolean(); }

Target:
public CorfuReplicationDiscoveryService(@Nonnull ServerContext serverContext, @Nonnull CorfuReplicationClusterManagerAdapter clusterManagerAdapter, @Nonnull CompletableFuture<CorfuInterClusterReplicationServerNode> serverCallback) { this.clusterManagerAdapter = clusterManagerAdapter; this.logReplicationNodeId = serverContext.getNodeId(); this.serverContext = serverContext; this.localEndpoint = serverContext.getLocalEndpoint(); this.serverCallback = serverCallback; this.isLeader = new AtomicBoolean(); this.lockConfig = LockConfig.newInstance(serverContext.getLogReplicationConfig()); this.lockListener = new LogReplicationLockListener(this); }
Source:
protected void getResponse(String url, HttpResponse response, HttpRequestBase method, Map<String, Object> headers) { try { if (headers != null) { for (String key : headers.keySet()) { Object value = headers.get(key); if (value != null) { method.setHeader(key, value.toString()); } } } org.apache.http.HttpResponse resp; CookieStore store = response.getCookieStore(); if (store == null) { store = new BasicCookieStore(); } resp = getHttpResponse(store, url, method); int returnCode = resp.getStatusLine().getStatusCode(); response.setStatusCode(returnCode); HttpEntity entity = resp.getEntity(); Map<String, String> responseHeaders = response.getResponseHeaders(); for (Header h : resp.getAllHeaders()) { if(h.getName().equalsIgnoreCase("Set-Cookie")) { StringBuilder cookieHeader = new StringBuilder(); List<Cookie> cookies = store.getCookies(); for(Cookie cookie : cookies) { cookieHeader.append(cookie.getName() + "=" + cookie.getValue()); cookieHeader.append(";"); } responseHeaders.put(h.getName(), cookieHeader.toString()); } else { responseHeaders.put(h.getName(), h.getValue()); } } if (entity == null) { response.setResponse(null); } else { if (response instanceof BinaryHttpResponse) { BinaryHttpResponse binaryHttpResponse = (BinaryHttpResponse) response; byte[] content = EntityUtils.toByteArray(entity); binaryHttpResponse.setResponseContent(content); String fileName = getAttachmentFileName(resp); binaryHttpResponse.setFileName(fileName); } else { String result = EntityUtils.toString(entity); response.setResponse(result); } } } catch (Exception e) { throw new RuntimeException("Unable to get response from: " + url, e); } finally { method.reset(); } }

Target:
protected void getResponse(String url, HttpResponse response, HttpRequestBase method, Map<String, Object> headers) { try { if (headers != null) { for (String key : headers.keySet()) { Object value = headers.get(key); if (value != null) { method.setHeader(key, value.toString()); } } } org.apache.http.HttpResponse resp; CookieStore store = response.getCookieStore(); if (store == null) { resp = getHttpResponse(url, method); } else { resp = getHttpResponse(store, url, method); } int returnCode = resp.getStatusLine().getStatusCode(); response.setStatusCode(returnCode); HttpEntity entity = resp.getEntity(); Map<String, String> responseHeaders = response.getResponseHeaders(); for (Header h : resp.getAllHeaders()) { responseHeaders.put(h.getName(), h.getValue()); } if (entity == null) { response.setResponse(null); } else { if (response instanceof BinaryHttpResponse) { BinaryHttpResponse binaryHttpResponse = (BinaryHttpResponse) response; byte[] content = EntityUtils.toByteArray(entity); binaryHttpResponse.setResponseContent(content); String fileName = getAttachmentFileName(resp); binaryHttpResponse.setFileName(fileName); } else { String result = EntityUtils.toString(entity); response.setResponse(result); } } } catch (Exception e) { throw new RuntimeException("Unable to get response from: " + url, e); } finally { method.reset(); } }
Source:
private double gauss(double x, double mean, double variance) { return Math.exp((-1. * (x - mean) * (x - mean)) / (2. * variance)) / Math.sqrt(2. * Math.PI * variance); }

Target:
private double gauss(double x, double mean, double variance) { return Math.exp(-1. * Math.pow(x - mean, 2) / (2. * variance)) / Math.sqrt(2. * Math.PI * variance); }
Source:
private void createJarArchive(File archiveFile, List<String> toBeJared, File tempDir) throws IOException{ long now = System.currentTimeMillis(); byte buffer[] = new byte[10240]; File tmpjar = File.createTempFile(".rulec_", ".jar", archiveFile.getParentFile()); FileOutputStream stream = new FileOutputStream(tmpjar); JarOutputStream out = new JarOutputStream(stream, new Manifest()); try { for (String path : toBeJared) { JarEntry jarAdd = new JarEntry(path); File f = new File(tempDir, path); jarAdd.setTime(now); out.putNextEntry(jarAdd); if (f.isFile()) { FileInputStream in = new FileInputStream(f); try { while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } } finally { in.close(); } } out.closeEntry(); } if (!tmpjar.renameTo(archiveFile)) { throw new IOException("Cannot replace archiveFile"); } } finally { out.close(); tmpjar.delete(); } }

Target:
private void createJarArchive(File archiveFile, List<String> toBeJared, File tempDir) throws IOException{ long now = System.currentTimeMillis(); byte buffer[] = new byte[10240]; File tmpjar = File.createTempFile(".rulec_", ".jar", archiveFile.getParentFile()); FileOutputStream stream = new FileOutputStream(tmpjar); JarOutputStream out = new JarOutputStream(stream, new Manifest()); try { for (String path : toBeJared) { JarEntry jarAdd = new JarEntry(path); File f = new File(tempDir, path); jarAdd.setTime(now); out.putNextEntry(jarAdd); if (f.isFile()) { FileInputStream in = new FileInputStream(f); try { while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } } finally { in.close(); } } out.closeEntry(); } } finally { out.close(); } try { if (!tmpjar.renameTo(archiveFile)) { throw new IOException("Cannot replace archiveFile"); } } finally { tmpjar.delete(); } }
Source:
protected TokenEndpointResponse performRequest(LoginOptions options) throws Exception { return OAuth2.swapJWTForTokens(HttpAccess.DEFAULT, new URI(options.loginUrl), options.jwt); }

Target:
protected TokenEndpointResponse performRequest(LoginOptions options) { try { return OAuth2.swapJWTForTokens(HttpAccess.DEFAULT, new URI(options.loginUrl), options.jwt); } catch (Exception e) { onAuthFlowError("jwt_oauth_error", e.getLocalizedMessage()); callback.finish(); } return null; }
Source:
private ServerRequest request() { Map<String, Object> request = new ArrayMap<>(); request.put(Fields.KIND.getValue(), mKind.getValue()); Map<String, Object> metadata = new ArrayMap<>(); metadata.put("sender", mSender.getId()); Date ref = new Date(); try { ref = mKind.equals(ServiceRequest.RequestKind.NODE_MESSAGE) ? DateSerialization.dateSerializer.toDate((String) mConstructingMap.get(Fields.DATE.getValue())) : new Date(); } catch (ParseException e) { e.printStackTrace(); } metadata.put("datetime", formatDate( new Date())); metadata.put("ref", formatDate(ref)); request.put("metadata", new JSONObject(metadata)); request.put("message", new JSONObject(mConstructingMap)); return new ServerRequest(new JSONObject(request)); }

Target:
private ServerRequest request() { Map<String, Object> request = new ArrayMap<>(); request.put(Fields.KIND.getValue(), mKind.getValue()); Map<String, Object> metadata = new ArrayMap<>(); metadata.put("client", mSender.getId()); Date ref = new Date(); try { ref = mKind.equals(ServiceRequest.RequestKind.NODE_MESSAGE) ? DateSerialization.dateSerializer.toDate((String) mConstructingMap.get(Fields.DATE.getValue())) : new Date(); } catch (ParseException e) { Log.d("RequestBuilder", "Couldn't handle build ServerRequest correctly !"); } metadata.put("datetime", formatDate(new Date())); metadata.put("ref", formatDate(ref)); request.put("metadata", new JSONObject(metadata)); request.put("message", new JSONObject(mConstructingMap)); return new ServerRequest(new JSONObject(request)); }
Source:
private PrefilledCardholderDetails getPrefilledCardholderDetails() { if (cardholderName != null) { if (this.prefilledCardholderDetails == null) { this.prefilledCardholderDetails = new PrefilledCardholderDetails(); } this.prefilledCardholderDetails.setCardholderName(cardholderName); } if (addressLine1 != null || addressLine2 != null || postcode != null || city != null || country != null) { if (this.prefilledCardholderDetails == null) { this.prefilledCardholderDetails = new PrefilledCardholderDetails(); } this.prefilledCardholderDetails.setAddress(addressLine1, addressLine2, postcode, city, country); } return prefilledCardholderDetails; }

Target:
private PrefilledCardholderDetails getPrefilledCardholderDetails() { if (cardholderName != null) { this.prefilledCardholderDetails = new PrefilledCardholderDetails(); this.prefilledCardholderDetails.setCardholderName(cardholderName); } if (addressLine1 != null || addressLine2 != null || postcode != null || city != null || country != null) { if (this.prefilledCardholderDetails == null) { this.prefilledCardholderDetails = new PrefilledCardholderDetails(); } this.prefilledCardholderDetails.setAddress(addressLine1, addressLine2, postcode, city, country); } return prefilledCardholderDetails; }
Source:
private static RedDeerProperties getByName(String name){ RedDeerProperties rdProperty; try { rdProperty = RedDeerProperties.getByName(name); } catch (RedDeerException e) { rdProperty = RedDeerProperties.getByName("reddeer." + name); } return rdProperty; }

Target:
private static RedDeerProperties getByName(String name){ if (name.startsWith("reddeer.")){ return RedDeerProperties.getByName(name); } else { return RedDeerProperties.getByName("reddeer." + name); } }
Source:
public String getMainActivity() throws AndroidSdkException { return activityName; }

Target:
public String getMainActivity() throws AndroidSdkException { if(activityName.contains(".")) return activityName; else return packageName + "." + activityName; }
Source:
public StateDelta compare(State baseState) throws BundleException { BundleDescription[] current = this.getBundles(); StateDeltaImpl delta = new StateDeltaImpl(this); for (BundleDescription current1 : current) { BundleDescription existing = baseState.getBundleByLocation(current1.getLocation()); if (existing == null) { delta.recordBundleAdded((BundleDescriptionImpl) current1); } else if (updated.contains(current1.getLocation())) { delta.recordBundleUpdated((BundleDescriptionImpl) current1); } } BundleDescription[] existing = baseState.getBundles(); for (BundleDescription existing1 : existing) { BundleDescription local = getBundleByLocation(existing1.getLocation()); if (local == null) { delta.recordBundleRemoved((BundleDescriptionImpl) existing1); } } return delta; }

Target:
public StateDelta compare(State baseState) throws BundleException { BundleDescription[] currentBundles = this.getBundles(); StateDeltaImpl delta = new StateDeltaImpl(this); for (BundleDescription current : currentBundles) { BundleDescription existing = baseState.getBundleByLocation(current.getLocation()); if (existing == null) { delta.recordBundleAdded((BundleDescriptionImpl) current); } else if (updated.contains(current.getLocation())) { delta.recordBundleUpdated((BundleDescriptionImpl) current); } } BundleDescription[] existingBundles = baseState.getBundles(); for (BundleDescription existing : existingBundles) { BundleDescription local = getBundleByLocation(existing.getLocation()); if (local == null) { delta.recordBundleRemoved((BundleDescriptionImpl) existing); } } return delta; }