auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Iterator<Tuple2<Long, Tuple2<byte[], byte[]>>> call(Iterator<KVPair> kvPairIterator) throws Exception { if (!kvPairIterator.hasNext()) return Collections.EMPTY_LIST.iterator(); List<Tuple2<Long, Tuple2<byte[], byte[]>>> outList = new ArrayList<>(); while (kvPairIterator.hasNext()) { KVPair kvPair = kvPairIterator.next(); if (kvPair == null) continue; Tuple2<byte[], byte[]> kv = new Tuple2(kvPair.getRowKey(), kvPair.getValue()); outList.add(new Tuple2(conglomerateId, kv)); } return outList.iterator(); }

Target:
public Iterator<Tuple2<Long, Tuple2<byte[], byte[]>>> call(Iterator<KVPair> kvPairIterator) throws Exception { return new NullFilterKVPairIterator(conglomerateId, kvPairIterator); }
Source:
public InfoboxBuilderPage selectHeaderWithIndex(int index) { wait.forElementVisible(headers.get(index)); headers.get(index).click(); return this; }

Target:
public InfoboxBuilderPage selectHeaderWithIndex(int index) { WebElement selectedHeader = headers.get(index); wait.forElementClickable(selectedHeader); selectedHeader.click(); return this; }
Source:
public void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws UnprocessableEntityException, PatchBadRequestException, AuthorizeException, ResourceNotFoundException { try { EPerson eperson = es.find(context, uuid); if (eperson == null) { throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found"); } List<Operation> operations = patch.getOperations(); boolean isAdmin; try { isAdmin = authorizeService.isAdmin(context); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } for (Operation op: operations) { if (op.getPath().contentEquals("/canLogin") || op.getPath().contentEquals("/certificate") || op.getPath().contentEquals("/netid") || op.getPath().contentEquals("/email")) { if (!isAdmin) { throw new AuthorizeException(op.getPath() + " requires administrator."); } } } EPersonRest ePersonRest = findOne(context, uuid); EPersonRest patchedModel = (EPersonRest) epersonPatch.patch(ePersonRest, operations); updatePatchedValues(context, patchedModel, eperson); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
protected void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws AuthorizeException, SQLException { patchDSpaceObject(apiCategory, model, uuid, patch); }
Source:
public void shouldReturn404OnGetTransactionsWhenAccountIdIsNonNumeric() { getChargeApi .withAccountId("invalidAccountId") .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) .getCharges() .contentType(JSON) .statusCode(NOT_FOUND.getStatusCode()) .body("code", is(404)) .body("message", is("HTTP 404 Not Found")); }

Target:
public void shouldReturn404OnGetTransactionsWhenAccountIdIsNonNumeric() { getChargeApi .withAccountId("invalidAccountId") .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) .getTransactions() .contentType(JSON) .statusCode(NOT_FOUND.getStatusCode()) .body("code", is(404)) .body("message", is("HTTP 404 Not Found")); }
Source:
void multipleReceiverAndAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int firstBatch = 2; int secondBatch = 2; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages; if (isSessionEnabled) { messages = TestUtils.getServiceBusMessages(firstBatch, CONTENTS_BYTES, messageId, isSessionEnabled, sessionId); messages.addAll(TestUtils.getServiceBusMessages(secondBatch, CONTENTS_BYTES, messageId, isSessionEnabled, sessionId2)); } else { messages = TestUtils.getServiceBusMessages(firstBatch + secondBatch, CONTENTS_BYTES, messageId, isSessionEnabled, null); } sendMessage(messages).block(TIMEOUT); StepVerifier.create(receiver.receive().limitRequest(firstBatch)) .assertNext(message -> { messagesPending.decrementAndGet(); }) .assertNext(message -> { messagesPending.decrementAndGet(); }) .thenCancel() .verify(); StepVerifier.create(receiver2.receive().limitRequest(secondBatch)) .assertNext(message -> { messagesPending.decrementAndGet(); }) .assertNext(message -> { messagesPending.decrementAndGet(); }) .thenCancel() .verify(); }

Target:
void multipleReceiverAndAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int firstBatch = 2; int secondBatch = 2; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages; if (isSessionEnabled) { messages = TestUtils.getServiceBusMessages(firstBatch, CONTENTS_BYTES, messageId, sessionId); messages.addAll(TestUtils.getServiceBusMessages(secondBatch, CONTENTS_BYTES, messageId, sessionId2)); } else { messages = TestUtils.getServiceBusMessages(firstBatch + secondBatch, messageId, CONTENTS_BYTES); } sendMessage(messages).block(TIMEOUT); StepVerifier.create(receiver.receive(), firstBatch) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .thenCancel() .verify(); StepVerifier.create(receiver2.receive(), secondBatch) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .thenCancel() .verify(); }
Source:
public void handleBackpressure(CoreEvent event) { asyncQueue.offer(event); synchronized (asyncQueue) { asyncQueue.notify(); } synchronized (executing) { if (executing.get() != null) { if (!executing.get().isDone()) { return; } } executing.set(dispatchTask()); } }

Target:
public void handleBackpressure(CoreEvent event) { asyncQueue.offer(event); synchronized (executing) { if (executing.get() == null) { executing.set(dispatchTask()); } } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DynamicPomDependency)) { return false; } DynamicPomDependency that = (DynamicPomDependency) o; return getGroupID().equals(that.getGroupID()) && getArtifactID().equals(that.getArtifactID()) && getVersion().equals(that.getVersion()) && Objects.equals(getScope(), that.getScope()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DynamicPomDependency)) { return false; } DynamicPomDependency that = (DynamicPomDependency) o; if (!getGroupID().equals(that.getGroupID())) { return false; } if (!getArtifactID().equals(that.getArtifactID())) { return false; } if (!getVersion().equals(that.getVersion())) { return false; } return getScope() != null ? getScope().equals(that.getScope()) : that.getScope() == null; }
Source:
public void testModelEnrichmentWhenTopLevelDecisionTableWithDecision() { setupGraphWithDiagram(); setupGraphWithDecision(); final Optional<DecisionTable> oModel = definition.getModelClass(); definition.enrich(Optional.of(NODE_UUID), decision, oModel); final DecisionTable model = oModel.get(); assertBasicEnrichment(model); final List<InputClause> input = model.getInput(); assertThat(input.size()).isEqualTo(1); assertThat(input.get(0).getInputExpression()).isInstanceOf(InputClauseLiteralExpression.class); assertThat(input.get(0).getInputExpression().getText().getValue()).isEqualTo(DECISION_NAME_1); assertThat(input.get(0).getInputExpression().getTypeRef()).isEqualTo(DECISION_QNAME_1); assertStandardOutputClauseEnrichment(model); assertStandardDecisionRuleEnrichment(model, 1, 1); assertParentHierarchyEnrichment(model, 1, 1); }

Target:
public void testModelEnrichmentWhenTopLevelDecisionTableWithDecision() { setupGraphWithDiagram(); setupGraphWithDecision(); final Optional<DecisionTable> oModel = definition.getModelClass(); definition.enrich(Optional.of(NODE_UUID), decision, oModel); final DecisionTable model = oModel.get(); assertBasicEnrichment(model); final List<InputClause> input = model.getInput(); assertThat(input.size()).isEqualTo(1); assertThat(input.get(0).getInputExpression()).isInstanceOf(InputClauseLiteralExpression.class); assertThat(input.get(0).getInputExpression().getText().getValue()).isEqualTo(DECISION_NAME_1); assertThat(input.get(0).getInputExpression().getTypeRef()).isEqualTo(DECISION_QNAME_1); assertStandardOutputClauseEnrichment(model); assertStandardDecisionRuleEnrichment(model); assertParentHierarchyEnrichment(model); }
Source:
private void addAlert(VDS host, AuditLogType auditMessage) { AuditLogableBase logableBase = new AuditLogableBase(); logableBase.addCustomValue("VdsName", host.getName()); AlertDirector.addVdsAlert(host.getId(), auditMessage, auditLogDirector, logableBase); }

Target:
private void addAlert(VDS host, AuditLogType auditMessage) { AuditLogableBase logableBase = Injector.injectMembers(new AuditLogableBase()); logableBase.setVds(host); AlertDirector.addVdsAlert(host.getId(), auditMessage, auditLogDirector, logableBase); }
Source:
public static String encodeRow(String value) { return getRowPrefix() + SortSkew.getCode(value) + value; }

Target:
public static String encodeRow(String value) { return section.getRowPrefix() + SortSkew.getCode(value) + value; }
Source:
private ArrayList<String> relationshipStringList(List<QueryParameters.SpatialRelationship> relationshipList) { ArrayList<String> stringList = new ArrayList<>(); for (QueryParameters.SpatialRelationship relationship : relationshipList) { stringList.add(relationship.toString()); } return stringList; }

Target:
private static ArrayList<String> relationshipStringList(List<QueryParameters.SpatialRelationship> relationshipList) { ArrayList<String> stringList = new ArrayList<>(); for (QueryParameters.SpatialRelationship relationship : relationshipList) { stringList.add(relationship.toString()); } return stringList; }
Source:
public void testOperationWithResponseExamples() { String openApiYAML = readIntoYaml(GetOperationWithResponseExamples.class); int start = openApiYAML.indexOf("get:"); int end = openApiYAML.length() - 1; String extractedYAML = openApiYAML.substring(start, end); String expectedYAML = "get:\n" + " summary: \"Simple get operation\"\n" + " description: \"Defines a simple get operation with no inputs and a complex output\"\n" + " operationId: \"getWithPayloadResponse\"\n" + " responses:\n" + " 200:\n" + " description: \"voila!\"\n" + " content:\n" + " application/json:\n" + " schema:\n" + " type: \"object\"\n" + " properties:\n" + " id:\n" + " type: \"string\"\n" + " description: \"the user id\"\n" + " examples:\n" + " basic:\n" + " summary: \"shows a basic example\"\n" + " description: \"basic\"\n" + " value: \"{\\\"id\\\": 19877734}\"\n" + " deprecated: true"; assertEquals(extractedYAML, expectedYAML); }

Target:
public void testOperationWithResponseExamples() { String openApiYAML = readIntoYaml(GetOperationWithResponseExamples.class); int start = openApiYAML.indexOf("get:"); int end = openApiYAML.indexOf("components:"); String extractedYAML = openApiYAML.substring(start, end); String expectedYAML = "get:\n" + " summary: \"Simple get operation\"\n" + " description: \"Defines a simple get operation with no inputs and a complex output\"\n" + " operationId: \"getWithPayloadResponse\"\n" + " responses:\n" + " 200:\n" + " description: \"voila!\"\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: \"#/components/schemas/SampleResponseSchema\"\n" + " examples:\n" + " basic:\n" + " summary: \"shows a basic example\"\n" + " description: \"basic\"\n" + " value:\n" + " id: 19877734\n" + " deprecated: true\n"; assertEquals(extractedYAML, expectedYAML); }
Source:
public AssetField[] getAssetFieldsForAddress(final InetAddress address, final String vendor) { getReadLock().lock(); try { if (vendor == null) { LOG.debug("getAssetFieldsForAddress: WSMAN vendor field was null for address {}, returning empty list", InetAddressUtils.str(address)); return new AssetField[0]; } final List<AssetField> retval = new ArrayList<>(); for (final org.opennms.netmgt.config.wsmanAsset.adapter.Package pkg : m_config.getPackages()) { final String pkgVendor = pkg.getVendor(); if (pkgVendor != null) { if (pkgVendor.equals(vendor)) { retval.addAll(pkg.getAssetFields()); } } } if (retval.size() == 0) { LOG.debug("getAssetFieldsForAddress: Zero AssetField matches returned for with vendor: {}", InetAddressUtils.str(address), vendor); } return retval.toArray(new AssetField[0]); } finally { getReadLock().unlock(); } }

Target:
public AssetField[] getAssetFieldsForAddress(final InetAddress address, final String vendor) { getReadLock().lock(); try { if (vendor == null) { LOG.debug("getAssetFieldsForAddress: WSMAN vendor field was null for address {}, returning empty list", InetAddressUtils.str(address)); return new AssetField[0]; } final List<AssetField> retval = new ArrayList<>(); for (final org.opennms.netmgt.config.wsmanAsset.adapter.Package pkg : m_config.getPackages()) { final String pkgVendor = pkg.getVendor(); if (pkgVendor != null) { if (pkgVendor.equals(vendor)) { retval.addAll(pkg.getAssetFields()); } } } if (retval.isEmpty()) { LOG.debug("getAssetFieldsForAddress: Zero AssetField matches returned for with vendor: {}", InetAddressUtils.str(address), vendor); } return retval.toArray(new AssetField[0]); } finally { getReadLock().unlock(); } }
Source:
private void addAcceptor(final Issue issue, IssueResolutionAcceptor acceptor, String validDomain) { acceptor.accept(issue, validDomain, null, null, new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { if (element instanceof GeneratorEntry) { EObject elementRef = ((GeneratorEntry) element).getElementRef(); if (elementRef instanceof Statechart) { TransactionalEditingDomain sharedDomain = DiagramPartitioningUtil.getSharedDomain(); AbstractTransactionalCommand refactoringCommand = new AbstractTransactionalCommand(sharedDomain, CHANGE_DOMAIN_COMMAND, Collections.EMPTY_LIST) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { try { Statechart realStatechart = (Statechart) DiagramPartitioningUtil.getSharedDomain() .getResourceSet().getEObject(EcoreUtil.getURI(elementRef), true); (realStatechart).setDomainID(validDomain); } catch (Exception ex) { return CommandResult.newErrorCommandResult(ex); } return CommandResult.newOKCommandResult(); } @Override protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.CANCEL_STATUS; } }; try { refactoringCommand.execute(new NullProgressMonitor(), null); } catch (Exception ex) { ex.printStackTrace(); } } } } }); }

Target:
private void addAcceptor(final Issue issue, IssueResolutionAcceptor acceptor, String validDomain) { acceptor.accept(issue, validDomain, null, null, new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { if (element instanceof GeneratorEntry) { EObject referencedStatechart = ((GeneratorEntry) element).getElementRef(); if (referencedStatechart instanceof Statechart) { TransactionalEditingDomain sharedDomain = DiagramPartitioningUtil.getSharedDomain(); DomainChangeCommand refactoringCommand = new DomainChangeCommand(sharedDomain, CHANGE_DOMAIN_COMMAND, Collections.EMPTY_LIST, validDomain, (Statechart) referencedStatechart); try { refactoringCommand.execute(new NullProgressMonitor(), null); } catch (Exception ex) { ex.printStackTrace(); } } } } }); }
Source:
public PlanGroupReduceOperator(GroupReduceFunction<IN, OUT> udf, int[] logicalGroupingFields, String name, TypeInformation<IN> inputType, TypeInformation<OUT> outputType) { super(udf, logicalGroupingFields, name); this.inType = inputType; this.outType = outputType; super.setCombinable(this.isCombinable()); }

Target:
public PlanGroupReduceOperator(GroupReduceFunction<IN, OUT> udf, int[] logicalGroupingFields, String name, TypeInformation<IN> inputType, TypeInformation<OUT> outputType) { super(udf, logicalGroupingFields, name); this.inType = inputType; this.outType = outputType; super.setCombinable(getUserCodeWrapper().getUserCodeAnnotation(Combinable.class) != null); }
Source:
public static String getString(Locale language, String key) { if ((Objects.isNull(commonMessages) || commonMessages.size() <= 1) && (Objects.isNull(errorMessages) || errorMessages.size() <= 1)) { loadMsgs(); } if (localMessages.containsKey(language)) { ResourceBundle languageLocal = localMessages.get(language); if (languageLocal.containsKey(key)) { return languageLocal.getString(key); } String lowKey = key.toLowerCase(); if (languageLocal.containsKey(lowKey)) { return languageLocal.getString(lowKey); } } try { if (commonMessages.containsKey(language)) { ResourceBundle messages = commonMessages.get(language); if (messages.containsKey(key)) { return messages.getString(key); } } if (errorMessages.containsKey(language)) { ResourceBundle messages = errorMessages.get(language); if (messages.containsKey(key)) { return messages.getString(key); } } return key; } catch (RuntimeException irrelevant) { return key; } }

Target:
public static String getString(Locale language, String key) { if ((Objects.isNull(commonMessages) || commonMessages.size() <= 1) && (Objects.isNull(errorMessages) || errorMessages.size() <= 1)) { loadMsgs(); } List<Map<Locale, ResourceBundle>> messages = new ArrayList<>(); messages.add(localMessages); messages.add(commonMessages); messages.add(errorMessages); for (Map<Locale, ResourceBundle> message : messages) { if (message.containsKey(language)) { String foundMessage = getTranslatedMessage(message, language, key); if (!Objects.equals(foundMessage, "")) { return foundMessage; } } } return key; }
Source:
public Iterator<T> iterator() { return Stream.range(0, getWordsNum() << ADDRESS_BITS_PER_WORD) .filter(i -> (getWord(i >> ADDRESS_BITS_PER_WORD) & (1L << i)) != 0) .map(fromInt) .iterator(); }

Target:
public Iterator<T> iterator() { return new BitSetIterator<>(this); }
Source:
public ReadSupport<T> getReadSupport(Configuration configuration){ if (readSupportClass != null) { return getReadSupportInstance(readSupportClass); } else { return getReadSupportInstance(configuration); } }

Target:
ReadSupport<T> getReadSupport(Configuration configuration){ return getReadSupportInstance(readSupportClass == null ? (Class<? extends ReadSupport<T>>) getReadSupportClass(configuration) : readSupportClass); }
Source:
public AbstractBigtableAdmin( BigtableOptions options, Configuration configuration, AbstractBigtableConnection connection, BigtableTableAdminClient bigtableTableAdminClient, Set<TableName> disabledTables) { LOG.debug("Creating BigtableAdmin"); this.configuration = configuration; this.options = options; this.connection = connection; this.bigtableTableAdminClient = bigtableTableAdminClient; this.disabledTables = disabledTables; this.bigtableClusterName = BigtableClusterName.from(options); this.tableAdapter = new TableAdapter(options, columnDescriptorAdapter); }

Target:
public AbstractBigtableAdmin( BigtableOptions options, Configuration configuration, AbstractBigtableConnection connection, BigtableTableAdminClient bigtableTableAdminClient, Set<TableName> disabledTables) { LOG.debug("Creating BigtableAdmin"); this.configuration = configuration; this.options = options; this.connection = connection; this.bigtableTableAdminClient = bigtableTableAdminClient; this.disabledTables = disabledTables; this.bigtableClusterName = options.getClusterName(); this.tableAdapter = new TableAdapter(options, columnDescriptorAdapter); }
Source:
protected SSLEngine engineCreateSSLEngine(String host, int port) throws IllegalStateException { try { if (dynamicSSLContextImpl == null) { return this.getConfiguredDefaultSSLContext().createSSLEngine(host, port); } SSLContext sslContext = dynamicSSLContextImpl .getSSLContext(new URI(null, null, host, port, null, null, null)); if (sslContext == null) { throw new IllegalStateException(ElytronMessages.log.receivedSSLContextFromDynamicSSLContextProviderWasNull()); } if (sslContext instanceof DynamicSSLContext && sslContext.getSocketFactory().equals(this.engineGetSocketFactory())) { throw new IllegalStateException(ElytronMessages.log.dynamicSSLContextCreatesLoop()); } return sslContext.createSSLEngine(host, port); } catch (URISyntaxException e) { throw new IllegalStateException(ElytronMessages.log.couldNotCreateURI()); } catch (DynamicSSLContextException e) { throw new IllegalStateException(ElytronMessages.log.couldNotCreateDynamicSSLContextEngine()); } }

Target:
protected SSLEngine engineCreateSSLEngine(String host, int port) throws IllegalStateException { try { if (dynamicSSLContextImpl == null) { return this.getConfiguredDefaultSSLContext().createSSLEngine(host, port); } SSLContext sslContext = dynamicSSLContextImpl .getSSLContext(new URI(null, null, host, port, null, null, null)); if (sslContext == null) { throw ElytronMessages.log.receivedSSLContextFromDynamicSSLContextProviderWasNull(); } if (sslContext instanceof DynamicSSLContext && sslContext.getSocketFactory().equals(this.engineGetSocketFactory())) { throw ElytronMessages.log.dynamicSSLContextCreatesLoop(); } return sslContext.createSSLEngine(host, port); } catch (URISyntaxException e) { throw ElytronMessages.log.couldNotCreateURI(); } catch (DynamicSSLContextException e) { throw ElytronMessages.log.couldNotCreateDynamicSSLContextEngine(); } }
Source:
public void handlesLastPartitionCorrectly() { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = ParallelIndexSupervisorTask.createMergeIOConfigs( 10, createPartitionToLocations(count), CREATE_PARTIAL_SEGMENT_MERGE_IO_CONFIG ); assertNoMissingPartitions(count, assignedPartitionLocation); }

Target:
public void handlesLastPartitionCorrectly() { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = createMergeIOConfigs(); assertNoMissingPartitions(count, assignedPartitionLocation); }
Source:
public static void handleError(ChannelHandlerContext ctx, ProtocolError protocolError) { ChannelFuture f = ctx.writeAndFlush(new ErrorMessage( protocolError.getId(), protocolError.getErrorType(), protocolError.getTrace(), protocolError.getErrorMessage() )); switch (protocolError.getErrorType()) { case Invalid: case Timeout: case Cancelled: case Busy: case Declined: case UnexpectedError: case BadRequest: case NetworkError: case Unhealthy: break; case FatalProtocolError: f.addListener(ChannelFutureListener.CLOSE); break; default: break; } }

Target:
public static void handleError(ChannelHandlerContext ctx, ProtocolError protocolError) { ChannelFuture f = ctx.writeAndFlush(new ErrorMessage( protocolError.getId(), protocolError.getErrorType(), protocolError.getTrace(), protocolError.getMessage() )); switch (protocolError.getErrorType()) { case Invalid: case Timeout: case Cancelled: case Busy: case Declined: case UnexpectedError: case BadRequest: case NetworkError: case Unhealthy: break; case FatalProtocolError: f.addListener(ChannelFutureListener.CLOSE); break; default: break; } }
Source:
private File createTempReactorProject(Server server) throws MojoFailureException, MojoExecutionException { File tempFolder = new File(server.getServerDirectory(), "temp-project"); if (!tempFolder.exists()) { tempFolder.mkdir(); } Model tempModel = createModel(); Set<Project> watchedModules = server.getWatchedProjects(); for(Project module: watchedModules){ File srcDir = new File(module.getPath()); File moduleFile = new File(tempFolder, module.getArtifactId()); try { FileUtils.copyDirectory(srcDir, moduleFile); Model model = Project.loadProject(moduleFile).getModel(); Parent parent = new Parent(); parent.setArtifactId("temp-project"); parent.setGroupId("org.temp"); parent.setVersion("1.0"); model.setParent(parent); Writer writer = new FileWriter(new File(moduleFile, "pom.xml")); new MavenXpp3Writer().write(writer, model); tempModel.addModule(module.getArtifactId()); } catch (IOException e) { e.printStackTrace(); } } try { Writer writer = new FileWriter(new File(tempFolder, "pom.xml")); new MavenXpp3Writer().write(writer, tempModel); } catch (IOException e) { e.printStackTrace(); } return tempFolder; }

Target:
private File createTempReactorProject(Server server) throws MojoFailureException, MojoExecutionException { File tempFolder = new File(server.getServerDirectory(), "temp-project"); if (!tempFolder.exists()) { tempFolder.mkdir(); } Model tempModel = createModel(); Set<Project> watchedModules = server.getWatchedProjects(); for(Project module: watchedModules){ Path newLink = Paths.get(new File(tempFolder, module.getArtifactId()).getAbsolutePath()); Path existingfile = Paths.get(module.getPath()); try { Files.createSymbolicLink(newLink, existingfile); tempModel.addModule(module.getArtifactId()); } catch (IOException e) { throw new RuntimeException("Couldn't create link", e); } catch (UnsupportedOperationException e) { throw new RuntimeException("Couldn't create link due to unsupported file system", e); } } try { Writer writer = new FileWriter(new File(tempFolder, "pom.xml")); new MavenXpp3Writer().write(writer, tempModel); } catch (IOException e) { throw new RuntimeException("Failed to write pom.xml", e); } return tempFolder; }
Source:
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) throws InterruptedException { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); journal.logAddEntry(entry, false , (rc, ledgerId, entryId, addr, ctx) -> { if (LOG.isDebugEnabled()) { LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); } if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); return result; }

Target:
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); try { journal.logAddEntry(entry, false , (rc, ledgerId, entryId, addr, ctx) -> { if (LOG.isDebugEnabled()) { LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); } if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); } catch (InterruptedException e) { Thread.currentThread().interrupt(); result.setException(e); } return result; }
Source:
public static ArrayList<String> toHtmlList(Context context) { ArrayList<String> items = new ArrayList<String>(); PackageManager packageManager = context.getPackageManager(); PackageInfo pkInfo = PackageUtils.getPackageInfo(context); ApplicationInfo applicationInfo = pkInfo != null ? pkInfo.applicationInfo : null; String appName; if (applicationInfo != null && packageManager.getApplicationLabel(applicationInfo) != null) { appName = packageManager.getApplicationLabel(applicationInfo).toString(); } else { appName = "Unknown"; } items.add("<strong>" + appName + " - " + PackageUtils.getVersionName(context) + " - Version code: " + PackageUtils.getVersionCode(context) + "</strong>"); items.add("<strong>Android device name: " + DeviceUtils.getInstance().getDeviceName(context) + "</strong>"); Iterator<LogEntry> it = mLogEntries.iterator(); while (it.hasNext()) { items.add(it.next().toHtml()); } return items; }

Target:
public static ArrayList<String> toHtmlList(Context context) { ArrayList<String> items = new ArrayList<String>(); items.add("<strong>" + getAppInfoHeaderText(context) + "</strong>"); items.add("<strong>" + getDeviceInfoHeaderText(context) + "</strong>"); Iterator<LogEntry> it = mLogEntries.iterator(); while (it.hasNext()) { items.add(it.next().toHtml()); } return items; }
Source:
private DataSource createDataSource(String driverClass, String url, String account, String password) { ComboPooledDataSource dataSource = new ComboPooledDataSource(); try { dataSource.setDriverClass(driverClass); dataSource.setJdbcUrl(url); dataSource.setUser(account); dataSource.setPassword(password); dataSource.setMinPoolSize(10); dataSource.setMaxPoolSize(35); dataSource.setAcquireIncrement(0); dataSource.setMaxStatements(0); dataSource.setMaxIdleTime(300); dataSource.setIdleConnectionTestPeriod(30); dataSource.setTestConnectionOnCheckin(false); dataSource.setTestConnectionOnCheckout(true); dataSource.setPreferredTestQuery("SELECT 1;"); dataSource.setMaxConnectionAge(8 * 24 * 60 * 60); dataSource.setCheckoutTimeout(8 * 24 * 60 * 60); } catch (PropertyVetoException e) { e.printStackTrace(); } mPoolMap.put(url, dataSource); return dataSource; }

Target:
private DataSource createDataSource(String driverClass, String url, String account, String password) { ComboPooledDataSource dataSource = new ComboPooledDataSource(); try { dataSource.setDriverClass(driverClass); dataSource.setJdbcUrl(url); dataSource.setUser(account); dataSource.setPassword(password); dataSource.setMinPoolSize(10); dataSource.setMaxPoolSize(35); dataSource.setAcquireIncrement(0); dataSource.setMaxStatements(0); dataSource.setMaxIdleTime(300); dataSource.setIdleConnectionTestPeriod(30); dataSource.setTestConnectionOnCheckin(false); dataSource.setTestConnectionOnCheckout(true); dataSource.setPreferredTestQuery("SELECT 1;"); dataSource.setMaxConnectionAge(480); dataSource.setCheckoutTimeout(480); } catch (PropertyVetoException e) { e.printStackTrace(); } mPoolMap.put(url, dataSource); return dataSource; }
Source:
public void assignUserToPullRequest(User user, PullRequest pull) { JsonObject json = Json.createObjectBuilder().add(FIELD_KEY_ASSIGNEE, user.username).build(); final String uri = buildIssueUri(pull.repo.name, pull.number); logger.debug(String.format("assign user [%s] to pr [%s]", user.username, pull.title)); try { Request req = client.entry() .method(Request.PATCH).body().set(json) .back().uri().path(uri) .back(); req.fetch(); } catch (IOException e) { logger.error(String.format("assigning user [%s] to pr [%s] FAILED - what a fukking a shaaame.", user.username, pull.title)); throw new UnexpectedException(e); } }

Target:
public void assignUserToPullRequest(User user, PullRequest pull) { JsonObject json = Json.createObjectBuilder().add(FIELD_KEY_ASSIGNEE, user.username).build(); final String uri = buildIssueUri(pull.repo.name, pull.number); logger.debug("assign user to pr {}", user.username, pull.title); try { Request req = client.entry() .method(Request.PATCH).body().set(json) .back().uri().path(uri) .back(); req.fetch(); } catch (IOException e) { logger.error("assigning user to pr FAILED - what a shame!", user.username, pull.title); throw new UnexpectedException(e); } }
Source:
public void dispose() { deregisterClient(); if (null != client) { client.destroy(false); } if (null != server) { server.destroy(); } currentEndpointIdentifier = null; }

Target:
public void dispose() { deregisterClient(); currentEndpointIdentifier = null; }
Source:
public WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subprotocol, HttpHeaders customHeaders, int maxFramePayloadLength, long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl, String httpRequestEncoderName, String httpResponseDecoderName) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, absoluteUpgradeUrl, httpRequestEncoderName, httpResponseDecoderName); }

Target:
WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subprotocol, HttpHeaders customHeaders, int maxFramePayloadLength, long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl, String httpRequestEncoderName, String httpResponseDecoderName) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, absoluteUpgradeUrl, httpRequestEncoderName, httpResponseDecoderName); }
Source:
public void testLocation() { JavaPackageInfoSource packageInfo = Roaster.create(JavaPackageInfoSource.class); packageInfo.setPackage("abc"); Assert.assertThat(packageInfo.getStartPosition(), is(0)); System.out.println(packageInfo); Assert.assertThat(packageInfo.getEndPosition(), is(20)); Assert.assertThat(packageInfo.getColumnNumber(), is(0)); Assert.assertThat(packageInfo.getLineNumber(), is(1)); }

Target:
public void testLocation() { JavaPackageInfoSource packageInfo = Roaster.create(JavaPackageInfoSource.class); packageInfo.setPackage("abc"); Assert.assertThat(packageInfo.getStartPosition(), is(0)); Assert.assertThat(packageInfo.getEndPosition(), is(20)); Assert.assertThat(packageInfo.getColumnNumber(), is(0)); Assert.assertThat(packageInfo.getLineNumber(), is(1)); }
Source:
public void setup(Context.OperatorContext context) { AggregatorRegistry.DEFAULT_AGGREGATOR_REGISTRY.setup(); schema = new DimensionalSchema(new DimensionalConfigurationSchema(eventSchemaJSON, AggregatorRegistry.DEFAULT_AGGREGATOR_REGISTRY)); maxProductId = 7; maxCustomerId = 30; maxChannelId = schema.getDimensionalConfigurationSchema().getKeysToEnumValuesList().get(KEY_CHANNEL).size(); maxRegionId = schema.getDimensionalConfigurationSchema().getKeysToEnumValuesList().get(KEY_REGION).size(); tuplesPerCurrentWindow = maxTuplesPerWindow; generateDiscounts(); generateRegionalTax(); initializeDataGenerators(); }

Target:
public void setup(Context.OperatorContext context) { AggregatorRegistry.DEFAULT_AGGREGATOR_REGISTRY.setup(); schema = new DimensionalSchema(new DimensionalConfigurationSchema(eventSchemaJSON, AggregatorRegistry.DEFAULT_AGGREGATOR_REGISTRY)); maxProductId = 100; maxCustomerId = 30; maxChannelId = schema.getDimensionalConfigurationSchema().getKeysToEnumValuesList().get(KEY_CHANNEL).size(); maxRegionId = schema.getDimensionalConfigurationSchema().getKeysToEnumValuesList().get(KEY_REGION).size(); tuplesPerCurrentWindow = maxTuplesPerWindow; generateDiscounts(); generateRegionalTax(); initializeDataGenerators(); }
Source:
private static <T> void validateEntry(ReferenceDataId<?> id, Object value) { if (!id.getReferenceDataType().isInstance(value)) { if (value == null) { throw new IllegalArgumentException(Messages.format( "Reference data must not be null for identifier '{}'", id)); } throw new ClassCastException(Messages.format( "Value '{}' does not implement parameterized type '{}' for identifier '{}'", value, id.getReferenceDataType().getSimpleName(), id)); } }

Target:
private static void validateEntry(ReferenceDataId<?> id, Object value) { if (!id.getReferenceDataType().isInstance(value)) { if (value == null) { throw new IllegalArgumentException(Messages.format( "Value for identifier '{}' must not be null", id)); } throw new ClassCastException(Messages.format( "Value for identifier '{}' does not implement expected type '{}': '{}'", id, id.getReferenceDataType().getSimpleName(), value)); } }
Source:
public List<String> buildLinesFromFile(File file) throws IOException, NoDataException, EmptyFileException { List<String> lines; InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); try { lines = bufferedReader.lines().collect(Collectors.toList()); if (lines.size() == 0) { throw new EmptyFileException("File [" + file.getName() + "] is empty"); } else if (lines.size() == 1) { throw new NoDataException("Header was found, but no data is present in file [" + file.getName() + "]"); } } finally { inputStreamReader.close(); } return lines; }

Target:
public List<String> buildLinesFromFile(File file) throws IOException, NoDataException, EmptyFileException { List<String> lines; try (BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(file), "UTF-8"))) { lines = bufferedReader.lines().collect(Collectors.toList()); if (lines.size() == 0) { throw new EmptyFileException("File [" + file.getName() + "] is empty"); } else if (lines.size() == 1) { throw new NoDataException("Header was found, but no data is present in file [" + file.getName() + "]"); } } return lines; }
Source:
public static HashMap<String, Map<String, Boolean>> listWhitelisted(int uid) { Util.log(null, Log.WARN, "Getting whitelists for " + uid); HashMap<String, Map<String, Boolean>> mapWhitelisted = new HashMap<String, Map<String, Boolean>>(); for (PSetting setting : getSettingList(uid)) { String[] components = setting.name.split("\\."); if (components.length < 2) continue; String type = components[0]; String name = setting.name.replace(components[0] + ".", ""); if (type.equals(Meta.cWhitelistAccount) || type.equals(Meta.cWhitelistContact) || type.equals(Meta.cWhitelistApplication)) continue; if (setting.value.equals("")) continue; if (!mapWhitelisted.containsKey(type)) mapWhitelisted.put(type, new HashMap<String, Boolean>()); mapWhitelisted.get(type).put(name, Boolean.parseBoolean(setting.value)); Util.log(null, Log.WARN, String.format("Whitelist for %d (%s) %s = %s", uid, type, name, setting.value)); } return mapWhitelisted; }

Target:
public static HashMap<String, Map<String, Boolean>> listWhitelisted(int uid) { Util.log(null, Log.WARN, "Getting whitelists for " + uid); HashMap<String, Map<String, Boolean>> mapWhitelisted = new HashMap<String, Map<String, Boolean>>(); for (PSetting setting : getSettingList(uid)) { if (setting.name.startsWith("Whitelist")) { String[] components = setting.name.split("\\."); if (components.length < 3) continue; String type = components[1]; String name = setting.name.replace(components[0] + "." + components[1] + ".", ""); if (setting.value.equals("")) continue; if (!mapWhitelisted.containsKey(type)) mapWhitelisted.put(type, new HashMap<String, Boolean>()); mapWhitelisted.get(type).put(name, Boolean.parseBoolean(setting.value)); Util.log(null, Log.WARN, String.format("Whitelist for %d (%s) %s = %s", uid, type, name, setting.value)); } } return mapWhitelisted; }
Source:
private void processRequests() { AsyncRequestInfo requestInfo = null; String uri = null; while (true) { try { requestInfo = requests.poll(POLL_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (requestInfo != null) { uri = requestInfo.getRestRequest().getUri(); trackMetricsOnDequeue(requestInfo); processRequest(requestInfo); logger.trace("Request was handled successfully", uri); } else { break; } } catch (Exception e) { logger.error("Handling of request failed", uri, e); restServerMetrics.dequeuedRequestHandlerRequestHandlingError.inc(); if (requestInfo != null) { onResponseComplete(requestInfo.getRestResponseChannel(), e, false); releaseResources(requestInfo.getRestRequest(), null); } } } }

Target:
private void processRequests() { AsyncRequestInfo requestInfo = null; String uri = null; int processedThisTime = 0; while (processedThisTime < SINGLE_ITERATION_REQUEST_PROCESS_LIMIT) { try { requestInfo = requests.poll(POLL_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (requestInfo != null) { queuedRequestCount.decrementAndGet(); uri = requestInfo.getRestRequest().getUri(); trackMetricsOnDequeue(requestInfo); processRequest(requestInfo); logger.trace("Request was handled successfully", uri); } else { break; } } catch (Exception e) { logger.error("Handling of request failed", uri, e); restServerMetrics.dequeuedRequestHandlerRequestHandlingError.inc(); if (requestInfo != null) { onResponseComplete(requestInfo.getRestResponseChannel(), e, false); releaseResources(requestInfo.getRestRequest(), null); } } finally { processedThisTime++; } } }
Source:
protected void scanFile(XmlFile file) { Charset charset = file.getInputFile().charset(); for (Node comment : getComments(file)) { if (reportedNodes.contains(comment)) { continue; } List<Node> siblingComments = getNextCommentSiblings(comment); checkCommentBlock(siblingComments, charset); reportedNodes.addAll(siblingComments); } reportedNodes.clear(); }

Target:
protected void scanFile(XmlFile file) { Charset charset = file.getInputFile().charset(); for (Node comment : getComments(file)) { if (visitedNodes.contains(comment)) { continue; } List<Node> siblingComments = getNextCommentSiblings(comment); checkCommentBlock(siblingComments, charset); visitedNodes.addAll(siblingComments); } visitedNodes.clear(); }
Source:
private Message<?> decodeNativeFormat(byte[] bytes) throws Exception { ByteBuffer buffer = ByteBuffer.wrap(bytes); if (buffer.remaining() > 4) { int headersLen = buffer.getInt(); if (headersLen >= 0 && headersLen < buffer.remaining() - 4) { buffer.position(headersLen + 4); int payloadLen = buffer.getInt(); if (payloadLen != buffer.remaining()) { buffer.position(0); return null; } else { buffer.position(4); @SuppressWarnings("unchecked") Map<String, Object> headers = this.objectMapper.readValue(bytes, buffer.position(), headersLen, HashMap.class); buffer.position(buffer.position() + headersLen); buffer.getInt(); Object payload; byte[] payloadBytes = new byte[payloadLen]; buffer.get(payloadBytes); payload = payloadBytes; return new GenericMessage<Object>(payload, new MutableMessageHeaders(headers)); } } } buffer.position(0); return null; }

Target:
private Message<?> decodeNativeFormat(byte[] bytes) throws Exception { ByteBuffer buffer = ByteBuffer.wrap(bytes); if (buffer.remaining() > 4) { int headersLen = buffer.getInt(); if (headersLen >= 0 && headersLen < buffer.remaining() - 4) { buffer.position(headersLen + 4); int payloadLen = buffer.getInt(); if (payloadLen != buffer.remaining()) { return null; } else { buffer.position(4); @SuppressWarnings("unchecked") Map<String, Object> headers = this.objectMapper.readValue(bytes, buffer.position(), headersLen, HashMap.class); buffer.position(buffer.position() + headersLen); buffer.getInt(); Object payload; byte[] payloadBytes = new byte[payloadLen]; buffer.get(payloadBytes); payload = payloadBytes; return new GenericMessage<Object>(payload, new MutableMessageHeaders(headers)); } } } return null; }
Source:
public HttpRequest getHttpRequest(Request coapRequest) throws TranslationException { if (coapRequest == null) { throw new IllegalArgumentException("coapRequest == null"); } HttpRequest httpRequest = null; String coapMethod = null; switch (coapRequest.getCode()) { case GET: coapMethod = "GET"; break; case POST: coapMethod = "POST"; break; case PUT: coapMethod = "PUT"; break; case DELETE: coapMethod = "DELETE"; break; } URI proxyUri; try { String proxyUriString = URLDecoder.decode( coapRequest.getOptions().getProxyUri(), "UTF-8"); proxyUri = new URI(proxyUriString); } catch (UnsupportedEncodingException e) { LOGGER.warn("UTF-8 do not support this encoding: {}", e); throw new TranslationException("UTF-8 do not support this encoding", e); } catch (URISyntaxException e) { LOGGER.warn("Cannot translate the server uri {}", e); throw new InvalidFieldException("Cannot get the proxy-uri from the coap message", e); } RequestLine requestLine = new BasicRequestLine(coapMethod, proxyUri.toString(), HttpVersion.HTTP_1_1); HttpEntity httpEntity = getHttpEntity(coapRequest); if (httpEntity == null) { httpRequest = new BasicHttpRequest(requestLine); } else { httpRequest = new BasicHttpEntityEnclosingRequest(requestLine); ((HttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); ContentType contentType = ContentType.get(httpEntity); httpRequest.setHeader("content-type", contentType.toString()); } Header[] headers = getHttpHeaders(coapRequest.getOptions().asSortedList()); for (Header header : headers) { httpRequest.addHeader(header); } return httpRequest; }

Target:
public HttpRequest getHttpRequest(Request coapRequest) throws TranslationException { if (coapRequest == null) { throw new IllegalArgumentException("coapRequest == null"); } HttpRequest httpRequest = null; String coapMethod = null; switch (coapRequest.getCode()) { case GET: coapMethod = "GET"; break; case POST: coapMethod = "POST"; break; case PUT: coapMethod = "PUT"; break; case DELETE: coapMethod = "DELETE"; break; } URI proxyUri; try { String proxyUriString = URLDecoder.decode( coapRequest.getOptions().getProxyUri(), "UTF-8"); proxyUri = new URI(proxyUriString); } catch (UnsupportedEncodingException e) { LOGGER.warn("UTF-8 do not support this encoding", e); throw new TranslationException("UTF-8 do not support this encoding", e); } catch (URISyntaxException e) { LOGGER.warn("Cannot translate the server uri", e); throw new InvalidFieldException("Cannot get the proxy-uri from the coap message", e); } RequestLine requestLine = new BasicRequestLine(coapMethod, proxyUri.toString(), HttpVersion.HTTP_1_1); HttpEntity httpEntity = getHttpEntity(coapRequest); if (httpEntity == null) { httpRequest = new BasicHttpRequest(requestLine); } else { httpRequest = new BasicHttpEntityEnclosingRequest(requestLine); ((HttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity); ContentType contentType = ContentType.get(httpEntity); httpRequest.setHeader("content-type", contentType.toString()); } Header[] headers = getHttpHeaders(coapRequest.getOptions().asSortedList()); for (Header header : headers) { httpRequest.addHeader(header); } return httpRequest; }
Source:
public void expressionMapVerifyResultTest() { String expressionCollectionJsonString = new TextNode("JsonText").toString(); expressionEvaluator.verifyResult(expressionCollectionJsonString, new HashMap<>(), null); }

Target:
public void expressionMapVerifyResultTest() { String expressionCollectionJsonString = new TextNode("{key_a : 1}").toString(); Map<String, BigDecimal> contextValue = Collections.singletonMap("key_a", BigDecimal.valueOf(1)); assertTrue(expressionEvaluator.verifyResult(expressionCollectionJsonString, contextValue, Map.class)); }
Source:
private StateMachine initStateMachine() { return StateMachine.newBuilder() .addState(RUNNING, "Running normally, with no outstanding pauses") .addState(WAITING_PAUSE_RESULT, "Waiting for pause confirmation from Controller Task") .addState(PAUSED, "Controller Task has paused") .addState(CANCELLING, "Pause is being cancelled") .setInitialState(RUNNING) .addTransition(RUNNING, RUNNING, "Running normally") .addTransition(RUNNING, WAITING_PAUSE_RESULT, "The pause request has been sent") .addTransition(WAITING_PAUSE_RESULT, PAUSED, "The Controller Task has confirmed pause") .addTransition(PAUSED, RUNNING, "The resume request has been sent") .addTransition(WAITING_PAUSE_RESULT, CANCELLING, "The pause request cannot be satisfied") .addTransition(CANCELLING, RUNNING, "The pause has been cancelled") .build(); }

Target:
private StateMachine initStateMachine() { return StateMachine.newBuilder() .addState(RUNNING, "Running normally, with no outstanding pauses") .addState(WAITING_PAUSE_RESULT, "Waiting for pause confirmation from Controller Task") .addState(PAUSED, "Controller Task has paused") .addState(CANCELLING, "Pause is being cancelled") .setInitialState(RUNNING) .addTransition(RUNNING, WAITING_PAUSE_RESULT, "The pause request has been sent") .addTransition(WAITING_PAUSE_RESULT, PAUSED, "The Controller Task has confirmed pause") .addTransition(PAUSED, RUNNING, "The resume request has been sent") .addTransition(WAITING_PAUSE_RESULT, CANCELLING, "The pause request cannot be satisfied") .addTransition(CANCELLING, RUNNING, "The pause has been cancelled") .build(); }
Source:
public void testFilterPrivate() { filter.inClazz = DummyPrivatePOJO.class; filter.setCondition("({$}.getVal() == 100)"); filter.activate(null); logger.debug("start round 0"); filter.beginWindow(0); data.setVal(100); filter.input.process(data); Assert.assertEquals("true tuples", 1, filter.trueTuples); Assert.assertEquals("false tuples", 0, filter.falseTuples); filter.endWindow(); logger.debug("end round 0"); logger.debug("start round 1"); filter.beginWindow(1); data.setVal(1000); filter.input.process(data); Assert.assertEquals("true tuples", 0, filter.trueTuples); Assert.assertEquals("false tuples", 1, filter.falseTuples); filter.endWindow(); logger.debug("end round 1"); filter.deactivate(); }

Target:
public void testFilterPrivate() { prepareFilterOperator(DummyPrivatePOJO.class, "({$}.getVal() == 100)"); filter.beginWindow(0); data.setVal(100); filter.input.put(data); Assert.assertEquals("true condition true tuples", 1, trueSink.getCount()); Assert.assertEquals("true condition false tuples", 0, falseSink.getCount()); Assert.assertEquals("true condition error tuples", 0, errorSink.getCount()); filter.endWindow(); clearSinks(); filter.beginWindow(1); data.setVal(1000); filter.input.put(data); Assert.assertEquals("false condition true tuples", 0, trueSink.getCount()); Assert.assertEquals("false condition false tuples", 1, falseSink.getCount()); Assert.assertEquals("false condition error tuples", 0, errorSink.getCount()); filter.endWindow(); clearFilterOperator(); }