auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onLeash(PlayerLeashEntityEvent e) { if (!isEnabled()) { return; } Player p = (Player)e.getPlayer(); ItemStack item = p.getInventory().getItemInMainHand(); SlimefunItem slimeItem = SlimefunItem.getByItem(item); if (slimeItem instanceof GrapplingHook) { e.setCancelled(true); } }

Target:
public void onLeash(PlayerLeashEntityEvent e) { if (!isEnabled()) { return; } Player p = e.getPlayer(); ItemStack item = p.getInventory().getItemInMainHand(); SlimefunItem slimeItem = SlimefunItem.getByItem(item); if (slimeItem instanceof GrapplingHook) { e.setCancelled(true); } }
Source:
public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); }

Target:
public Mono<Void> cancelScheduledMessages(Iterable<Long> sequenceNumbers, String associatedLinkName) { return isAuthorized(ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE) .then(createChannel.flatMap(channel -> { final Message requestMessage = createManagementMessage( ManagementConstants.OPERATION_CANCEL_SCHEDULED_MESSAGE, associatedLinkName); final List<Long> numbers = new ArrayList<>(); sequenceNumbers.forEach(s -> numbers.add(s)); final Long[] longs = numbers.toArray(new Long[0]); requestMessage.setBody(new AmqpValue(Collections.singletonMap(ManagementConstants.SEQUENCE_NUMBERS, longs))); return sendWithVerify(channel, requestMessage, null); })).then(); }
Source:
public <E extends Exception> boolean suppressed(Class<E> type) { return Arrays.stream(getSuppressed()).map(type::isInstance).anyMatch(x -> x); }

Target:
public <E extends Exception> boolean suppressed(Class<E> type) { return Arrays.stream(getSuppressed()).anyMatch(type::isInstance); }
Source:
private void doStart() throws Exception { Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); FilePath workspace = getContext().get(FilePath.class); Launcher launcher = getContext().get(Launcher.class); Map<String,String> overrides = new LinkedHashMap<>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<>(); for (MultiBinding<?> binding : step.bindings) { if (binding.getDescriptor().requiresWorkspace() && (workspace == null || launcher == null)) { throw new MissingContextVariableException(FilePath.class); } MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); } if (!overrides.isEmpty()) { boolean unix = launcher != null ? launcher.isUnix() : true; listener.getLogger().println("Masking exact matches of " + overrides.keySet().stream().map( v -> unix ? "$" + v : "%" + v + "%" ).collect(Collectors.joining(" or "))); } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback2(unbinders)). start(); }

Target:
private void doStart() throws Exception { Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); FilePath workspace = getContext().get(FilePath.class); Launcher launcher = getContext().get(Launcher.class); Map<String,String> overrides = new LinkedHashMap<>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<>(); for (MultiBinding<?> binding : step.bindings) { if (binding.getDescriptor().requiresWorkspace() && (workspace == null || launcher == null)) { throw new MissingContextVariableException(FilePath.class); } MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); } if (!overrides.isEmpty()) { boolean unix = launcher != null ? launcher.isUnix() : true; listener.getLogger().println("Masking only exact matches of " + overrides.keySet().stream().map( v -> unix ? "$" + v : "%" + v + "%" ).collect(Collectors.joining(" or "))); } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback2(unbinders)). start(); }
Source:
public Throwable cause() { Object result = this.result; if (result == CANCELLATION_CAUSE_HOLDER) { throw new LeanCancellationException(); } return (result instanceof CauseHolder) ? ((CauseHolder) result).cause : null; }

Target:
public Throwable cause() { Object result = this.result; if (result != CANCELLATION_CAUSE_HOLDER) { return (result instanceof CauseHolder) ? ((CauseHolder) result).cause : null; } CancellationException ce = new LeanCancellationException(); if (RESULT_UPDATER.compareAndSet(this, CANCELLATION_CAUSE_HOLDER, new CauseHolder(ce))) { return ce; } return ((CauseHolder) this.result).cause; }
Source:
protected void processOldImageFromDb() { updateOldImageActive(Snapshot.SnapshotType.PREVIEW, false); }

Target:
protected void processOldImageFromDb() { updateOldImageAsActive(Snapshot.SnapshotType.PREVIEW, false); }
Source:
public void testAnalyze() throws HaskellException { Function add5 = new Function(); Expr add5Expr = new Apply(new Ident("(+)"), add5.addArgument()); add5.setExpr(add5Expr); assertEquals("\\ arg0 = ((+) arg0)", add5.toHaskell()); Expr addition = new Apply(add5, new Value(new ConstT("Int"), "5")); assertEquals("Int", addition.analyze(this.env).prune().toHaskellType()); }

Target:
public void testAnalyze() throws HaskellException { Function.FunctionArgument arg = new Function.FunctionArgument(new ConstT("Int")); Expr applies = new Apply(new Ident("(+)"), arg); Function f = new Function(applies, arg); assertEquals("(Int -> (Int -> Int))", f.analyze(this.env).prune().toHaskellType()); Function.FunctionArgument arg1 = new Function.FunctionArgument(new ConstT("Int")); Function add5 = new Function(new Apply(new Apply(f, new Value(new ConstT("Int"), "5")), arg1), arg1); assertEquals("(Int -> Int)", add5.analyze(this.env).prune().toHaskellType()); }
Source:
private List<String> externalTableBasePathWithClause() throws IOException, SemanticException { Path externalTableLocation = new Path(Path.SEPARATOR, new Path("replica_external_base")); DistributedFileSystem fileSystem = replica.miniDFSCluster.getFileSystem(); externalTableLocation = PathBuilder.fullyQualifiedHDFSUri(externalTableLocation, fileSystem); fileSystem.mkdirs(externalTableLocation); return Collections.singletonList( "'" + HiveConf.ConfVars.REPL_EXTERNAL_TABLE_BASE_DIR.varname + "'='" + externalTableLocation.toString() + "'" ); }

Target:
private List<String> externalTableBasePathWithClause() throws IOException, SemanticException { Path externalTableLocation = new Path(REPLICA_EXTERNAL_BASE); DistributedFileSystem fileSystem = replica.miniDFSCluster.getFileSystem(); externalTableLocation = PathBuilder.fullyQualifiedHDFSUri(externalTableLocation, fileSystem); fileSystem.mkdirs(externalTableLocation); return Collections.singletonList( "'" + HiveConf.ConfVars.REPL_EXTERNAL_TABLE_BASE_DIR.varname + "'='" + externalTableLocation.toString() + "'" ); }
Source:
private static ChatColor toColor(String name) { if (name.equalsIgnoreCase("obfuscated")) return ChatColor.MAGIC; if (name.equalsIgnoreCase("underlined")) return ChatColor.UNDERLINE; for (ChatColor color : ChatColor.values()) { if (color == ChatColor.MAGIC) continue; if (color.name().equalsIgnoreCase(name.toUpperCase())) return color; } return null; }

Target:
private static ChatColor toColor(String name) { if (name.equals("obfuscated")) return ChatColor.MAGIC; if (name.equals("underlined")) return ChatColor.UNDERLINE; for (ChatColor color : ChatColor.values()) { if (color == ChatColor.MAGIC) continue; if (color.name().equalsIgnoreCase(name.toUpperCase())) return color; } return null; }
Source:
public void testPrefixTrim() { String logDir = getContext().getServerConfig().get("--log-path") + File.separator + "log"; StreamLogFiles log = new StreamLogFiles(getContext(), false); final long numSegments = 50; for(long x = 0; x < numSegments * StreamLogFiles.RECORDS_PER_LOG_FILE; x++) { writeToLog(log, x); } File logs = new File(logDir); assertThat((long) logs.list().length).isEqualTo(numSegments); final long endSegment = 25; long trimAddress = endSegment * StreamLogFiles.RECORDS_PER_LOG_FILE + 1; Set<SegmentHandle> trimmedHandles = new HashSet<>(); for (SegmentHandle sh : log.getSegmentHandles()) { if (sh.getSegment() < endSegment) { trimmedHandles.add(sh); } } log.prefixTrim(trimAddress); log.compact(); assertThat(log.getSegmentHandles().size()).isEqualTo((int) endSegment); String[] afterTrimFiles = logs.list(); assertThat(afterTrimFiles).hasSize((int) (numSegments - endSegment)); Set<String> fileNames = new HashSet<>(Arrays.asList(afterTrimFiles)); for (long x = endSegment + 1; x < numSegments; x++) { String logFile = Long.toString(x) + ".log"; assertThat(fileNames).contains(logFile); } log.prefixTrim(trimAddress); long trimmedExceptions = 0; for(long x = 0; x < numSegments * StreamLogFiles.RECORDS_PER_LOG_FILE; x++) { ILogData logData = log.read(x); if(logData.isTrimmed()) { trimmedExceptions++; } } for (SegmentHandle sh : trimmedHandles) { assertThat(sh.getWriteChannel().isOpen()).isFalse(); } assertThat(trimmedExceptions).isEqualTo(trimAddress + 1); }

Target:
public void testPrefixTrim() { String logDir = getContext().getServerConfig().get("--log-path") + File.separator + "log"; StreamLogFiles log = new StreamLogFiles(getContext(), false); final long numSegments = 50; for(long x = 0; x < numSegments * StreamLogFiles.RECORDS_PER_LOG_FILE; x++) { writeToLog(log, x); } File logs = new File(logDir); assertThat((long) logs.list().length).isEqualTo(numSegments); final long endSegment = 25; long trimAddress = endSegment * StreamLogFiles.RECORDS_PER_LOG_FILE + 1; Set<SegmentHandle> trimmedHandles = new HashSet<>(); for (SegmentHandle sh : log.getOpenSegmentHandles()) { if (sh.getSegment() < endSegment) { trimmedHandles.add(sh); } } log.prefixTrim(trimAddress); log.compact(); assertThat(log.getOpenSegmentHandles().size()).isEqualTo((int) endSegment); String[] afterTrimFiles = logs.list(); assertThat(afterTrimFiles).hasSize((int) (numSegments - endSegment)); Set<String> fileNames = new HashSet<>(Arrays.asList(afterTrimFiles)); for (long x = endSegment + 1; x < numSegments; x++) { String logFile = Long.toString(x) + ".log"; assertThat(fileNames).contains(logFile); } log.prefixTrim(trimAddress); long trimmedExceptions = 0; for(long x = 0; x < numSegments * StreamLogFiles.RECORDS_PER_LOG_FILE; x++) { ILogData logData = log.read(x); if(logData.isTrimmed()) { trimmedExceptions++; } } for (SegmentHandle sh : trimmedHandles) { assertThat(sh.getWriteChannel().isOpen()).isFalse(); } assertThat(trimmedExceptions).isEqualTo(trimAddress + 1); }
Source:
private int getFlag(String propertyName) { if (propertyName==null) return 0; switch (propertyName) { case BUSY_PROPERTY: return BUSY_FLAG; case PROPAGATED_CONFLICT_PROPERTY: return PROPAGATED_CONFLICT_FLAG; case PROPAGATED_ERROR_MARKER_PROPERTY: return PROPAGATED_ERROR_FLAG; case PROPAGATED_WARNING_MARKER_PROPERTY: return PROPAGATED_WARNING_FLAG; default: break; } return 0; }

Target:
private int getFlag(String propertyName) { if (propertyName == null) { return 0; } switch (propertyName) { case BUSY_PROPERTY: return BUSY_FLAG; case PROPAGATED_CONFLICT_PROPERTY: return PROPAGATED_CONFLICT_FLAG; case PROPAGATED_ERROR_MARKER_PROPERTY: return PROPAGATED_ERROR_FLAG; case PROPAGATED_WARNING_MARKER_PROPERTY: return PROPAGATED_WARNING_FLAG; default: break; } return 0; }
Source:
public static String createAndRegisterNewRequestToken(String... properties) { String newToken = UUID.randomUUID().toString(); registerRequestToken(newToken); if (properties.length != 0) { addTraceTokenProperties(properties); } return newToken; }

Target:
public static String createAndRegisterNewRequestToken(String... properties) { checkArgument((properties.length % 2) == 0, "odd number of elements in properties"); String newToken = UUID.randomUUID().toString(); registerRequestToken(newToken); if (properties.length != 0) { addTraceTokenProperties(properties); } return newToken; }
Source:
private int computeHashCode() { final int[] parts = new int[4]; parts[0] = (mapping == null) ? 0 : mapping.hashCode(); parts[1] = (semantic == null) ? 0 : getSemanticID().hashCode(); parts[2] = (line == null) ? 0 : getLineID().hashCode(); parts[3] = (column == null) ? 0 : getColumnID().hashCode(); final String sep = "/"; return KeyCache.DEFAULT.getKey(parts[0] + sep + parts[1] + sep + parts[2] + sep + parts[3]); }

Target:
private int computeHashCode() { final int[] parts = new int[4]; parts[0] = (mapping == null) ? 0 : mapping.hashCode(); parts[1] = (semantic == null) ? 0 : getSemanticID(); parts[2] = (line == null) ? 0 : getLineID(); parts[3] = (column == null) ? 0 : getColumnID(); final String sep = "/"; return KeyCache.DEFAULT.getKey(parts[0] + sep + parts[1] + sep + parts[2] + sep + parts[3]); }
Source:
private static @NotNull Vector2 readPosition(@NotNull JsonValue jsonValue, @Nullable String superComponent) { Optional<String> string = Optional.ofNullable(jsonValue.getString("position", null)); return string .map(SolMath::readV2) .orElseThrow(() -> new SolDescriptiveException("Some of your " + superComponent + "s is missing a required \"position\" argument, or it is malformed.")); }

Target:
private static @NotNull Vector2 readPosition(@NotNull JsonValue jsonValue, @Nullable String superComponent) { Optional<String> string = Optional.ofNullable(jsonValue.getString("position", null)); return string .map(SolMath::readVector2String) .orElseThrow(() -> new SolDescriptiveException("Some of your " + superComponent + "s is missing a required \"position\" argument, or it is malformed.")); }
Source:
public void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws UnprocessableEntityException, PatchBadRequestException, SQLException, AuthorizeException { itemPatch.patch(context, apiCategory, model, uuid, patch); findOne(context, uuid); }

Target:
public void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws UnprocessableEntityException, PatchBadRequestException, SQLException, AuthorizeException, ResourceNotFoundException { ItemRest restModel = findOne(context, uuid); if (restModel == null) { throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found"); } itemPatch.patch(restModel, context, patch); }
Source:
public void testExists() throws Exception { h.execute("insert into something (id, name) values (1, 'Coda')"); h.registerCollectorFactory(new MaybeCollectorFactory()); @SuppressWarnings("unchecked") Maybe<String> rs = h.createQuery("select name from something where id = :id") .bind("id", 1) .mapTo(String.class) .collectInto(Maybe.class); assertThat(rs.isKnown(), equalTo(true)); assertThat(rs.getValue(), equalTo("Coda")); }

Target:
public void testExists() throws Exception { Handle h = h2.getSharedHandle(); h.execute("insert into something (id, name) values (1, 'Coda')"); h.registerCollectorFactory(new GuavaOptionalCollectorFactory()); @SuppressWarnings("unchecked") Optional<String> rs = h.createQuery("select name from something where id = :id") .bind("id", 1) .mapTo(String.class) .collectInto(Optional.class); assertThat(rs.isPresent(), equalTo(true)); assertThat(rs.get(), equalTo("Coda")); }
Source:
public void selectionRangeUpdated(final TmfSelectionRangeUpdatedSignal signal) { final ITmfTrace trace = fTrace; if (signal.getSource() == this || trace == null) { return; } TmfTraceContext ctx = TmfTraceManager.getInstance().getTraceContext(trace); long beginTime = ctx.getSelectionRange().getStartTime().toNanos(); long endTime = ctx.getSelectionRange().getEndTime().toNanos(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (fTimeGraphViewer.getControl().isDisposed()) { return; } if (beginTime == getTimeGraphViewer().getSelectionBegin() && endTime == getTimeGraphViewer().getSelectionEnd()) { return; } if (beginTime == endTime) { fTimeGraphViewer.setSelectedTime(beginTime, true); } else { fTimeGraphViewer.setSelectionRange(beginTime, endTime, true); } synchingToTime(fTimeGraphViewer.getSelectionBegin()); } }); }

Target:
public void selectionRangeUpdated(final TmfSelectionRangeUpdatedSignal signal) { final ITmfTrace trace = fTrace; if (signal.getSource() == this || trace == null) { return; } TmfTraceContext ctx = TmfTraceManager.getInstance().getTraceContext(trace); long beginTime = ctx.getSelectionRange().getStartTime().toNanos(); long endTime = ctx.getSelectionRange().getEndTime().toNanos(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (fTimeGraphViewer.getControl().isDisposed()) { return; } if (beginTime == fTimeGraphViewer.getSelectionBegin() && endTime == fTimeGraphViewer.getSelectionEnd()) { return; } if (beginTime == endTime) { fTimeGraphViewer.setSelectedTime(beginTime, true); } else { fTimeGraphViewer.setSelectionRange(beginTime, endTime, true); } synchingToTime(fTimeGraphViewer.getSelectionBegin()); } }); }
Source:
@Override public void unlink(String pathname) throws ErrnoException { os.unlink(pathname); }

Target:
@Override public void unlink(String pathname) throws ErrnoException { BlockGuard.getThreadPolicy().onWriteToDisk(); os.unlink(pathname); }
Source:
private void setUpRsync() { logger.fine("setUpRsync called..."); if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsWrapper.getValueForKey(SettingsServiceBean.Key.UploadMethods))) { try { ScriptRequestResponse scriptRequestResponse = commandEngine.submit(new RequestRsyncScriptCommand(dvRequestService.getDataverseRequest(), dataset)); logger.fine("script: " + scriptRequestResponse.getScript()); if (scriptRequestResponse.getScript() != null && !scriptRequestResponse.getScript().isEmpty()) { setRsyncScript(scriptRequestResponse.getScript()); rsyncScriptFilename = "upload-" + workingVersion.getDataset().getIdentifier() + ".bash"; setHasRsyncScript(true); } else { setHasRsyncScript(false); } } catch (EJBException ex) { logger.warning("Problem getting rsync script (EJBException): " + EjbUtil.ejbExceptionToString(ex)); } catch (RuntimeException ex) { logger.warning("Problem getting rsync script (RuntimeException): " + ex.getLocalizedMessage()); } catch (CommandException cex) { logger.warning("Problem getting rsync script (Command Exception): " + cex.getLocalizedMessage()); } } }

Target:
private void setUpRsync() { logger.fine("setUpRsync called..."); if (DataCaptureModuleUtil.rsyncSupportEnabled(settingsWrapper.getValueForKey(SettingsServiceBean.Key.UploadMethods))) { try { ScriptRequestResponse scriptRequestResponse = commandEngine.submit(new RequestRsyncScriptCommand(dvRequestService.getDataverseRequest(), dataset)); logger.fine("script: " + scriptRequestResponse.getScript()); if (scriptRequestResponse.getScript() != null && !scriptRequestResponse.getScript().isEmpty()) { setRsyncScript(scriptRequestResponse.getScript()); rsyncScriptFilename = DataCaptureModuleUtil.getScriptName(workingVersion); setHasRsyncScript(true); } else { setHasRsyncScript(false); } } catch (EJBException ex) { logger.warning("Problem getting rsync script (EJBException): " + EjbUtil.ejbExceptionToString(ex)); } catch (RuntimeException ex) { logger.warning("Problem getting rsync script (RuntimeException): " + ex.getLocalizedMessage()); } catch (CommandException cex) { logger.warning("Problem getting rsync script (Command Exception): " + cex.getLocalizedMessage()); } } }
Source:
protected void updateTitle(String brand) { if (brand != null) { IBrandManager brandManager = TasksUiPlugin.getDefault().getBrandManager(); setTitle(brandManager.getConnectorLabel(getConnector(), brand)); } }

Target:
protected void updateTitle(String brand) { IBrandManager brandManager = TasksUiPlugin.getDefault().getBrandManager(); setTitle(brandManager.getConnectorLabel(getConnector(), brand)); }
Source:
public static <T extends JavaSource<?>> T create(final Class<T> type) { for (JavaParser parser : getParsers()) { final T result = parser.create(type); if (result != null) { return result; } } return null; }

Target:
public static <T extends JavaSource<?>> T create(final Class<T> type) { for (JavaParser parser : getParsers()) { final T result = parser.create(type); if (result != null) { return result; } } throw new ParserException("Cannot find JavaParserProvider capable of producing JavaSource of type " + type.getSimpleName(), new IllegalArgumentException(type.getName())); }
Source:
public void execute() { final DialogBox db = new DialogBox(false, true); db.setText("About MIT App Inventor"); db.setStyleName("ode-DialogBox"); db.setHeight("200px"); db.setWidth("400px"); db.setGlassEnabled(true); db.setAnimationEnabled(true); db.center(); VerticalPanel DialogBoxContents = new VerticalPanel(); String html = MESSAGES.gitBuildId(GitBuildId.getDate(), GitBuildId.getVersion()) + "<BR/>Use Companion: " + BlocklyPanel.getCompVersion() + "<BR/>Target Android SDK: " + YaVersion.TARGET_SDK_VERSION; Config config = Ode.getInstance().getSystemConfig(); String releaseNotesUrl = config.getReleaseNotesUrl(); if (!Strings.isNullOrEmpty(releaseNotesUrl)) { html += "<BR/><BR/>Please see <a href=\"" + releaseNotesUrl + "\" target=\"_blank\">release notes</a>"; } String tosUrl = config.getTosUrl(); if (!Strings.isNullOrEmpty(tosUrl)) { html += "<BR/><BR/><a href=\"" + tosUrl + "\" target=\"_blank\">" + MESSAGES.privacyTermsLink() + "</a>"; } HTML message = new HTML(html); SimplePanel holder = new SimplePanel(); Button ok = new Button("Close"); ok.addClickListener(new ClickListener() { public void onClick(Widget sender) { db.hide(); } }); holder.add(ok); DialogBoxContents.add(message); DialogBoxContents.add(holder); db.setWidget(DialogBoxContents); db.show(); }

Target:
public void execute() { final DialogBox db = new DialogBox(false, true); db.setText("About MIT App Inventor"); db.setStyleName("ode-DialogBox"); db.setHeight("200px"); db.setWidth("400px"); db.setGlassEnabled(true); db.setAnimationEnabled(true); db.center(); VerticalPanel DialogBoxContents = new VerticalPanel(); String html = MESSAGES.gitBuildId(GitBuildId.getDate(), GitBuildId.getVersion()) + "<BR/>" + MESSAGES.useCompanion(YaVersion.PREFERRED_COMPANION, YaVersion.PREFERRED_COMPANION + "u") + "<BR/>" + MESSAGES.targetSdkVersion(YaVersion.TARGET_SDK_VERSION, YaVersion.TARGET_ANDROID_VERSION); Config config = Ode.getInstance().getSystemConfig(); String releaseNotesUrl = config.getReleaseNotesUrl(); if (!Strings.isNullOrEmpty(releaseNotesUrl)) { html += "<BR/><BR/>Please see <a href=\"" + releaseNotesUrl + "\" target=\"_blank\">release notes</a>"; } String tosUrl = config.getTosUrl(); if (!Strings.isNullOrEmpty(tosUrl)) { html += "<BR/><BR/><a href=\"" + tosUrl + "\" target=\"_blank\">" + MESSAGES.privacyTermsLink() + "</a>"; } HTML message = new HTML(html); SimplePanel holder = new SimplePanel(); Button ok = new Button("Close"); ok.addClickListener(new ClickListener() { public void onClick(Widget sender) { db.hide(); } }); holder.add(ok); DialogBoxContents.add(message); DialogBoxContents.add(holder); db.setWidget(DialogBoxContents); db.show(); }
Source:
protected void processValue(int quark, long timestamp, ITmfStateValue value) throws AttributeNotFoundException, TimeRangeException, StateValueTypeException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); if (fStack == ValueTypeStack.TYPE_STACK_PUSH) { ss.pushAttribute(timestamp, value, quark); } else if (fStack == ValueTypeStack.TYPE_STACK_POP) { ss.popAttribute(timestamp, quark); } else { ss.modifyAttribute(timestamp, value, quark); } }

Target:
protected void processValue(int quark, long timestamp, ITmfStateValue value) throws AttributeNotFoundException, TimeRangeException, StateValueTypeException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); switch (fStack) { case POP: ss.popAttribute(timestamp, quark); break; case PUSH: ss.pushAttribute(timestamp, value, quark); break; case NULL: case PEEK: default: ss.modifyAttribute(timestamp, value, quark); break; } }
Source:
final void setPluginConfigValues(Map<String, Map<String, String>> pluginConfigValues) { NativeMap<StringMap> configValues = NativeMap.create().cast(); for (Entry<String, Map<String, String>> e : pluginConfigValues.entrySet()) { StringMap values = StringMap.create(); configValues.put(e.getKey(), values); for (Entry<String, String> e2 : e.getValue().entrySet()) { values.put(e2.getKey(), e2.getValue()); } } setPluginConfigValuesRaw(configValues); }

Target:
final void setPluginConfigValues(Map<String, Map<String, String>> pluginConfigValues) { if (!pluginConfigValues.isEmpty()) { NativeMap<StringMap> configValues = NativeMap.create().cast(); for (Entry<String, Map<String, String>> e : pluginConfigValues.entrySet()) { StringMap values = StringMap.create(); configValues.put(e.getKey(), values); for (Entry<String, String> e2 : e.getValue().entrySet()) { values.put(e2.getKey(), e2.getValue()); } } setPluginConfigValuesRaw(configValues); } }
Source:
public void before() { postProcessorRegistry = new PostProcessorDescriptorRegistryImpl<String>(); postProcessorRegistry.put(CompareDiagramPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( Pattern.compile("<LINK_0>\\d.\\d.\\d/notation"), null, new CompareDiagramPostProcessor(), 10)); emfCompare = EMFCompare.builder().setPostProcessorRegistry(postProcessorRegistry).build(); }

Target:
public void before() { postProcessorRegistry = new PostProcessorDescriptorRegistryImpl<String>(); postProcessorRegistry.put(CompareDiagramPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( Pattern.compile("<LINK_0>\\d.\\d.\\d/notation"), null, new CompareDiagramPostProcessor(), 30)); emfCompare = EMFCompare.builder().setPostProcessorRegistry(postProcessorRegistry).build(); }
Source:
private static String formatMessage(String msg, Object... args) { try { return String.format(msg, (Object[]) args); } catch (IllegalFormatException | FormatterClosedException ignore) { } return msg; }

Target:
private static String formatMessage(String msg, Object... args) { try { return String.format(Locale.ENGLISH, msg, (Object[]) args); } catch (IllegalFormatException | FormatterClosedException ignore) { } return msg; }
Source:
public void validateInputTask(PluginTask task) { task.setIncrementalColumn(Optional.of(INCREMENTAL_COLUMN)); task.setUidColumn(Optional.of(UID_COLUMN)); if (!task.getActivityTypeIds().isEmpty()) { List<String> invalidIds = new ArrayList<>(); for (String id : task.getActivityTypeIds()) { if (StringUtils.isBlank(id) || !StringUtils.isNumeric(StringUtils.trimToEmpty(id))) { invalidIds.add(id); } } if (!invalidIds.isEmpty()) { throw new ConfigException(MessageFormat.format("Invalid activity type id: [{0}]", StringUtils.join(invalidIds, ", "))); } try (MarketoRestClient restClient = createMarketoRestClient(task)) { MarketoService marketoService = new MarketoServiceImpl(restClient); Iterable<ObjectNode> nodes = marketoService.getActivityTypes(); if (nodes != null) { checkValidActivityTypeIds(nodes, task.getActivityTypeIds()); } else { } } } super.validateInputTask(task); }

Target:
public void validateInputTask(PluginTask task) { task.setIncrementalColumn(Optional.of(INCREMENTAL_COLUMN)); task.setUidColumn(Optional.of(UID_COLUMN)); if (!task.getActivityTypeIds().isEmpty()) { List<Integer> activityIds = checkValidActivityTypeIds(task); try (MarketoRestClient restClient = createMarketoRestClient(task)) { MarketoService marketoService = new MarketoServiceImpl(restClient); Iterable<ObjectNode> nodes = marketoService.getActivityTypes(); if (nodes != null) { checkValidActivityTypeIds(nodes, activityIds); } } task.setActTypeIds(activityIds); } else { task.setActTypeIds(new ArrayList<Integer>()); } super.validateInputTask(task); }
Source:
public void testToJsonWithLengthLimitNonAscii() { JsonCodec<ImmutablePerson> jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158\u015a", 500), false); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); }

Target:
public void testToJsonWithLengthLimitNonAscii() { JsonCodec<ImmutablePerson> jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158", 1000), false); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); }
Source:
public String toString() { return "BinlogPosition[" + file + ":" + offset + ":" + gtidStr + "]"; }

Target:
public String toString() { return "BinlogPosition[" + (gtidSetStr == null ? file + ":" + offset : gtidSetStr) + "]"; }
Source:
public void failNonTxnEnqueue() { CorfuQueue<String> corfuQueue = new CorfuQueue<>(getDefaultRuntime(), "test"); Assertions.assertThatThrownBy(() -> corfuQueue.enqueue("c")) .isInstanceOf(IllegalStateException.class) .hasMessage("must be called within a transaction!"); }

Target:
public void failNonTxnEnqueue() { CorfuQueue<String> corfuQueue = new CorfuQueue<>(getDefaultRuntime(), "test"); assertThatThrownBy(() -> corfuQueue.enqueue("c")) .isInstanceOf(IllegalStateException.class) .hasMessage("must be called within a transaction!"); }
Source:
public void store(String key, Object value) { File dir = new File(getMapStorePath()); if (new File(getPersistencePath()).canWrite()) { boolean created = dir.mkdirs(); if (created || dir.exists()) { LOGGER.trace("Entering: store - key: {}", key); try (OutputStream file = new FileOutputStream(getMapStorePath() + key + PERSISTED_FILE_SUFFIX); OutputStream buffer = new BufferedOutputStream(file); ObjectOutputStream output = new ObjectOutputStream(buffer)) { output.writeObject(value); } catch (IOException e) { LOGGER.debug("IOException storing value in cache with key = " + key, e); } } else { LOGGER.debug("Unable to create directory: {}", dir.getAbsolutePath()); } } }

Target:
public void store(String key, Object value) { File dir = new File(getMapStorePath()); if (new File(getPersistencePath()).canWrite()) { boolean created = dir.mkdirs(); if (created || dir.exists()) { LOGGER.trace("Entering: store - key: {}", key); try (OutputStream file = new FileOutputStream(getPersistedFilePathForKey(key)); OutputStream buffer = new BufferedOutputStream(file); ObjectOutputStream output = new ObjectOutputStream(buffer)) { output.writeObject(value); } catch (IOException e) { LOGGER.debug("IOException storing value in cache with key = {}", key, e); LOGGER.warn( "Error storing value in cache with key [{}]. Turn logging to debug for more info.", key); } } else { LOGGER.debug("Unable to create directory: {}", dir.getAbsolutePath()); } } }
Source:
public void closeThisNode(long endtime) { fRwl.writeLock().lock(); try { if (!fIntervals.isEmpty()) { if (endtime < fIntervals.get(fIntervals.size() - 1).getEndTime()) { throw new IllegalArgumentException("Closing end time should be greater than the end time of the intervals of this node"); } } fNodeEnd = endtime; } finally { fRwl.writeLock().unlock(); } }

Target:
public void closeThisNode(long endtime) { fRwl.writeLock().lock(); try { if (!fIntervals.isEmpty()) { if (endtime < Iterables.getLast(fIntervals).getEndTime()) { throw new IllegalArgumentException("Closing end time should be greater than or equal to the end time of the intervals of this node"); } } fNodeEnd = endtime; } finally { fRwl.writeLock().unlock(); } }
Source:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(fieldName, value); if (hint.analyzer != null) { matchQuery.analyzer(hint.analyzer); } return matchQuery; }

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { return QueryBuilders.matchQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
private void migratePartialDownloads(SqlDatabaseWrapper database, PartialDownloadMigrationExtractor partialDownloadMigrationExtractor, DownloadsPersistence downloadsPersistence) { List<Migration> partialMigrations = partialDownloadMigrationExtractor.extractMigrations(); for (int i = 0; i < partialMigrations.size(); i++) { downloadsPersistence.startTransaction(); database.startTransaction(); Migration migration = partialMigrations.get(i); migrateV1DataToV2Database(downloadsPersistence, migration); deleteFrom(database, migration); downloadsPersistence.transactionSuccess(); downloadsPersistence.endTransaction(); database.setTransactionSuccessful(); database.endTransaction(); } }

Target:
private void migratePartialDownloads(SqlDatabaseWrapper database, PartialDownloadMigrationExtractor partialDownloadMigrationExtractor, DownloadsPersistence downloadsPersistence) { List<Migration> partialMigrations = partialDownloadMigrationExtractor.extractMigrations(); for (Migration partialMigration : partialMigrations) { downloadsPersistence.startTransaction(); database.startTransaction(); migrateV1DataToV2Database(downloadsPersistence, partialMigration); deleteFrom(database, partialMigration); downloadsPersistence.transactionSuccess(); downloadsPersistence.endTransaction(); database.setTransactionSuccessful(); database.endTransaction(); } Log.d(TAG, "partial migrations are all EXTRACTED, time is " + System.nanoTime()); }
Source:
private static String toPathString(String moduleName) { return moduleName.replace('.', '/') + '/' + moduleName + '/'; }

Target:
private static String toPathString(String moduleName) { return moduleName.replace('.', '/') + '/' + moduleName; }
Source:
public int hashCode() { HashCodeBuilder hcBuilder = new HashCodeBuilder(); hcBuilder.append(releaseVer); return hcBuilder.toHashCode(); }

Target:
public int hashCode() { return this.releaseVer != null ? this.releaseVer.hashCode() : 0; }
Source:
public void connect() throws IOException { if (connected) return; try (final InputStream in = getJarFileURL().openConnection().getInputStream()) { jarFile = AccessController.doPrivileged( new PrivilegedExceptionAction<JarFile>() { public JarFile run() throws IOException { Path tmpFile = Files.createTempFile("jar_cache", null); try { Files.copy(in, tmpFile, StandardCopyOption.REPLACE_EXISTING); JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ); tmpFile.toFile().deleteOnExit(); return jarFile; } catch (Throwable thr) { try { Files.delete(tmpFile); } catch (IOException ioe) { thr.addSuppressed(ioe); } throw thr; } finally { in.close(); } } }); connected = true; } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } }

Target:
public void connect() throws IOException { if (connected) { return; } try (final InputStream in = getJarFileURL().openConnection().getInputStream()) { jarFile = AccessController.doPrivileged( new PrivilegedExceptionAction<JarFile>() { public JarFile run() throws IOException { Path tmpFile = Files.createTempFile("jar_cache", null); try { Files.copy(in, tmpFile, StandardCopyOption.REPLACE_EXISTING); JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ); tmpFile.toFile().deleteOnExit(); return jarFile; } catch (Throwable thr) { try { Files.delete(tmpFile); } catch (IOException ioe) { thr.addSuppressed(ioe); } throw thr; } finally { in.close(); } } }); connected = true; } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } }
Source:
public OrganizationType getOrganization(String exchangeName, String hcid) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); String hcidWithoutPrefix = HomeCommunityMap.formatHomeCommunityId(hcid); String hcidWithPrefix = HomeCommunityMap.getHomeCommunityIdWithPrefix(hcid); if (StringUtils.isEmpty(hcidWithoutPrefix) || StringUtils.isEmpty(hcidWithPrefix)) { return null; } Map<String, OrganizationType> map = null; if (StringUtils.isNotEmpty(exchangeName)) { map = exCache.get(exchangeName); } else if (StringUtils.isNotEmpty(exInfo.getDefaultExchange())) { map = exCache.get(exInfo.getDefaultExchange()); } else { if (null != getCache().values()) { map = extractHcidOrganizationMap(); } } if (null != map) { return map.get(hcidWithPrefix) != null ? map.get(hcidWithPrefix) : map.get(hcidWithoutPrefix); } else { return null; } }

Target:
public OrganizationType getOrganization(String exchangeName, String hcid) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); String hcidWithoutPrefix = HomeCommunityMap.formatHomeCommunityId(hcid); String hcidWithPrefix = HomeCommunityMap.getHomeCommunityIdWithPrefix(hcid); if (StringUtils.isEmpty(hcidWithoutPrefix) || StringUtils.isEmpty(hcidWithPrefix)) { return null; } Map<String, OrganizationType> map = null; if (StringUtils.isNotEmpty(exchangeName)) { map = exCache.get(exchangeName); } else if (StringUtils.isNotEmpty(getDefaultExchange())) { map = exCache.get(getDefaultExchange()); } else { if (null != getCache().values()) { map = extractHcidOrganizationMap(); } } if (null != map) { return map.get(hcidWithPrefix) != null ? map.get(hcidWithPrefix) : map.get(hcidWithoutPrefix); } else { return null; } }
Source:
public void invalidate() { mActionMode.invalidate(); if (mMenu != null) { mMenu.invalidate(); } }

Target:
public void invalidate() { mActionMode.invalidate(); if (mMenu != null) mMenu.invalidate(); }
Source:
public String submitECLandGetResults(String ecl, String targetcluster, int resultLimit, int maxwait) throws Exception { String results = null; initEclDirectClient(); try { results = eclDirectClient.submitECLandGetResults(ecl, targetcluster, resultLimit, maxwait); } catch (Exception e) { System.out.println("Error submiting ECL: " + e.getLocalizedMessage()); throw e; } return results; }

Target:
public String submitECLandGetResults(String ecl, String targetcluster, int resultLimit, int maxwait) throws Exception { String results = null; initEclDirectClient(); try { results = eclDirectClient.submitECLandGetResults(ecl, targetcluster, resultLimit, maxwait); } catch (Exception e) { Utils.println(System.err, "Error submitting ECL: " + e.getLocalizedMessage(), false, verbosemode); throw e; } return results; }
Source:
public boolean supportsReloading() { return supportsReloading; }

Target:
public final boolean supportsReloading() { return supportsReloading; }
Source:
private org.kie.dmn.model.api.DRGElement stunnerToDMN(final Node<?, ?> node, final Consumer<ComponentWidths> componentWidthsConsumer) { if (node.getContent() instanceof View<?>) { View<?> view = (View<?>) node.getContent(); if (view.getDefinition() instanceof InputData) { return inputDataConverter.dmnFromNode((Node<View<InputData>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof Decision) { return decisionConverter.dmnFromNode((Node<View<Decision>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof BusinessKnowledgeModel) { return bkmConverter.dmnFromNode((Node<View<BusinessKnowledgeModel>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof KnowledgeSource) { return knowledgeSourceConverter.dmnFromNode((Node<View<KnowledgeSource>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof DecisionService) { return decisionServiceConverter.dmnFromNode((Node<View<DecisionService>, ?>) node, componentWidthsConsumer); } else { throw new UnsupportedOperationException("TODO"); } } throw new RuntimeException("wrong diagram structure to marshall"); }

Target:
private org.kie.dmn.model.api.DRGElement stunnerToDMN(final Node<?, ?> node, final Consumer<ComponentWidths> componentWidthsConsumer) { if (node.getContent() instanceof View<?>) { final View<?> view = (View<?>) node.getContent(); if (view.getDefinition() instanceof InputData) { return inputDataConverter.dmnFromNode((Node<View<InputData>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof Decision) { return decisionConverter.dmnFromNode((Node<View<Decision>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof BusinessKnowledgeModel) { return bkmConverter.dmnFromNode((Node<View<BusinessKnowledgeModel>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof KnowledgeSource) { return knowledgeSourceConverter.dmnFromNode((Node<View<KnowledgeSource>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof DecisionService) { return decisionServiceConverter.dmnFromNode((Node<View<DecisionService>, ?>) node, componentWidthsConsumer); } else { throw new UnsupportedOperationException("Unsupported node type detected."); } } throw new RuntimeException("wrong diagram structure to marshall"); }
Source:
private Message runCommand(OMRequest request, long trxLogIndex) { OMResponse response = handler.handle(request); if (response.getSuccess()) { lastAppliedIndex = trxLogIndex; } return OMRatisHelper.convertResponseToMessage(response); }

Target:
private Message runCommand(OMRequest request, long trxLogIndex) { OMResponse response = handler.handle(request); lastAppliedIndex = trxLogIndex; return OMRatisHelper.convertResponseToMessage(response); }
Source:
private void textChanged() { patternFilter.setPattern(filterText.getText()); getTableViewer().refresh(); Set<Object> checkedItems = getCheckedItems(); for (Object object : checkedItems) { getTableViewer().setChecked(object, true); } }

Target:
private void textChanged() { patternFilter.setPattern(filterText.getText()); getTableViewer().refresh(); for (Object checkedItem : getCheckedItems()) { getTableViewer().setChecked(checkedItem, true); } }
Source:
public void test_roundtrip_tlen_preserved() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ReferenceSource source = new ReferenceSource(new File(SAM_TOOLS_TEST_DIR, "cram_tlen.fasta")); final List<SAMRecord> records = new ArrayList<>(); try (SamReader reader = SamReaderFactory.make().open(new File(SAM_TOOLS_TEST_DIR, "cram_tlen_reads.sorted.sam"))) { try (CRAMFileWriter writer = new CRAMFileWriter(baos, source, reader.getFileHeader(), "test.cram")) { for (final SAMRecord record : reader) { writer.addAlignment(record); records.add(record); } } } try (CRAMFileReader cramReader = new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (File) null, source, ValidationStringency.STRICT)) { final SAMRecordIterator iterator = cramReader.getIterator(); int i = 0; while (iterator.hasNext()) { final SAMRecord record1 = iterator.next(); final SAMRecord record2 = records.get(i++); Assert.assertEquals(record1.getInferredInsertSize(), record2.getInferredInsertSize(), record1.getReadName()); Assert.assertEquals(record1, record2, record1.getReadName()); } Assert.assertEquals(records.size(), i); } }

Target:
public void test_roundtrip_tlen_preserved() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ReferenceSource source = new ReferenceSource(new File(SAM_TOOLS_TEST_DIR, "cram_tlen.fasta")); final List<SAMRecord> records = new ArrayList<>(); try (SamReader reader = SamReaderFactory.make().open(new File(SAM_TOOLS_TEST_DIR, "cram_tlen_reads.sorted.sam")); CRAMFileWriter writer = new CRAMFileWriter(baos, source, reader.getFileHeader(), "test.cram")) { for (final SAMRecord record : reader) { writer.addAlignment(record); records.add(record); } } try (CRAMFileReader cramReader = new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (File) null, source, ValidationStringency.STRICT)) { final SAMRecordIterator iterator = cramReader.getIterator(); int i = 0; while (iterator.hasNext()) { final SAMRecord record1 = iterator.next(); final SAMRecord record2 = records.get(i++); Assert.assertEquals(record1.getInferredInsertSize(), record2.getInferredInsertSize(), record1.getReadName()); Assert.assertEquals(record1, record2, record1.getReadName()); } Assert.assertEquals(records.size(), i); } }
Source:
public int compareUnsortedEncodedKeyComponents(@Nullable Double lhs, @Nullable Double rhs) { return Double.compare(DimensionHandlerUtils.convertObjectToDouble(lhs), DimensionHandlerUtils.convertObjectToDouble(rhs)); }

Target:
public int compareUnsortedEncodedKeyComponents(@Nullable Double lhs, @Nullable Double rhs) { return Double.compare(DimensionHandlerUtils.nullToZero(lhs), DimensionHandlerUtils.nullToZero(rhs)); }
Source:
public synchronized void store(@NotNull String serverId, @NotNull KieServerState kieServerState) { if (!retrieveKieServerId(kieServerState).equals(serverId)) { throw new IllegalArgumentException("Invalid KieServerId: Id does not match with KieServerState."); } processKieServerStateByOpenShift(client -> { DeploymentConfig dc = client.deploymentConfigs().withName(serverId).get(); ConfigMap cm = client.configMaps().withName(serverId).get(); String stateXML = xs.toXML(kieServerState); if (Boolean.parseBoolean(kieServerState.getConfiguration() .getConfigItemValue(KieServerConstants.KIE_SERVER_STATE_IMMUTABLE, "false"))) { createNewKieServerStateCM(kieServerState, serverId, client); return null; } else if (isServerStateUpdateAllowed(cm, kieServerState)) { cm.setData(Collections.singletonMap(CFG_MAP_DATA_KEY, stateXML)); } else { return null; } ObjectMeta md = cm.getMetadata(); Map<String, String> ann = md.getAnnotations() == null ? new ConcurrentHashMap<>() : md.getAnnotations(); md.setAnnotations(ann); ann.put(STATE_CHANGE_TIMESTAMP, ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT)); if (isKieServerReady()) { if (isKieServerRuntime() && !isDCStable(dc)) { logger.warn("Updating KieServerState is not supported if there are in-progress DeploymentConfig activities."); } else { ann.put(ROLLOUT_REQUIRED, "true"); client.configMaps().createOrReplace(cm); } } return null; }); }

Target:
public synchronized void store(@NotNull String serverId, @NotNull KieServerState kieServerState) { if (!retrieveKieServerId(kieServerState).equals(serverId)) { throw new IllegalArgumentException("Invalid KieServerId: Id does not match with KieServerState."); } processKieServerStateByOpenShift(client -> { DeploymentConfig dc = client.deploymentConfigs().withName(serverId).get(); ConfigMap cm = client.configMaps().withName(serverId).get(); if (Boolean.parseBoolean(kieServerState.getConfiguration() .getConfigItemValue(KIE_SERVER_STATE_IMMUTABLE, Boolean.FALSE.toString()))) { if (Boolean.parseBoolean(System.getProperty(KIE_SERVER_STATE_IMMUTABLE_INIT, Boolean.FALSE.toString()))) { createNewKieServerStateCM(kieServerState, serverId, client); } else { logger.debug("Overwrite immutable KieServer, id:{}, state is not allow.", serverId); } } else if (isServerStateUpdateAllowed(dc, cm, kieServerState)) { ObjectMeta md = cm.getMetadata(); Map<String, String> ann = md.getAnnotations() == null ? new ConcurrentHashMap<>() : md.getAnnotations(); md.setAnnotations(ann); ann.put(STATE_CHANGE_TIMESTAMP, ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT)); ann.put(ROLLOUT_REQUIRED, "true"); cm.setData(Collections.singletonMap(CFG_MAP_DATA_KEY, xs.toXML(kieServerState))); client.configMaps().createOrReplace(cm); } return null; }); }