auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private WindowDefinition getWindowDefinition(Optional<Window> maybeWindow, ExpressionAnalysisContext context) { if (!maybeWindow.isPresent()) { return null; } Window window = maybeWindow.get(); List<Symbol> partitionSymbols = new ArrayList<>(window.getPartitions().size()); for (Expression partition : window.getPartitions()) { Symbol symbol = convert(partition, context); SemanticSortValidator.validate(symbol, "PARTITION BY"); partitionSymbols.add(symbol); } OrderBy orderBy = OrderyByAnalyzer.analyzeSortItems(window.getOrderBy(), sortKey -> { Symbol symbol = convert(sortKey, context); SemanticSortValidator.validate(symbol); return symbol; }); WindowFrameDefinition windowFrameDefinition = WindowDefinition.UNBOUNDED_PRECEDING_CURRENT_ROW; if (window.getWindowFrame().isPresent()) { WindowFrame windowFrame = window.getWindowFrame().get(); FrameBound start = windowFrame.getStart(); if (start.equals(UNBOUNDED_FOLLOWING)) { throw new IllegalArgumentException("Window frame start cannot be UNBOUNDED FOLLOWING"); } FrameBoundDefinition startBound = convertToAnalyzedFrameBound(context, start); FrameBoundDefinition endBound = new FrameBoundDefinition(FrameBound.Type.CURRENT_ROW); if (windowFrame.getEnd().isPresent()) { FrameBound end = windowFrame.getEnd().get(); if (end.equals(UNBOUNDED_PRECEDING)) { throw new IllegalArgumentException("Window frame end cannot be UNBOUNDED PRECEDING"); } endBound = convertToAnalyzedFrameBound(context, end); } windowFrameDefinition = new WindowFrameDefinition(windowFrame.getType(), startBound, endBound); } return new WindowDefinition(partitionSymbols, orderBy, windowFrameDefinition); }

Target:
private WindowDefinition getWindowDefinition(Optional<Window> maybeWindow, ExpressionAnalysisContext context) { if (!maybeWindow.isPresent()) { return null; } Window window = maybeWindow.get(); List<Symbol> partitionSymbols = new ArrayList<>(window.getPartitions().size()); for (Expression partition : window.getPartitions()) { Symbol symbol = convert(partition, context); SemanticSortValidator.validate(symbol, "PARTITION BY"); partitionSymbols.add(symbol); } OrderBy orderBy = OrderyByAnalyzer.analyzeSortItems(window.getOrderBy(), sortKey -> { Symbol symbol = convert(sortKey, context); SemanticSortValidator.validate(symbol); return symbol; }); WindowFrameDefinition windowFrameDefinition = WindowDefinition.UNBOUNDED_PRECEDING_CURRENT_ROW; if (window.getWindowFrame().isPresent()) { WindowFrame windowFrame = window.getWindowFrame().get(); FrameBound start = windowFrame.getStart(); FrameBoundDefinition startBound = convertToAnalyzedFrameBound(context, start); FrameBoundDefinition endBound = windowFrame.getEnd() .map(end -> convertToAnalyzedFrameBound(context, end)) .orElse(new FrameBoundDefinition(FrameBound.Type.CURRENT_ROW)); windowFrameDefinition = new WindowFrameDefinition(windowFrame.getType(), startBound, endBound); } return new WindowDefinition(partitionSymbols, orderBy, windowFrameDefinition); }
Source:
public Timeline createTimeline(final Timeline timeline) { try { jdbcTemplate.update( "INSERT INTO zn_data.timeline(" + " tl_id, et_name, tl_order, st_id, tl_topic, " + " tl_created_at, tl_switched_at, tl_cleanup_at, tl_latest_position) " + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb)", timeline.getId(), timeline.getEventType(), timeline.getOrder(), timeline.getStorage().getId(), timeline.getTopic(), timeline.getCreatedAt(), timeline.getSwitchedAt(), timeline.getCleanupAt(), timeline.getLatestPosition() == null ? null : jsonMapper.writer().writeValueAsString(timeline.getLatestPosition())); return timeline; } catch (final JsonProcessingException ex) { throw new IllegalArgumentException("Can not serialize latest position to json", ex); } }

Target:
public Timeline createTimeline(final Timeline timeline) { if (null == timeline.getId()) { throw new IllegalArgumentException("Timeline id can not be null on create (" + timeline + ")"); } try { jdbcTemplate.update( "INSERT INTO zn_data.timeline(" + " tl_id, et_name, tl_order, st_id, tl_topic, " + " tl_created_at, tl_switched_at, tl_cleanup_at, tl_latest_position) " + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?::jsonb)", timeline.getId(), timeline.getEventType(), timeline.getOrder(), timeline.getStorage().getId(), timeline.getTopic(), timeline.getCreatedAt(), timeline.getSwitchedAt(), timeline.getCleanupAt(), timeline.getLatestPosition() == null ? null : jsonMapper.writer().writeValueAsString(timeline.getLatestPosition())); return timeline; } catch (final JsonProcessingException ex) { throw new IllegalArgumentException("Can not serialize latest position to json", ex); } }
Source:
public Iterable<E> getSubgraphContaining(E element) { final Node<E> node = nodes.get(element); if (node != null) { return new SubgraphBuilder<E>(node).build(); } return Collections.emptyList(); }

Target:
public Iterable<E> getSubgraphContaining(E element) { synchronized(nodes) { final Node<E> node = nodes.get(element); if (node != null) { return new SubgraphBuilder<E>(node).build(); } return Collections.emptyList(); } }
Source:
private void addFolderContentsToZip(String srcFolder, ZipOutputStream zip) { File folder = new File(srcFolder); String[] fileList = folder.list(); try { if (fileList != null) { int i = 0; while (true) { if (fileList.length == i) break; if (new File(folder, fileList[i]).isDirectory()) { zip.putNextEntry(new ZipEntry(fileList[i] + File.separator)); zip.closeEntry(); } addToZip("", srcFolder + File.separator + fileList[i], zip); i++; } } } catch (Exception ex) { getLog().error("Error occurred while creating CAR file. " + ex); } }

Target:
private void addFolderContentsToZip(String srcFolder, ZipOutputStream zip) throws ArchiveException { File folder = new File(srcFolder); String[] fileList = folder.list(); if (fileList == null) { return; } try { int i = 0; while (true) { if (fileList.length == i) break; if (new File(folder, fileList[i]).isDirectory()) { zip.putNextEntry(new ZipEntry(fileList[i] + File.separator)); zip.closeEntry(); } addToZip(Constants.EMPTY_STRING, srcFolder + File.separator + fileList[i], zip); i++; } } catch (IOException ex) { throw new ArchiveException(Constants.ARCHIVE_EXCEPTION_MSG, ex); } }
Source:
public void fileMappedWithDeleteOnCloseShouldNotFlushDirtyPagesOnClose() throws Exception { AtomicInteger flushCounter = new AtomicInteger(); PageSwapperFactory swapperFactory = flushCountingPageSwapperFactory( flushCounter ); swapperFactory.open( fs, Configuration.EMPTY ); try ( PageCache cache = createPageCache( swapperFactory, maxPages, PageCacheTracer.NULL, PageCursorTracerSupplier.NULL, EmptyVersionContextSupplier.EMPTY ) ) { File file = file( "a" ); try ( PagedFile pf = cache.map( file, filePageSize, DELETE_ON_CLOSE ); WritableByteChannel channel = pf.openWritableByteChannel() ) { generateFileWithRecords( channel, recordCount, recordSize ); } } assertThat( flushCounter.get(), lessThan( recordCount / recordsPerFilePage ) ); }

Target:
public void fileMappedWithDeleteOnCloseShouldNotFlushDirtyPagesOnClose() throws Exception { AtomicInteger flushCounter = new AtomicInteger(); PageSwapperFactory swapperFactory = flushCountingPageSwapperFactory( flushCounter ); swapperFactory.open( fs, Configuration.EMPTY ); File file = file( "a" ); try ( PageCache cache = createPageCache( swapperFactory, maxPages, PageCacheTracer.NULL, PageCursorTracerSupplier.NULL, EmptyVersionContextSupplier.EMPTY ); PagedFile pf = cache.map( file, filePageSize, DELETE_ON_CLOSE ); WritableByteChannel channel = pf.openWritableByteChannel() ) { generateFileWithRecords( channel, recordCount, recordSize ); } assertThat( flushCounter.get(), lessThan( recordCount / recordsPerFilePage ) ); }
Source:
public <T> List<T> getList(String key, Class<T> type) { for (Config child : children) { if (child.containsKey(key)) { return child.getList(key, type); } } return null; }

Target:
public <T> List<T> getList(String key, Class<T> type) { for (Config child : children) { if (child.containsKey(key)) { return child.getList(key, type); } } return notFound(key); }
Source:
public static MultiPlaceEvent onPlayerMultiBlockPlace(EntityPlayer player, List<BlockSnapshot> blockSnapshots, EnumFacing direction) { BlockSnapshot snap = blockSnapshots.get(0); IBlockState placedAgainst = snap.getWorld().getBlockState(snap.getPos().offset(direction.getOpposite())); MultiPlaceEvent event = new MultiPlaceEvent(blockSnapshots, placedAgainst, player); MinecraftForge.EVENT_BUS.post(event); return event; }

Target:
public static MultiPlaceEvent onPlayerMultiBlockPlace(EntityPlayer player, List<BlockSnapshot> blockSnapshots, EnumFacing direction) { return onPlayerMultiBlockPlace(player, blockSnapshots, direction, null); }
Source:
public void testSerialize() { Set<Property> props = new HashSet<Property>(); Property prop1 = new Property(); prop1.setName("testProp1"); prop1.setValue("testValue1"); prop1.setType(PropertyType.Text); props.add(prop1); Property prop2 = new Property(); prop2.setName("testProp2"); prop2.setValue("testValue2"); prop2.setType(PropertyType.Number); props.add(prop2); SourceInfo si = new SourceInfo(); si.setId("testId"); si.setDuration(500); si.setFragmentId("fragId"); si.setHostAddress("hostAddr"); si.setHostName("hostName"); si.setMultipleConsumers(true); si.setEndpoint(new EndpointRef("sourceUri", "sourceOp", false)); si.setProperties(props); si.setTimestamp(TimeUnit.NANOSECONDS.toMicros(System.nanoTime())); SourceInfo result = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(si); oos.flush(); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = (SourceInfo) ois.readObject(); bais.close(); ois.close(); } catch (Exception e) { e.printStackTrace(); fail("Failed to serialize: " + e); } assertNotNull(result); assertEquals(result, si); }

Target:
public void testSerialize() { Set<Property> props = new HashSet<Property>(); Property prop1 = new Property(); prop1.setName("testProp1"); prop1.setValue("testValue1"); prop1.setType(PropertyType.Text); props.add(prop1); Property prop2 = new Property(); prop2.setName("testProp2"); prop2.setValue("testValue2"); prop2.setType(PropertyType.Number); props.add(prop2); SourceInfo si = new SourceInfo(); si.setId("testId"); si.setDuration(500); si.setFragmentId("fragId"); si.setHostAddress("hostAddr"); si.setHostName("hostName"); si.setMultipleConsumers(true); si.setEndpoint(new EndpointRef("sourceUri", "sourceOp", false)); si.setProperties(props); si.setTimestamp(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())); SourceInfo result = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(si); oos.flush(); oos.close(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = (SourceInfo) ois.readObject(); bais.close(); ois.close(); } catch (Exception e) { e.printStackTrace(); fail("Failed to serialize: " + e); } assertNotNull(result); assertEquals(result, si); }
Source:
public Path decryptAsFile(String filePathOrEncrypted) { Path decryptedFile = getCachedSecretFile(filePathOrEncrypted); if (decryptedFile != null) { return decryptedFile; } String decryptedContents = decrypt(filePathOrEncrypted); if (decryptedContents.equals(filePathOrEncrypted)) { return Paths.get(filePathOrEncrypted); } decryptedFile = decryptedFilePath("tmp", decryptedContents); cacheSecretFile(filePathOrEncrypted, decryptedFile); return decryptedFile; }

Target:
public Path decryptAsFile(String filePathOrEncrypted) { Path decryptedFile = getCachedSecretFile(filePathOrEncrypted); if (decryptedFile != null) { return decryptedFile; } String decryptedContents = decrypt(filePathOrEncrypted); if (StringUtils.equals(decryptedContents, filePathOrEncrypted)) { return Paths.get(filePathOrEncrypted); } decryptedFile = decryptedFilePath("tmp", decryptedContents); cacheSecretFile(filePathOrEncrypted, decryptedFile); return decryptedFile; }
Source:
private Metadata createMetadata(String tableName) { Metadata metadata = new Metadata(); BigtableInstanceName instanceName = this.bigtableOptions.getInstanceName(); if (instanceName != null) { String projectId = this.bigtableOptions.getProjectId(); String instanceId = this.bigtableOptions.getInstanceId(); String tableId = instanceName.toTableId(tableName); metadata.put(GRPC_PARAMS_KEY, String.format("[project_id=%s,instance_id=m%s,table_id=%s]", projectId, instanceId, tableId)); } return metadata; }

Target:
private Metadata createMetadata(String tableName) { Metadata metadata = new Metadata(); if (tableName != null) { metadata.put(GRPC_RESOURCE_PREFIX_KEY, tableName); } return metadata; }
Source:
public void testSweeperFailsHalfwayThroughOnDeleteTable() throws InterruptedException { createTable(SweepStrategy.CONSERVATIVE); putIntoDefaultColumn("foo", "bar", 50); putIntoDefaultColumn("foo2", "bang", 75); putIntoDefaultColumn("foo3", "baz", 100); putIntoDefaultColumn("foo4", "buzz", 125); byte[] nextStartRow = partialSweep(150).getNextStartRow().get(); kvs.dropTable(TABLE_NAME); SweepResults results = sweepRunner.run( TABLE_NAME, ImmutableSweepBatchConfig.builder() .deleteBatchSize(DEFAULT_BATCH_SIZE) .candidateBatchSize(DEFAULT_BATCH_SIZE) .maxCellTsPairsToExamine(DEFAULT_BATCH_SIZE) .build(), nextStartRow); Thread.sleep(1); assertEquals(SweepResults.createEmptySweepResult(Optional.empty()), results); }

Target:
public void testSweeperFailsHalfwayThroughOnDeleteTable() { createTable(SweepStrategy.CONSERVATIVE); putIntoDefaultColumn("foo", "bar", 50); putIntoDefaultColumn("foo2", "bang", 75); putIntoDefaultColumn("foo3", "baz", 100); putIntoDefaultColumn("foo4", "buzz", 125); byte[] nextStartRow = partialSweep(150).getNextStartRow().get(); kvs.dropTable(TABLE_NAME); SweepResults results = sweepRunner.run( TABLE_NAME, ImmutableSweepBatchConfig.builder() .deleteBatchSize(DEFAULT_BATCH_SIZE) .candidateBatchSize(DEFAULT_BATCH_SIZE) .maxCellTsPairsToExamine(DEFAULT_BATCH_SIZE) .build(), nextStartRow); assertEquals(SweepResults.createEmptySweepResult(Optional.empty()), results); }
Source:
public Object clone() throws CloneNotSupportedException { super.clone(); CommandContext ctx = new CommandContext(); ctx.setFromContext(this); return this.duplicate(); }

Target:
public Object clone() { return new CommandContext(this); }
Source:
public ChainedTokenCredential build() { return new ChainedTokenCredential(credentials); }

Target:
public ChainedTokenCredential build() { return new ChainedTokenCredential(new ArrayDeque<>(credentials)); }
Source:
private boolean hasEnoughBytes(ByteBuf in) { if(in.readableBytes() >= this.requiredBytes) { return true; } return false; }

Target:
private boolean hasEnoughBytes(ByteBuf in) { return in.readableBytes() >= requiredBytes; }
Source:
public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: try { getInputStream().available(); } catch (Exception e) { disconnect(); synchronized (this) { this.notify(); } break; } try { if (getInputStream().available() > 0) { synchronized (this) { this.notify(); } } } catch (Exception e) { e.printStackTrace(); } break; } }

Target:
public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: try { getInputStream().available(); } catch (Exception e) { close(); synchronized (this) { this.notify(); } break; } try { if (getInputStream().available() > 0) { synchronized (this) { this.notify(); } } } catch (Exception e) { e.printStackTrace(); } break; } }
Source:
private static boolean isInsecureAlgorithm(String algorithmName) { Matcher matcher = ALGORITHM_PATTERN.matcher(algorithmName); if (matcher.find()) { String algorithm = matcher.group(1); String mode = matcher.group(2); String padding = matcher.group(3); if (mode.equals("ECB")) { return true; } else if (mode.equals("CBC")) { return padding.equals("PKCS5Padding") || padding.equals("PKCS7Padding"); } if (algorithm.equals("RSA")) { return !(padding.equals("OAEPWITHSHA-256ANDMGF1PADDING") || padding.equals("OAEPWithSHA-1AndMGF1Padding")); } return false; } return true; }

Target:
private static boolean isInsecureAlgorithm(String algorithmName) { Matcher matcher = ALGORITHM_PATTERN.matcher(algorithmName); if (matcher.matches()) { String algorithm = matcher.group(1); String mode = matcher.group(2); String padding = matcher.group(3); if ("ECB".equals(mode)) { return true; } else if ("CBC".equals(mode)) { return "PKCS5Padding".equals(padding) || "PKCS7Padding".equals(padding); } if ("RSA".equals(algorithm)) { return !("OAEPWITHSHA-256ANDMGF1PADDING".equals(padding) || "OAEPWithSHA-1AndMGF1Padding".equals(padding)); } return false; } return true; }
Source:
public void buildOrgUnitProgramRelation(OrganisationUnitExtended sdkOrganisationUnitExtended) { OrgUnitDB appOrgUnit = sdkOrganisationUnitExtended.getAppOrgUnit(); Log.d(TAG, "buildOrgUnitProgramRelation " + appOrgUnit.getName()); for (ProgramExtended sdkProgramExtended : ProgramExtended.getExtendedList( SdkQueries.getProgramsForOrganisationUnit(appOrgUnit.getUid(), ProgramType.WITHOUT_REGISTRATION))) { if(sdkProgramExtended.isValidProgram()) { sdkProgramExtended.setAppProgram( programMapObjects.get(sdkProgramExtended.getUid())); addOrgUnitProgramRelation(sdkOrganisationUnitExtended, sdkProgramExtended); } } }

Target:
public void buildOrgUnitProgramRelation(OrganisationUnitExtended sdkOrganisationUnitExtended) { OrgUnitDB appOrgUnit = sdkOrganisationUnitExtended.getAppOrgUnit(); Log.d(TAG, "buildOrgUnitProgramRelation " + appOrgUnit.getName()); for (ProgramExtended sdkProgramExtended : ProgramExtended.getExtendedList( SdkQueries.getProgramsForOrganisationUnit(appOrgUnit.getUid(), PreferencesState.getInstance().getContext().getString(R.string.pull_program_code, ProgramType.WITHOUT_REGISTRATION), ProgramType.WITHOUT_REGISTRATION))) { sdkProgramExtended.setAppProgram( programMapObjects.get(sdkProgramExtended.getUid())); addOrgUnitProgramRelation(sdkOrganisationUnitExtended, sdkProgramExtended); } }
Source:
private static StageExecutionPlan createPlan(ConnectorSplitSource splitSource) { Symbol symbol = new Symbol("column"); PlanNodeId tableScanNodeId = new PlanNodeId("plan_id"); TableScanNode tableScan = new TableScanNode( tableScanNodeId, new TableHandle(CONNECTOR_ID, new TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); RemoteSourceNode remote = new RemoteSourceNode(new PlanNodeId("remote_id"), new PlanFragmentId("plan_fragment_id"), ImmutableList.of()); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("plan_id"), new JoinNode(new PlanNodeId("join_id"), INNER, tableScan, remote, ImmutableList.of(), ImmutableList.<Symbol>builder() .addAll(tableScan.getOutputSymbols()) .addAll(remote.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(JoinNode.DistributionType.PARTITIONED)), ImmutableMap.of(symbol, VARCHAR), SOURCE_DISTRIBUTION, ImmutableList.of(tableScanNodeId), new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), ImmutableList.of(symbol))); return new StageExecutionPlan( testFragment, ImmutableMap.of(tableScanNodeId, new ConnectorAwareSplitSource(CONNECTOR_ID, TestingTransactionHandle.create(), splitSource, SplitSchedulingStrategy.ALL_AT_ONCE)), ImmutableList.of()); }

Target:
private static StageExecutionPlan createPlan(ConnectorSplitSource splitSource) { Symbol symbol = new Symbol("column"); PlanNodeId tableScanNodeId = new PlanNodeId("plan_id"); TableScanNode tableScan = new TableScanNode( tableScanNodeId, new TableHandle(CONNECTOR_ID, new TestingTableHandle()), ImmutableList.of(symbol), ImmutableMap.of(symbol, new TestingColumnHandle("column")), Optional.empty(), TupleDomain.all(), null); RemoteSourceNode remote = new RemoteSourceNode(new PlanNodeId("remote_id"), new PlanFragmentId("plan_fragment_id"), ImmutableList.of()); PlanFragment testFragment = new PlanFragment( new PlanFragmentId("plan_id"), new JoinNode(new PlanNodeId("join_id"), INNER, tableScan, remote, ImmutableList.of(), ImmutableList.<Symbol>builder() .addAll(tableScan.getOutputSymbols()) .addAll(remote.getOutputSymbols()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(JoinNode.DistributionType.PARTITIONED)), ImmutableMap.of(symbol, VARCHAR), SOURCE_DISTRIBUTION, ImmutableList.of(tableScanNodeId), new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), ImmutableList.of(symbol)), UNGROUPED_EXECUTION); return new StageExecutionPlan( testFragment, ImmutableMap.of(tableScanNodeId, new ConnectorAwareSplitSource(CONNECTOR_ID, TestingTransactionHandle.create(), splitSource, UNGROUPED_SCHEDULING)), ImmutableList.of()); }
Source:
Set<Status> syncableStates() { return EnumSet.of( Status.AVAILABLE, Status.UPDATE_FAILED, Status.ENABLE_SECURITY_FAILED, Status.START_FAILED, Status.STOPPED, Status.STOP_FAILED, Status.AMBIGUOUS, Status.BACKUP_FINISHED, Status.RESTORE_FINISHED ); }

Target:
Set<Status> syncableStates() { return EnumSet.of( Status.AVAILABLE, Status.UPDATE_FAILED, Status.ENABLE_SECURITY_FAILED, Status.START_FAILED, Status.STOPPED, Status.STOP_FAILED, Status.AMBIGUOUS, Status.RESTORE_FAILED, Status.BACKUP_FAILED, Status.BACKUP_FINISHED, Status.RESTORE_FINISHED ); }
Source:
GdkColor getContextBackground () { long fontHandle = fontHandle (); long context = OS.gtk_widget_get_style_context (fontHandle); long styleState = OS.gtk_widget_get_state_flags(handle); GdkRGBA rgba = new GdkRGBA (); OS.gtk_style_context_get_background_color (context, (int)styleState, rgba); if (rgba.alpha == 0) { return display.COLOR_WIDGET_BACKGROUND; } GdkColor color = new GdkColor (); color.red = (short)(rgba.red * 0xFFFF); color.green = (short)(rgba.green * 0xFFFF); color.blue = (short)(rgba.blue * 0xFFFF); return color; }

Target:
GdkColor getContextBackground () { long fontHandle = fontHandle (); long context = OS.gtk_widget_get_style_context (fontHandle); int styleState = OS.gtk_widget_get_state_flags(handle); GdkRGBA rgba = new GdkRGBA (); OS.gtk_style_context_get_background_color (context, styleState, rgba); if (rgba.alpha == 0) { return display.COLOR_WIDGET_BACKGROUND; } GdkColor color = new GdkColor (); color.red = (short)(rgba.red * 0xFFFF); color.green = (short)(rgba.green * 0xFFFF); color.blue = (short)(rgba.blue * 0xFFFF); return color; }
Source:
private Answer executeRequest(SyncDomainCommand cmd) { try { isNuageVspManagerLoaded(); boolean success = _nuageVspManagerClient.syncDomainWithNuageVsp(cmd.getDomainUuid(), cmd.getDomainName(), cmd.getDomainPath(), cmd.isToAdd(), cmd.isToRemove()); return new SyncDomainAnswer(success); } catch (Exception e) { return new SyncDomainAnswer(false); } }

Target:
private Answer executeRequest(SyncDomainCommand cmd) { try { isNuageVspManagerLoaded(); boolean success = _nuageVspManagerClient.syncDomainWithNuageVsp(cmd.getDomainUuid(), cmd.getDomainName(), cmd.getDomainPath(), cmd.isToAdd(), cmd.isToRemove()); return new SyncDomainAnswer(success); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e); return new SyncDomainAnswer(false); } }
Source:
public FlexmarkParser() { MutableDataSet options = new MutableDataSet(); options.set(Parser.EXTENSIONS, Arrays.asList(StrikethroughExtension.create(), TablesExtension.create(), GitLabExtension.create(), UMLExtension.create(), AutolinkExtension.create(), WikiLinkExtension.create(), TypographicExtension.create())); options.set(HtmlRenderer.SOFT_BREAK, "<br />\n"); parser = Parser.builder(options).build(); renderer = HtmlRenderer.builder(options).build(); }

Target:
public FlexmarkParser() { MutableDataSet options = new MutableDataSet(); options.set(Parser.EXTENSIONS, Arrays.asList(StrikethroughExtension.create(), TablesExtension.create(), UMLExtension.create(), AutolinkExtension.create(), WikiLinkExtension.create(), TypographicExtension.create())); options.set(HtmlRenderer.SOFT_BREAK, "<br />\n"); parser = Parser.builder(options).build(); renderer = HtmlRenderer.builder(options).build(); }
Source:
private static HashMap<Integer, Long> getIdToDateMap(Vector<Integer> ids, SqlStorage<FormRecord> storage) { HashMap<Integer, Long> idToDateIndex = new HashMap<>(); for (int id : ids) { String dateAsString = storage.getMetaDataFieldForRecord(id, FormRecord.META_LAST_MODIFIED); long dateAsSeconds; try { dateAsSeconds = Long.valueOf(dateAsString); } catch (NumberFormatException e) { idToDateIndex.put(id, (long)id); continue; } idToDateIndex.put(id, dateAsSeconds); } return idToDateIndex; }

Target:
private static HashMap<Integer, Long> getIdToDateMap(Vector<Integer> ids, SqlStorage<FormRecord> storage) { HashMap<Integer, Long> idToDateIndex = new HashMap<>(); for (int id : ids) { String dateAsString = storage.getMetaDataFieldForRecord(id, FormRecord.META_LAST_MODIFIED); long dateAsSeconds; try { dateAsSeconds = Long.valueOf(dateAsString); } catch (NumberFormatException e) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Invalid date in last modified value: " + dateAsString); idToDateIndex.put(id, (long)id); continue; } idToDateIndex.put(id, dateAsSeconds); } return idToDateIndex; }
Source:
public void panelRenameButton_onClick_panelGetsSelected() { int count = panels.getPanelCount(); while (count-- > 1) { pushKeys(CLOSE_PANEL); } click("#dummy/dummy_col0_renameButton"); assertEquals(Optional.of(0), panels.getCurrentlySelectedPanel()); pushKeys(CREATE_RIGHT_PANEL); click("#dummy/dummy_col1_renameButton"); assertEquals(Optional.of(1), panels.getCurrentlySelectedPanel()); pushKeys(CLOSE_PANEL); pushKeys(KeyCode.ESCAPE); }

Target:
public void panelRenameButton_onClick_panelGetsSelected() { click(IdGenerator.getOcticonButtonIdReference(0, "renameButton")); assertEquals(Optional.of(0), panels.getCurrentlySelectedPanel()); pushKeys(CREATE_RIGHT_PANEL); click(IdGenerator.getOcticonButtonIdReference(1, "renameButton")); assertEquals(Optional.of(1), panels.getCurrentlySelectedPanel()); pushKeys(CLOSE_PANEL); pushKeys(KeyCode.ESCAPE); sleep(EVENT_DELAY); }
Source:
private Map<String, Map<String, ConfigParameterInfo>> getPluginConfig( ProjectState project, DynamicMap<ProjectConfigEntry> pluginConfigEntries, PluginConfigFactory cfgFactory) { TreeMap<String, Map<String, ConfigParameterInfo>> pluginConfig = new TreeMap<>(); for (Entry<ProjectConfigEntry> e : pluginConfigEntries) { PluginConfig cfg = cfgFactory.getFromProjectConfig(project, e.getPluginName()); ProjectConfigEntry configEntry = e.getProvider().get(); ConfigParameterInfo p = new ConfigParameterInfo(); p.displayName = configEntry.getDisplayName(); p.type = configEntry.getType(); p.value = cfg.getString(e.getExportName(), configEntry.getDefaultValue()); Map<String, ConfigParameterInfo> pc = pluginConfig.get(e.getPluginName()); if (pc == null) { pc = new TreeMap<>(); pluginConfig.put(e.getPluginName(), pc); } pc.put(e.getExportName(), p); } return pluginConfig; }

Target:
private Map<String, Map<String, ConfigParameterInfo>> getPluginConfig( ProjectState project, DynamicMap<ProjectConfigEntry> pluginConfigEntries, PluginConfigFactory cfgFactory) { TreeMap<String, Map<String, ConfigParameterInfo>> pluginConfig = new TreeMap<>(); for (Entry<ProjectConfigEntry> e : pluginConfigEntries) { PluginConfig cfg = cfgFactory.getFromProjectConfig(project, e.getPluginName()); ProjectConfigEntry configEntry = e.getProvider().get(); ConfigParameterInfo p = new ConfigParameterInfo(); p.displayName = configEntry.getDisplayName(); p.type = configEntry.getType(); p.value = cfg.getString(e.getExportName(), configEntry.getDefaultValue()); Map<String, ConfigParameterInfo> pc = pluginConfig.get(e.getPluginName()); if (pc == null) { pc = new TreeMap<>(); pluginConfig.put(e.getPluginName(), pc); } pc.put(e.getExportName(), p); } return !pluginConfig.isEmpty() ? pluginConfig : null; }
Source:
private EntityImportReport importVcf(Repository<Entity> inRepository, List<EntityType> addedEntities, Package importPackage) throws IOException { EntityImportReport report = new EntityImportReport(); String entityTypeId = inRepository.getName(); if (runAsSystem(() -> dataService.hasRepository(entityTypeId))) { throw new MolgenisDataException("Can't overwrite existing " + entityTypeId); } EntityType entityType = inRepository.getEntityType(); entityType.setBackend(metaDataService.getDefaultBackend().getName()); entityType.setPackage(importPackage); Repository<Entity> sampleRepository = createSampleRepository(addedEntities, entityType, importPackage); try (Repository<Entity> outRepository = dataService.getMeta().createRepository(entityType)) { permissionSystemService.giveUserWriteMetaPermissions(entityType); addedEntities.add(entityType); if (sampleRepository != null) { int sampleEntityCount = addSampleEntities(sampleRepository, inRepository); report.addNewEntity(sampleRepository.getName()); if (sampleEntityCount > 0) { report.addEntityCount(sampleRepository.getName(), sampleEntityCount); } } AtomicInteger vcfEntityCount = new AtomicInteger(); inRepository.forEachBatched(rowBatch -> { outRepository.add(rowBatch.stream()); vcfEntityCount.addAndGet(rowBatch.size()); }, 1000); if (vcfEntityCount.get() > 0) { report.addEntityCount(entityTypeId, vcfEntityCount.get()); } } report.addNewEntity(entityTypeId); return report; }

Target:
private EntityImportReport importVcf(Repository<Entity> inRepository, List<EntityType> addedEntities, Package importPackage) throws IOException { EntityImportReport report = new EntityImportReport(); String entityTypeId = inRepository.getName(); if (runAsSystem(() -> dataService.hasRepository(entityTypeId))) { throw new MolgenisDataException("Can't overwrite existing " + entityTypeId); } EntityType entityType = inRepository.getEntityType(); entityType.setBackend(metaDataService.getDefaultBackend().getName()); entityType.setPackage(importPackage); Repository<Entity> sampleRepository = createSampleRepository(addedEntities, entityType, importPackage); try (Repository<Entity> outRepository = dataService.getMeta().createRepository(entityType)) { permissionSystemService.giveUserWriteMetaPermissions(entityType); addedEntities.add(entityType); if (sampleRepository != null) { int sampleEntityCount = addSampleEntities(sampleRepository, inRepository); report.addNewEntity(sampleRepository.getName()); if (sampleEntityCount > 0) { report.addEntityCount(sampleRepository.getName(), sampleEntityCount); } } AtomicInteger vcfEntityCount = new AtomicInteger(); inRepository.forEachBatched(rowBatch -> { outRepository.add(rowBatch.stream()); vcfEntityCount.addAndGet(rowBatch.size()); }, VcfRepository.BATCH_SIZE); if (vcfEntityCount.get() > 0) { report.addEntityCount(entityTypeId, vcfEntityCount.get()); } } report.addNewEntity(entityTypeId); return report; }
Source:
public void run(Definition definition) throws IOException { LatexBackend latexBackend = new LatexBackend(sw, context); latexBackend.compile(definition); File latexFile = latexBackend.getLatexFile(); File pdfFile = generatePdf(latexFile); if (pdfFile.exists()) { copyFile(pdfFile, options.output()); } }

Target:
public void run(Definition definition) throws IOException { LatexBackend latexBackend = new LatexBackend(sw, context); latexBackend.compile(definition); File latexFile = latexBackend.getLatexFile(); File pdfFile = generatePdf(latexFile); if (pdfFile.exists()) { copyFile(pdfFile, new File(options.directory, FilenameUtils.removeExtension(new File(definition.getMainFile()).getName()) + ".pdf")); } }
Source:
private static Index genIndex(SqlKind type, Table t, String indexName, String constraintName, boolean hasGeog, List<Column> indexCols, List<AbstractExpression> exprs) { final Index index = t.getIndexes().add(indexName); if (hasGeog) { index.setCountable(false); index.setType(IndexType.COVERING_CELL_INDEX.getValue()); } else { index.setCountable(true); index.setType(IndexType.BALANCED_TREE.getValue()); } index.setUnique(true); index.setAssumeunique(type == SqlKind.ASSUME_UNIQUE); updateConstraint(t.getConstraints().add(constraintName), index, type, constraintName, t.getTypeName()); AtomicInteger i = new AtomicInteger(0); indexCols.forEach(column -> { final ColumnRef cref = index.getColumns().add(column.getName()); cref.setColumn(column); cref.setIndex(i.getAndIncrement()); }); if (! exprs.isEmpty()) { try { index.setExpressionsjson(DDLCompiler.convertToJSONArray(exprs)); } catch (JSONException e) { throw new PlanningErrorException(String.format( "Unexpected error serializing non-column expressions for index '%s' on type '%s': %s", indexName, t.getTypeName(), e.toString())); } } final AbstractExpression.UnsafeOperatorsForDDL unsafeOp = new AbstractExpression.UnsafeOperatorsForDDL(); exprs.forEach(expr -> expr.findUnsafeOperatorsForDDL(unsafeOp)); index.setIssafewithnonemptysources(! unsafeOp.isUnsafe()); return index; }

Target:
private static Index genIndex(SqlKind type, Table t, String indexName, String constraintName, boolean hasGeog, List<Column> indexCols, List<AbstractExpression> exprs) { final Index index = t.getIndexes().add(indexName); if (hasGeog) { index.setCountable(false); index.setType(IndexType.COVERING_CELL_INDEX.getValue()); } else { index.setCountable(true); index.setType(IndexType.BALANCED_TREE.getValue()); } index.setUnique(true); index.setAssumeunique(type == SqlKind.ASSUME_UNIQUE); setConstraintType(t.getConstraints().add(constraintName), index, type, constraintName, t.getTypeName()); AtomicInteger i = new AtomicInteger(0); indexCols.forEach(column -> { final ColumnRef cref = index.getColumns().add(column.getName()); cref.setColumn(column); cref.setIndex(i.getAndIncrement()); }); if (! exprs.isEmpty()) { try { index.setExpressionsjson(DDLCompiler.convertToJSONArray(exprs)); } catch (JSONException e) { except(String.format( "Unexpected error serializing non-column expressions for index '%s' on type '%s': %s", indexName, t.getTypeName(), e.toString())); } } final AbstractExpression.UnsafeOperatorsForDDL unsafeOp = new AbstractExpression.UnsafeOperatorsForDDL(); exprs.forEach(expr -> expr.findUnsafeOperatorsForDDL(unsafeOp)); index.setIssafewithnonemptysources(! unsafeOp.isUnsafe()); return index; }
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { List<String> fields = hint.getIndex().stream().map(EsHint.FieldHint::getField).collect(Collectors.toList()); Object[] values = (Object[]) value; if (fields.size() != values.length) { throw new IllegalArgumentException("fields size and values length should be the same"); } Map<String, Object> mapValueByField = IntStream.range(0, fields.size()) .boxed() .collect(Collectors.toMap(index -> fields.get(index), index -> values[index])); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); mapValueByField.entrySet() .forEach(entry -> boolQueryBuilder.must( QueryBuilders.termQuery(entry.getKey(), entry.getValue()))); return QueryBuilders.nestedQuery("files:files.file", boolQueryBuilder, ScoreMode.None); }

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { List<String> fields = hint.getIndex().stream().map(EsHint.FieldHint::getField).collect(Collectors.toList()); Object[] values = (Object[]) value; if (fields.size() != values.length) { throw new NuxeoException("Fields size and values length should be the same", SC_BAD_REQUEST); } BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); for (int index = 0; index < values.length; index++) { boolQueryBuilder.must(QueryBuilders.termQuery(fields.get(index), values[index])); } return QueryBuilders.nestedQuery("files:files.file", boolQueryBuilder, ScoreMode.None); }
Source:
public int hashCode() { return playerPrivateCertificate.hashCode() ^ playerPrivateCertificate.hashCode(); }

Target:
public int hashCode() { return Objects.hash(playerPublicCertificate, playerPrivateCertificate); }
Source:
public FilteredCheckboxTree(Composite parent, int treeStyle, PatternFilter filter, boolean useNewLook) { super(parent, treeStyle, filter, useNewLook); }

Target:
public FilteredCheckboxTree(Composite parent, int treeStyle, PatternFilter filter, boolean useNewLook) { this(parent, treeStyle, filter, useNewLook, false); }
Source:
public static OAuth2Code deserializeCode(Map<String, String> data) { return new OAuth2Code(data); }

Target:
public static final OAuth2Code deserializeCode(Map<String, String> data) { return new OAuth2Code(data); }
Source:
public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(true); addFastViews(layout); addViewShortcuts(layout); addPerspectiveShortcuts(layout); IFolderLayout topLeftFolder = layout.createFolder( "topLeftFolder", IPageLayout.LEFT, 0.15f, IPageLayout.ID_EDITOR_AREA); topLeftFolder.addView(PROJECT_VIEW_ID); IFolderLayout topFolders[] = new IFolderLayout[3]; topFolders[0]= layout.createFolder( "topFolder1", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[0].addView(CPU_VIEW_ID); topFolders[1] = layout.createFolder( "topFolder2", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[1].addView(DISK_VIEW_ID); topFolders[2] = layout.createFolder( "topFolders3", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[2].addView(MEMORY_VIEW_ID); IFolderLayout bottomRightFolder = layout.createFolder( "bottomRightFolder", IPageLayout.BOTTOM, 0.50f, IPageLayout.ID_EDITOR_AREA); bottomRightFolder.addView(HISTOGRAM_VIEW_ID); bottomRightFolder.addView(BOOKMARKS_VIEW_ID); layout.addNewWizardShortcut(NewTmfProjectWizard.ID); }

Target:
public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(true); IFolderLayout topLeftFolder = layout.createFolder( "topLeftFolder", IPageLayout.LEFT, 0.15f, IPageLayout.ID_EDITOR_AREA); topLeftFolder.addView(PROJECT_VIEW_ID); IFolderLayout topFolders[] = new IFolderLayout[3]; topFolders[0] = layout.createFolder( "topFolder1", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[0].addView(CPU_VIEW_ID); topFolders[1] = layout.createFolder( "topFolder2", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[1].addView(DISK_VIEW_ID); topFolders[2] = layout.createFolder( "topFolders3", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[2].addView(MEMORY_VIEW_ID); IFolderLayout bottomRightFolder = layout.createFolder( "bottomRightFolder", IPageLayout.BOTTOM, 0.50f, IPageLayout.ID_EDITOR_AREA); bottomRightFolder.addView(HISTOGRAM_VIEW_ID); bottomRightFolder.addView(BOOKMARKS_VIEW_ID); layout.addNewWizardShortcut(NewTmfProjectWizard.ID); }
Source:
private LogoutRequest signLogoutRequest(LogoutRequest logoutRequest) throws SignatureException, WSSecurityException, XMLStreamException { new SimpleSign(systemCrypto).signSamlObject(logoutRequest); Element reqElem = logoutMessage.getElementFromSaml(logoutRequest); String foo = DOM2Writer.nodeToString(reqElem); final Document responseDoc = StaxUtils.read(new ByteArrayInputStream(foo.getBytes(StandardCharsets.UTF_8))); return (LogoutRequest) OpenSAMLUtil.fromDom(responseDoc.getDocumentElement()); }

Target:
private LogoutRequest signLogoutRequest(LogoutRequest logoutRequest) throws SignatureException, WSSecurityException, XMLStreamException { new SimpleSign(systemCrypto).signSamlObject(logoutRequest); Element reqElem = logoutMessage.getElementFromSaml(logoutRequest); String nodeString = DOM2Writer.nodeToString(reqElem); final Document responseDoc = StaxUtils.read(new ByteArrayInputStream(nodeString.getBytes(StandardCharsets.UTF_8))); return (LogoutRequest) OpenSAMLUtil.fromDom(responseDoc.getDocumentElement()); }
Source:
public void testGETOperation() { System.setProperty(RESTWorkItemHandler.USE_SYSTEM_PROPERTIES, "true"); RESTWorkItemHandler handler = new RESTWorkItemHandler(USERNAME, PASSWORD); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("Url", SERVER_URL); workItem.setParameter("Method", "GET"); WorkItemManager manager = new TestWorkItemManager(workItem); handler.executeWorkItem(workItem, manager); String result = (String) workItem.getResult("Result"); assertNotNull("result cannot be null", result); assertEquals("Hello from REST", result); int responseCode = (Integer) workItem.getResult("Status"); assertNotNull(responseCode); assertEquals(200, responseCode); String responseMsg = (String) workItem.getResult("StatusMsg"); assertNotNull(responseMsg); assertEquals("request to endpoint " + workItem.getParameter("Url") + " successfully completed OK", responseMsg); }

Target:
public void testGETOperation() { RESTWorkItemHandler handler = new RESTWorkItemHandler(USERNAME, PASSWORD); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("Url", SERVER_URL); workItem.setParameter("Method", "GET"); WorkItemManager manager = new TestWorkItemManager(workItem); handler.executeWorkItem(workItem, manager); String result = (String) workItem.getResult("Result"); assertNotNull("result cannot be null", result); assertEquals("Hello from REST", result); int responseCode = (Integer) workItem.getResult("Status"); assertNotNull(responseCode); assertEquals(200, responseCode); String responseMsg = (String) workItem.getResult("StatusMsg"); assertNotNull(responseMsg); assertEquals("request to endpoint " + workItem.getParameter("Url") + " successfully completed OK", responseMsg); }
Source:
public Set<EventClass> registeredEventClasses() { return registry().registeredMessageClasses(); }

Target:
public final Set<EventClass> registeredEventClasses() { return registry().registeredMessageClasses(); }
Source:
public String getInstructorCourseInstructorDeleteLink(String courseId, String instructorEmail) { String link = Const.ActionURIs.INSTRUCTOR_COURSE_INSTRUCTOR_DELETE; link = Url.addParamToUrl(link,Const.ParamsNames.COURSE_ID, courseId); link = Url.addParamToUrl(link,Const.ParamsNames.INSTRUCTOR_EMAIL, instructorEmail); link = addUserIdToUrl(link); return link; }

Target:
private String getInstructorCourseInstructorDeleteLink(String courseId, String instructorEmail) { String link = Const.ActionURIs.INSTRUCTOR_COURSE_INSTRUCTOR_DELETE; link = Url.addParamToUrl(link,Const.ParamsNames.COURSE_ID, courseId); link = Url.addParamToUrl(link,Const.ParamsNames.INSTRUCTOR_EMAIL, instructorEmail); link = addUserIdToUrl(link); return link; }
Source:
private void saveTagToDataBase() { final List <TagDto> list = new ArrayList<TagDto>(); list.addAll(gridStorageR.getStore().getAll()); SessionDataService.Async.getInstance().saveTags(currentSession.getId(), list, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { new ExceptionPanel("Fail to save data : " + caught.getMessage()); } @Override public void onSuccess(Void result) { currentSession.getTags().clear(); currentSession.setTags(list); String tags = ""; for (int i = 0; i < currentSession.getTags().size(); i++) { tags += currentSession.getTags().get(i).getName() + " "; } currentTreeItem.put(getText(), tags); treeGrid.getTreeView().refresh(false); } }); }

Target:
private void saveTagToDataBase() { final List <TagDto> list = new ArrayList<TagDto>(); list.addAll(gridStorageR.getStore().getAll()); SessionDataService.Async.getInstance().saveTags(currentSession.getId(), list, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { atClose(); new ExceptionPanel("Fail to save into DB session's tags : " + caught.getMessage()); } @Override public void onSuccess(Void result) { currentSession.getTags().clear(); currentSession.setTags(list); String tags = ""; for (TagDto tagDto: currentSession.getTags()) { tags += tagDto.getName() + " "; } currentTreeItem.put(getText(), tags); treeGrid.getTreeView().refresh(false); atClose(); } }); }
Source:
public void upgradeContainer(final ContainerSpecKey containerSpecKey, ReleaseId releaseId) { ServerTemplate serverTemplate = templateStorage.load(containerSpecKey.getServerTemplateKey().getId()); if (serverTemplate == null) { throw new RuntimeException("No server template found for id " + containerSpecKey.getServerTemplateKey().getId()); } org.kie.server.controller.api.model.spec.ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerSpecKey.getId()); if (releaseId.getGroupId() == null) { releaseId.setGroupId(containerSpec.getReleasedId().getGroupId()); } if (releaseId.getArtifactId()== null) { releaseId.setArtifactId(containerSpec.getReleasedId().getArtifactId()); } ((ContainerSpec)containerSpec).setReleasedId(releaseId); templateStorage.update(serverTemplate); List<Container> containers = kieServerInstanceManager.upgradeContainer(serverTemplate, containerSpec); notificationService.notify(serverTemplate, containerSpec, containers); }

Target:
public void upgradeContainer(final ContainerSpecKey containerSpecKey, ReleaseId releaseId) { ServerTemplate serverTemplate = templateStorage.load(containerSpecKey.getServerTemplateKey().getId()); if (serverTemplate == null) { throw new RuntimeException("No server template found for id " + containerSpecKey.getServerTemplateKey().getId()); } ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerSpecKey.getId()); if (releaseId.getGroupId() == null) { releaseId.setGroupId(containerSpec.getReleasedId().getGroupId()); } if (releaseId.getArtifactId()== null) { releaseId.setArtifactId(containerSpec.getReleasedId().getArtifactId()); } containerSpec.setReleasedId(releaseId); templateStorage.update(serverTemplate); List<Container> containers = kieServerInstanceManager.upgradeContainer(serverTemplate, containerSpec); notificationService.notify(serverTemplate, containerSpec, containers); }
Source:
public void runInternal() throws ExecutionException, InterruptedException, TimeoutException, JsonProcessingException { possiblyRegisterListener(); stateManager.setStateIfNoSuccessfulRunYet(SeekableStreamSupervisorStateManager.State.CONNECTING_TO_STREAM); updatePartitionDataFromStream(); stateManager.setStateIfNoSuccessfulRunYet(SeekableStreamSupervisorStateManager.State.DISCOVERING_INITIAL_TASKS); discoverTasks(); updateTaskStatus(); checkTaskDuration(); checkPendingCompletionTasks(); checkCurrentTaskState(); if (!spec.isSuspended()) { log.info("[%s] supervisor is running.", dataSource); stateManager.setStateIfNoSuccessfulRunYet(SeekableStreamSupervisorStateManager.State.CREATING_TASKS); createNewTasks(); stateManager.setStateIfNoSuccessfulRunYet(SeekableStreamSupervisorStateManager.State.RUNNING); } else { log.info("[%s] supervisor is suspended.", dataSource); gracefulShutdownInternal(); stateManager.setState(SeekableStreamSupervisorStateManager.State.SUSPENDED); } if (log.isDebugEnabled()) { log.debug(generateReport(true).toString()); } else { log.info(generateReport(false).toString()); } stateManager.markRunFinishedAndEvaluateHealth(); }

Target:
public void runInternal() { try { possiblyRegisterListener(); stateManager.maybeSetState(SeekableStreamSupervisorStateManager.SeekableStreamState.CONNECTING_TO_STREAM); if (!updatePartitionDataFromStream() && !stateManager.isAtLeastOneSuccessfulRun()) { return; } stateManager.maybeSetState(SeekableStreamSupervisorStateManager.SeekableStreamState.DISCOVERING_INITIAL_TASKS); discoverTasks(); updateTaskStatus(); checkTaskDuration(); checkPendingCompletionTasks(); checkCurrentTaskState(); if (!spec.isSuspended()) { log.info("[%s] supervisor is running.", dataSource); stateManager.maybeSetState(SeekableStreamSupervisorStateManager.SeekableStreamState.CREATING_TASKS); createNewTasks(); } else { log.info("[%s] supervisor is suspended.", dataSource); gracefulShutdownInternal(); } if (log.isDebugEnabled()) { log.debug(generateReport(true).toString()); } else { log.info(generateReport(false).toString()); } } catch (Exception e) { stateManager.recordThrowableEvent(e); log.warn(e, "Exception in supervisor run loop for dataSource [%s]", dataSource); } finally { stateManager.markRunFinished(); } }