auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { MessageType type = MessageType.valueOf(bbis.readInt()); int size = bbis.readInt(); byte[] data = new byte[size]; bbis.readFully(data); Record record = Record.parseFrom(data); Any payload = record.getPayload(); if (!classMap.containsKey(payload.getTypeUrl())) { log.error("Deserialization error: Unknown type "+payload.getTypeUrl()+ " dumping map..\n"); for (String entry: classMap.keySet()) { log.error(entry + "=>" + classMap.get(entry)); } throw new SerializerException(payload.getTypeUrl()+" not in map!"); } Message value = payload.unpack(classMap.get(payload.getTypeUrl())); if (type.equals(MessageType.KEY)) { return value; } else { Message metadata = null; if (record.hasMetadata()) { Any anyMetadata = record.getMetadata(); metadata = anyMetadata.unpack(classMap.get(anyMetadata.getTypeUrl())); } return new CorfuRecord(value, metadata); } } catch (IOException ie) { log.error("Exception during deserialization!", ie); throw new SerializerException(ie); } }

Target:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { MessageType type = MessageType.valueOf(bbis.readInt()); int size = bbis.readInt(); byte[] data = new byte[size]; bbis.readFully(data); Record record = Record.parseFrom(data); Any payload = record.getPayload(); if (!classMap.containsKey(payload.getTypeUrl())) { log.error("Deserialization error: Encountered a log update for this class "+payload.getTypeUrl() +" but its corresponding class type cannot be found in in-memory type map. Dumping map..\n"); for (String entry: classMap.keySet()) { log.error(entry + "=>" + classMap.get(entry)); } throw new SerializerException(payload.getTypeUrl()+" not in map!"); } Message value = payload.unpack(classMap.get(payload.getTypeUrl())); if (type.equals(MessageType.KEY)) { return value; } else { Message metadata = null; if (record.hasMetadata()) { Any anyMetadata = record.getMetadata(); metadata = anyMetadata.unpack(classMap.get(anyMetadata.getTypeUrl())); } return new CorfuRecord(value, metadata); } } catch (IOException ie) { log.error("Exception during deserialization!", ie); throw new SerializerException(ie); } }
Source:
private ApiFuture<?> offer(Mutation mutation) { ApiFuture<?> future = null; try { if (mutation == null) { future = ApiFutures.immediateFailedFuture( new IllegalArgumentException("Cannot perform a mutation on a null object.")); } else if (mutation instanceof Put) { future = bulkMutation.add(adapter.adaptEntry((Put) mutation)); } else if (mutation instanceof Delete) { future = bulkMutation.add(adapter.adaptEntry((Delete) mutation)); } else if (mutation instanceof Increment) { future = dataClient.readModifyWriteRowAsync(adapter.adapt((Increment) mutation)); operationAccountant.registerOperation(new ApiFutureToListenableFuture<>(future)); } else if (mutation instanceof Append) { future = dataClient.readModifyWriteRowAsync(adapter.adapt((Append) mutation)); operationAccountant.registerOperation(new ApiFutureToListenableFuture<>(future)); } else { future = ApiFutures.immediateFailedFuture( new IllegalArgumentException( "Encountered unknown mutation type: " + mutation.getClass())); } } catch (Exception e) { future = ApiFutures.immediateFailedFuture(e); } return future; }

Target:
private ApiFuture<?> offer(Mutation mutation) { ApiFuture<?> future = null; try { if (mutation == null) { future = ApiFutures.immediateFailedFuture( new IllegalArgumentException("Cannot perform a mutation on a null object.")); } else if (mutation instanceof Put) { future = bulkMutation.add(adapter.adaptEntry((Put) mutation)); } else if (mutation instanceof Delete) { future = bulkMutation.add(adapter.adaptEntry((Delete) mutation)); } else if (mutation instanceof Increment) { future = dataClient.readModifyWriteRowAsync(adapter.adapt((Increment) mutation)); operationAccountant.registerOperation(future); } else if (mutation instanceof Append) { future = dataClient.readModifyWriteRowAsync(adapter.adapt((Append) mutation)); operationAccountant.registerOperation(future); } else { future = ApiFutures.immediateFailedFuture( new IllegalArgumentException( "Encountered unknown mutation type: " + mutation.getClass())); } } catch (Exception e) { future = ApiFutures.immediateFailedFuture(e); } return future; }
Source:
<T> void put(RegistrationType<T> registrationType, Handler<T> handler) { List<Handler<T>> handlers = get(registrationType); if (handlers == null) { handlers = new ArrayList<>(); registrationMap.put(registrationType, handlers); } handlers.add(handler); }

Target:
<T> void put(RegistrationType<T> registrationType, Handler<T> handler) { registrationMap.put(registrationType, handler); }
Source:
public void testToMapWithProperties() throws Exception { when(propertiesMock.entrySet()).thenReturn(exampleMap.entrySet()); Map<?, ?> entries = PROPERTIES_LOADER.toMap(propertiesMock); Assert.assertEquals("Returns a map of the properties", exampleMap, entries); }

Target:
public void testToMapWithProperties() throws Exception { when(propertiesMock.entrySet()).thenReturn(EXAMPLE_MAP.entrySet()); Map<?, ?> entries = PROPERTIES_LOADER.toMap(propertiesMock); assertThat(entries, equalTo(EXAMPLE_MAP)); }
Source:
protected boolean set(ItemStack itemStack, Text value) { if (itemStack.getTagCompound() == null) { itemStack.setTagCompound(new NBTTagCompound()); } itemStack.getTagCompound().setString(NbtDataUtil.ITEM_BOOK_AUTHOR, ((IMixinText) value).toLegacy('\247', Locale.ENGLISH)); return true; }

Target:
protected boolean set(ItemStack itemStack, Text value) { if (!itemStack.hasTagCompound()) { itemStack.setTagCompound(new NBTTagCompound()); } itemStack.getTagCompound().setString(NbtDataUtil.ITEM_BOOK_AUTHOR, Texts.legacy().to(value)); return true; }
Source:
public void resolve(EObject view, TransformationCache cache) { if (view instanceof EEFViewDescription) { List<EEFPageDescription> pages = ((EEFViewDescription) view).getPages(); for (EEFPageDescription page : pages) { List<EEFGroupDescription> groups = page.getGroups(); for (EEFGroupDescription group : groups) { List<EEFPropertyValidationRuleDescription> propertyValidationRules = group.getPropertyValidationRules(); for (EEFPropertyValidationRuleDescription eefPropertyValidationRule : propertyValidationRules) { this.resolve(eefPropertyValidationRule, cache); } } } } }

Target:
public void resolve(EObject view, TransformationCache cache) { if (view instanceof EEFViewDescription) { List<EEFPageDescription> pages = ((EEFViewDescription) view).getPages(); pages.forEach(page -> page.getGroups().forEach(group -> group.getPropertyValidationRules().forEach(propertyValidationRule -> this.resolve(propertyValidationRule, cache)))); } }
Source:
public void shouldBeAbleToSubmitAPartialRefundAfterACaptureHasBeenSubmitted() throws InterruptedException { WorldpayPaymentProvider connector = getValidWorldpayPaymentProvider(); GatewayResponse<WorldpayOrderStatusResponse> response = successfulWorldpayCardAuth(connector); assertThat(response.getBaseResponse().isPresent(), is(true)); String transactionId = response.getBaseResponse().get().getTransactionId(); assertThat(response.isSuccessful(), is(true)); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); GatewayResponse<WorldpayCaptureResponse> captureResponse = connector.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertThat(captureResponse.isSuccessful(), is(true)); RefundEntity refundEntity = new RefundEntity(chargeEntity, 1L, null); GatewayResponse refundGatewayResponse = connector.refund(RefundGatewayRequest.valueOf(refundEntity)); assertTrue(refundGatewayResponse.isSuccessful()); }

Target:
public void shouldBeAbleToSubmitAPartialRefundAfterACaptureHasBeenSubmitted() throws InterruptedException { WorldpayPaymentProvider connector = getValidWorldpayPaymentProvider(); GatewayResponse<WorldpayOrderStatusResponse> response = successfulWorldpayCardAuth(connector); assertThat(response.getBaseResponse().isPresent(), is(true)); String transactionId = response.getBaseResponse().get().getTransactionId(); assertThat(response.isSuccessful(), is(true)); assertThat(transactionId, is(not(nullValue()))); chargeEntity.setGatewayTransactionId(transactionId); GatewayResponse<WorldpayCaptureResponse> captureResponse = connector.capture(CaptureGatewayRequest.valueOf(chargeEntity)); assertThat(captureResponse.isSuccessful(), is(true)); RefundEntity refundEntity = new RefundEntity(chargeEntity, 1L, userExternalId); GatewayResponse refundGatewayResponse = connector.refund(RefundGatewayRequest.valueOf(refundEntity)); assertTrue(refundGatewayResponse.isSuccessful()); }
Source:
public List<RichGroup> getRichSubGroupsWithAttributesByNames(PerunSession sess, Group parentGroup, List<String> attrNames) throws InternalErrorException, GroupNotExistsException, VoNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); this.getGroupsManagerBl().checkGroupExists(sess, parentGroup); Vo vo = perunBl.getVosManagerBl().getVoById(sess, parentGroup.getVoId()); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN)) { throw new PrivilegeException(sess, "getRichSubGroupsWithAttributesByNames"); } List<RichGroup> richGroups = getGroupsManagerBl().filterOnlyAllowedAttributes(sess, getGroupsManagerBl().getAllRichGroupsWithAttributesByNames(sess, vo, attrNames)); if (AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) || AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) || AuthzResolver.hasRole(sess.getPerunPrincipal(), Role.PERUNADMIN)) { return richGroups; } if (AuthzResolver.hasRole(sess.getPerunPrincipal(), Role.GROUPADMIN)) { Iterator<RichGroup> i = richGroups.iterator(); while (i.hasNext()) { if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, i.next())) { i.remove(); } } return richGroups; } throw new PrivilegeException(sess, "getRichSubGroupsWithAttributesByNames"); }

Target:
public List<RichGroup> getRichSubGroupsWithAttributesByNames(PerunSession sess, Group parentGroup, List<String> attrNames) throws InternalErrorException, GroupNotExistsException, VoNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); this.getGroupsManagerBl().checkGroupExists(sess, parentGroup); Vo vo = perunBl.getVosManagerBl().getVoById(sess, parentGroup.getVoId()); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN)) { throw new PrivilegeException(sess, "getRichSubGroupsWithAttributesByNames"); } List<RichGroup> richGroups = getGroupsManagerBl().getAllRichGroupsWithAttributesByNames(sess, vo, attrNames); if (AuthzResolver.hasRole(sess.getPerunPrincipal(), Role.GROUPADMIN)) { Iterator<RichGroup> i = richGroups.iterator(); while (i.hasNext()) { if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, i.next())) { i.remove(); } } } return getGroupsManagerBl().filterOnlyAllowedAttributes(sess, richGroups); }
Source:
public CdsQuote pointsUpFrontFromQuotedSpread( ResolvedCdsTrade trade, CdsQuote quote, CreditRatesProvider ratesProvider, ReferenceData refData) { ArgChecker.notNull(trade, "trade"); ArgChecker.notNull(quote, "quote"); ArgChecker.notNull(ratesProvider, "ratesProvider"); ArgChecker.notNull(refData, "refData"); ArgChecker.isTrue(quote.getQuoteConvention().equals(CdsQuoteConvention.QUOTED_SPREAD), "quote must be quoted spread"); ResolvedCds product = trade.getProduct(); Currency currency = product.getCurrency(); StandardId legalEntityId = product.getLegalEntityId(); LocalDate valuationDate = ratesProvider.getValuationDate(); NodalCurve creditCurve = builder.calibrate( new ResolvedCdsTrade[] {trade}, new double[] {quote.getQuotedValue()}, new double[] {0d}, CurveName.of("temp"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData); CreditRatesProvider ratesProviderNew = ratesProvider.toBuilder() .creditCurves(ImmutableMap.of( Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of( legalEntityId, IsdaCompliantZeroRateDiscountFactors.of(currency, valuationDate, creditCurve)))) .build(); double puf = pointsUpfront(trade, ratesProviderNew, refData); return CdsQuote.of(CdsQuoteConvention.POINTS_UPFRONT, puf); }

Target:
public CdsQuote pointsUpFrontFromQuotedSpread( ResolvedCdsTrade trade, CdsQuote quote, CreditRatesProvider ratesProvider, ReferenceData refData) { ArgChecker.notNull(trade, "trade"); ArgChecker.notNull(quote, "quote"); ArgChecker.notNull(ratesProvider, "ratesProvider"); ArgChecker.notNull(refData, "refData"); ArgChecker.isTrue(quote.getQuoteConvention().equals(CdsQuoteConvention.QUOTED_SPREAD), "quote must be quoted spread"); ResolvedCds product = trade.getProduct(); Currency currency = product.getCurrency(); StandardId legalEntityId = product.getLegalEntityId(); LocalDate valuationDate = ratesProvider.getValuationDate(); NodalCurve creditCurve = calibrator.calibrate( ImmutableList.of(trade), DoubleArray.of(quote.getQuotedValue()), DoubleArray.of(0d), CurveName.of("temp"), valuationDate, ratesProvider.discountFactors(currency), ratesProvider.recoveryRates(legalEntityId), refData); CreditRatesProvider ratesProviderNew = ratesProvider.toBuilder() .creditCurves(ImmutableMap.of( Pair.of(legalEntityId, currency), LegalEntitySurvivalProbabilities.of( legalEntityId, IsdaCompliantZeroRateDiscountFactors.of(currency, valuationDate, creditCurve)))) .build(); double puf = pointsUpfront(trade, ratesProviderNew, refData); return CdsQuote.of(CdsQuoteConvention.POINTS_UPFRONT, puf); }
Source:
public void deleteAll(String sessionId) { ArrayList<String> sessions = (ArrayList) getHibernateTemplate().find("Select distinct k.sessionId from KeyValue k ORDER by k.sessionId"); if (sessions.size() == 0) return; if (sessionLimit < 0) { log.warn("Session count can't be < 0; was get {}", sessionLimit); return; } if (sessionLimit == 0) { log.warn("Session count limit is equal '0', all temporary data about sessions will be delete"); getHibernateTemplate().bulkUpdate("delete from KeyValue"); return; } List<String> sessionForDelete = Lists.newArrayList(); sessionForDelete.add(sessionId); if (sessions.size() > sessionLimit) { sessionForDelete.addAll(sessions.subList(0, (sessions.size() - 1) - sessionLimit)); } getHibernateTemplate().bulkUpdate("delete from KeyValue where sessionId in (?)", sessionForDelete.toArray()); }

Target:
public void deleteAll(String sessionId) { ArrayList<String> sessions = (ArrayList) getHibernateTemplate().find("Select distinct k.sessionId from KeyValue k ORDER by k.sessionId"); if (sessions.size() == 0) return; if (sessionLimit == 0) { log.warn("Session count limit is equal '0', all temporary data about sessions will be delete"); getHibernateTemplate().bulkUpdate("delete from KeyValue"); return; } List<String> sessionForDelete = Lists.newArrayList(); sessionForDelete.add(sessionId); if (sessions.size() > sessionLimit) { sessionForDelete.addAll(sessions.subList(0, (sessions.size() - 1) - sessionLimit)); } getHibernateTemplate().bulkUpdate("delete from KeyValue where sessionId in (?)", sessionForDelete.toArray()); }
Source:
private String getContributionOptionsColor(int points){ if(points == Const.POINTS_NOT_SURE || points == Const.POINTS_EQUAL_SHARE){ return "color_neutral"; } else if ( points < 100){ return "color-negative"; } else{ return "color-positive"; } }

Target:
private String getContributionOptionsColor(int points){ if(points == Const.POINTS_NOT_SURE || points == Const.POINTS_EQUAL_SHARE){ return "color_neutral"; } else if ( points < Const.POINTS_EQUAL_SHARE){ return "color-negative"; } else{ return "color-positive"; } }
Source:
private String getSuitablePathVariable(IPath commonPath) { String variableName = commonPath.lastSegment(); if (variableName == null) { variableName = commonPath.getDevice(); if (variableName == null) variableName = "ROOT"; else variableName = variableName.substring(0, variableName.length() -1); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < variableName.length(); i++) { char c = variableName.charAt(i); if (Character.isLetterOrDigit(c) || (c == '_')) buf.append(c); else buf.append('_'); } int index = 1; while (fProject.getPathVariableManager().isDefined(variableName)) { buf.append(index); index++; } return buf.toString(); }

Target:
private String getSuitablePathVariable(IPath commonPath) { String variableName = commonPath.lastSegment(); if (variableName == null) { variableName = commonPath.getDevice(); if (variableName == null) variableName = "ROOT"; else variableName = variableName.substring(0, variableName.length() -1); } StringBuilder buf = new StringBuilder(); for (int i = 0; i < variableName.length(); i++) { char c = variableName.charAt(i); if (Character.isLetterOrDigit(c) || (c == '_')) buf.append(c); else buf.append('_'); } int index = 1; while (fProject.getPathVariableManager().isDefined(buf.toString())) { buf.append(index); index++; } return buf.toString(); }
Source:
private void startAccountCreation() { if (PreferencesHelper.getCreateAccountStatus() == CreateAccountStatus.WAITING_FOR_SMS) { startActivity(new Intent(this, VerifyNumberActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)); } else { startActivity(new Intent(this, AgreeActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)); } finish(); }

Target:
private void startAccountCreation() { final Class<?> activity = PreferencesHelper.getCreateAccountStatus() == CreateAccountStatus.WAITING_FOR_SMS ? VerifyNumberActivity.class : AgreeActivity.class; startActivity(new Intent(this, activity).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)); finish(); }
Source:
private static HttpServer createServer(NodeInfo nodeInfo, HttpServerInfo httpServerInfo, HttpServerConfig config) { return createServer(new DummyServlet(Optional.empty()), nodeInfo, httpServerInfo, config); }

Target:
private static HttpServer createServer(NodeInfo nodeInfo, HttpServerInfo httpServerInfo, HttpServerConfig config) { return createServer(new DummyServlet(), nodeInfo, httpServerInfo, config); }
Source:
private String readFile(File directory, String fileName) throws IOException { File file = new File(directory, fileName); FileReader fr = new FileReader(file); StringBuilder sb = new StringBuilder(); char[] chars = new char[100]; int read = fr.read(chars); while (read > -1) { sb.append(chars, 0, read); read = fr.read(chars); } return sb.toString(); }

Target:
private String readFile(File directory, String fileName) throws IOException { return RawParseUtils .decode(IO.readFully(new File(directory, fileName))); }
Source:
private static Number compare(Object a, Object b) { Number compareResult = null; if (a instanceof Number && b instanceof Number) { compareResult = Numbers.compare((Number) a, (Number) b); } else if (a instanceof Number) { compareResult = -1; } else if (b instanceof Number) { compareResult = 1; } else { compareResult = a.toString().compareTo(b.toString()); } return compareResult; }

Target:
private static int compare(Object a, Object b) { return Value.Sorter.INSTANCE .compare(Value.wrap(Convert.javaToThrift(a)), Value.wrap(Convert.javaToThrift(b))); }
Source:
static org.ovirt.engine.api.model.Event getModel(int index) { org.ovirt.engine.api.model.Event model = new org.ovirt.engine.api.model.Event(); model.setId(String.valueOf(LOG_IDS[index])); model.setSeverity(AuditLogSeverity.ALERT.name()); model.setDescription(MESSAGES[index]); model.setOrigin(ORIGIN_NAMES[index]); model.setCustomId(CUSTOMER_EVENT_IDS[index]); model.setFloodRate(30); return model; }

Target:
static org.ovirt.engine.api.model.Event getModel(int index) { org.ovirt.engine.api.model.Event model = new org.ovirt.engine.api.model.Event(); model.setId(String.valueOf(LOG_IDS[index])); model.setSeverity( LogSeverity.ALERT.value()); model.setDescription(MESSAGES[index]); model.setOrigin(ORIGIN_NAMES[index]); model.setCustomId(CUSTOMER_EVENT_IDS[index]); model.setFloodRate(30); return model; }
Source:
public static Set<Bundle> getBundlesBySymbolicName(BundleContext bundleContext, String symbolicName) { return Arrays.stream(bundleContext.getBundles()) .filter(bundle -> bundle.adapt(BundleRevision.class).getSymbolicName().equals(symbolicName)) .collect(toSet()); }

Target:
public static Set<Bundle> getBundlesBySymbolicName(BundleContext bundleContext, String symbolicName) { return Arrays.stream(bundleContext.getBundles()) .filter(bundle -> symbolicName.equals(bundle.adapt(BundleRevision.class).getSymbolicName())) .collect(toSet()); }
Source:
private void checkPermission(String userId) throws ForbiddenException { Preconditions.checkNotNull(userId); final Set<String> teams = teamOperations.getTeamIdsByUser(userId); final List<String> allowedTeams = ruleControllerProperties.getAllowedTeams(); if (allowedTeams.stream().noneMatch(teams::contains)){ throw new ForbiddenException(format("%s has no permission! Found Teams: %s; required teams %s", userId, teams, allowedTeams)); } }

Target:
private void checkPermission(String userId) throws ForbiddenException { Preconditions.checkNotNull(userId, "userId must not be null!"); final Set<String> teams = teamOperations.getTeamIdsByUser(userId); final List<String> allowedTeams = ruleControllerProperties.getAllowedTeams(); if (allowedTeams.stream().noneMatch(teams::contains)){ throw new ForbiddenException(format("%s has no permission! Found Teams: %s; required teams %s", userId, teams, allowedTeams)); } }
Source:
public void refresh(boolean refreshGlobal, boolean refreshSelection) { if(fModel == null){ reinitializeCharts(); } else { if(refreshGlobal){ getCurrentState().newGlobalEntries(this); } if(refreshSelection){ long Tot = 0; int nbEventsType = 0; Map<String, Long> selectionModel = getTotalEventCountForChart(false); for (Long l : selectionModel.values()) { if(l != 0){ nbEventsType++; Tot += l; } } if (Tot == 0 || nbEventsType < 2) { getCurrentState().newEmptySelection(this); } else { getCurrentState().newSelection(this); } } } }

Target:
public synchronized void refresh(boolean refreshGlobal, boolean refreshSelection) { if(fModel == null){ reinitializeCharts(); } else { if(refreshGlobal){ getCurrentState().newGlobalEntries(this); } if(refreshSelection){ int nbEventsType = 0; Map<String, Long> selectionModel = getTotalEventCountForChart(false); for (Long l : selectionModel.values()) { if(l != 0){ nbEventsType++; } } if (nbEventsType < 2) { getCurrentState().newEmptySelection(this); } else { getCurrentState().newSelection(this); } } } }
Source:
public int hashCode() { if (isEmpty()) { return Objects.hash(comparer); } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; }

Target:
public int hashCode() { if (isEmpty()) { return Objects.hashCode(comparer); } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; }
Source:
private Map<String, String> envVars() { Map<String, String> env = new HashMap<>(); env.put("P4PORT", material.getServerAndPort()); env.put("P4CLIENT", clientName); if (!StringUtil.isBlank(material.getUserName())) { env.put("P4USER", material.getUserName()); } if (material.getUseTickets() && !StringUtil.isBlank(material.getPassword())) { env.put("P4PASSWD", material.getPassword()); } return env; }

Target:
private Map<String, String> envVars() { Map<String, String> env = new HashMap<>(); env.put("P4PORT", material.getServerAndPort()); env.put("P4CLIENT", clientName); if (!StringUtil.isBlank(material.getUserName())) { env.put("P4USER", material.getUserName()); } if (!material.getUseTickets() && !StringUtil.isBlank(material.getPassword())) { env.put("P4PASSWD", material.getPassword()); } return env; }
Source:
public void openContainer(Container container) { if (openContainer != inventoryContainer) { closeScreen(); } IInventory containerInventory = ((MinecraftInventoryAdapter) container).getInventory().get(0); String guiId = containerInventory instanceof IInteractionObject ? ((IInteractionObject) containerInventory).getGuiID() : "minecraft:chest"; this.getNextWindowId(); this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, guiId, containerInventory.getDisplayName(), containerInventory.getSizeInventory())); this.openContainer = (net.minecraft.inventory.Container) container; this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this$); }

Target:
public void openContainer(Container container) { if (this.openContainer != this.inventoryContainer) { closeScreen(); } IInventory containerInventory = ((MinecraftInventoryAdapter) container).getInventory().get(0); String guiId = containerInventory instanceof IInteractionObject ? ((IInteractionObject) containerInventory).getGuiID() : "minecraft:chest"; getNextWindowId(); this.connection.sendPacket(new SPacketOpenWindow(this.currentWindowId, guiId, containerInventory.getDisplayName(), containerInventory.getSizeInventory())); this.openContainer = (net.minecraft.inventory.Container) container; this.openContainer.windowId = this.currentWindowId; this.openContainer.addListener(this.this$); }
Source:
protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) throws Exception { String password = form.getFieldValue("password"); Application application = (Application) request.getAttribute(Application.class.getName()); String sptoken = form.getFieldValue("sptoken"); if (isJsonPreferred(request, response)) { Map<String, Object> model = new HashMap<String, Object>(); try { Account account = application.resetPassword(sptoken, password); if (autoLogin){ model.put("status", "200"); model.put("account", accountModelFactory.toMap(account, Collections.EMPTY_LIST)); } else { model.put("status", "200"); model.put("message", "OK"); } } catch (ResourceException re) { model = errorMap.toErrorMap(re.getStormpathError()); } catch (Exception e) { Map<String, Object> exceptionErrorMap = new HashMap<String, Object>(); exceptionErrorMap.put("message", e.getMessage()); exceptionErrorMap.put("status", 400); DefaultError error = new DefaultError(exceptionErrorMap); model = errorMap.toErrorMap(error); } return new DefaultViewModel("stormpathJsonView", model); } application.resetPassword(sptoken, password); String next; if (autoLogin){ next = loginNextUri; } else{ next = this.nextUri; } return new DefaultViewModel(next).setRedirect(true); }

Target:
protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) throws Exception { String password = form.getFieldValue("password"); Application application = (Application) request.getAttribute(Application.class.getName()); String sptoken = form.getFieldValue("sptoken"); if (isJsonPreferred(request, response)) { Map<String, Object> model = new HashMap<String, Object>(); try { Account account = application.resetPassword(sptoken, password); if (autoLogin){ final AuthenticationResult result = new TransientAuthenticationResult(account); this.authenticationResultSaver.set(request, response, result); model.put("account", accountModelFactory.toMap(account, Collections.EMPTY_LIST)); } else { response.setContentType(MediaType.APPLICATION_JSON_VALUE); return null; } } catch (Exception e) { model = errorModelFactory.toError(request, e).toMap(); response.setStatus(errorModelFactory.toError(request, e).getStatus()); } return new DefaultViewModel("stormpathJsonView", model); } String next; try { Account account = application.resetPassword(sptoken, password); if (autoLogin){ final AuthenticationResult result = new TransientAuthenticationResult(account); this.authenticationResultSaver.set(request, response, result); next = loginNextUri; } else{ next = this.nextUri; } } catch (Exception e) { next = errorUri; } return new DefaultViewModel(next).setRedirect(true); }
Source:
private void addVideoCardByDisplayType(DisplayType displayType, int numOfMonitors) { Map<String, Object> struct = new HashMap<String, Object>(); VmDeviceType vmDeviceType = getOsRepository().getDisplayDevice(vm.getOs(), vm.getVdsGroupCompatibilityVersion(), vm.getDefaultDisplayType()); struct.put(VdsProperties.Type, VmDeviceGeneralType.VIDEO.getValue()); struct.put(VdsProperties.Device, vmDeviceType); struct.put(VdsProperties.SpecParams, getNewMonitorSpecParams(displayType, numOfMonitors)); struct.put(VdsProperties.DeviceId, String.valueOf(Guid.newGuid())); devices.add(struct); }

Target:
private void addVideoCardByDisplayType(DisplayType displayType, int numOfMonitors) { Map<String, Object> struct = new HashMap<String, Object>(); VmDeviceType vmDeviceType = getOsRepository().getDisplayDevice(vm.getOs(), vm.getVdsGroupCompatibilityVersion(), displayType); struct.put(VdsProperties.Type, VmDeviceGeneralType.VIDEO.getValue()); struct.put(VdsProperties.Device, vmDeviceType); struct.put(VdsProperties.SpecParams, getNewMonitorSpecParams(displayType, numOfMonitors)); struct.put(VdsProperties.DeviceId, String.valueOf(Guid.newGuid())); devices.add(struct); }
Source:
public PaymentState(String status, boolean finished) { this(status, finished, null, null, null); }

Target:
public PaymentState(String status, boolean finished) { this(status, finished, null, null); }
Source:
protected VDSBrokerFrontend getVdsBroker() { return Backend.getInstance().getResourceManager(); }

Target:
protected VDSBrokerFrontend getVdsBroker() { return getBackend().getResourceManager(); }
Source:
public Module getProgramsGrammar(Module mod) { scala.collection.Set<Module> modules = org.kframework.Collections.Set(mod, baseK.getModule(PROGRAM_LISTS).get()); Option<Module> idOpt = baseK.getModule(ID); if(idOpt.isDefined() && !mod.equals(idOpt.get())) modules = org.kframework.Collections.add(idOpt.get(), modules); return Module.apply(mod.name() + POSTFIX, modules, Set(), Att()); }

Target:
public Module getProgramsGrammar(Module mod) { if(mod.name().endsWith(POSTFIX)) { return mod; } else { scala.collection.Set<Module> modules = Set(mod, baseK.getModule(PROGRAM_LISTS).get()); if (stream(mod.importedModules()).anyMatch(m -> m.name().equals(ID))) { Module idProgramParsingModule = baseK.getModule(ID_PROGRAM_PARSING).get(); modules = add(idProgramParsingModule, modules); } return Module.apply(mod.name() + POSTFIX, modules, Set(), Att()); } }
Source:
public int hashCode() { return Objects.hash(buildConfiguration, Arrays.asList(requestedBuilt), Arrays.asList(buildOrder)); }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + buildConfiguration.hashCode(); result = prime * result + Arrays.hashCode(requestedBuilt); result = prime * result + Arrays.hashCode(buildOrder); return result; }
Source:
public List<CurrencyPair> getExchangeSymbols() throws IOException { try { List<CurrencyPair> currencyPairs = new ArrayList<>(); for (String symbol : bitfinex.getSymbols()) { currencyPairs.add(BitfinexAdapters.adaptCurrencyPair(symbol)); } return currencyPairs; } catch (BitfinexException e) { throw BitfinexErrorAdapter.adapt(e); } }

Target:
public List<CurrencyPair> getExchangeSymbols() throws IOException { List<CurrencyPair> currencyPairs = new ArrayList<>(); for (String symbol : bitfinex.getSymbols()) { currencyPairs.add(BitfinexAdapters.adaptCurrencyPair(symbol)); } return currencyPairs; }
Source:
public void testObtainThenSuspendThenResumeMachine() throws Exception { MachineLocation machine = obtainMachine(ImmutableMap.of( "imageId", EUWEST_IMAGE_ID)); assertTrue(machine instanceof JcloudsSshMachineLocation); JcloudsSshMachineLocation sshMachine = (JcloudsSshMachineLocation) machine; assertTrue(sshMachine.isSshable(), "Cannot SSH to " + sshMachine); suspendMachine(machine); assertFalse(sshMachine.isSshable(), "Should not be able to SSH to suspended machine"); MachineLocation machine2 = resumeMachine(ImmutableMap.of("id", sshMachine.getJcloudsId())); assertTrue(machine2 instanceof JcloudsSshMachineLocation); assertTrue(((JcloudsSshMachineLocation) machine2).isSshable(), "Cannot SSH to " + machine2); }

Target:
public void testObtainThenSuspendThenResumeMachine() throws Exception { MachineLocation machine = obtainMachine(ImmutableMap.of( "imageId", EUWEST_IMAGE_ID)); JcloudsSshMachineLocation sshMachine = (JcloudsSshMachineLocation) machine; assertTrue(sshMachine.isSshable(), "Cannot SSH to " + sshMachine); suspendMachine(machine); assertFalse(sshMachine.isSshable(), "Should not be able to SSH to suspended machine"); MachineLocation machine2 = resumeMachine(ImmutableMap.of("id", sshMachine.getJcloudsId())); assertTrue(machine2 instanceof JcloudsSshMachineLocation); assertTrue(((JcloudsSshMachineLocation) machine2).isSshable(), "Cannot SSH to " + machine2); }
Source:
public void registerCachedFile(String filePath, String name) { this.cacheFile.put(name, filePath); }

Target:
public void registerCachedFile(String filePath, String name) throws RuntimeException{ if (!this.cacheFile.containsKey(name)) { this.cacheFile.put(name, filePath); } else { throw new RuntimeException("cache file " + name + "already exists!"); } }
Source:
public void parsingOnlineFile(final int configurationIndex, final String predictionFileName) throws PerfEnforceException { try { BufferedReader streamReader = new BufferedReader(new FileReader(predictionFileName)); String currentLine = ""; double nextQueryPrediction = 0; while ((currentLine = streamReader.readLine()) != null) { nextQueryPrediction = Double.parseDouble((currentLine.split(",")[0]).split(":")[1]); } streamReader.close(); queryPredictions[configurationIndex] = nextQueryPrediction; } catch (Exception e) { throw new PerfEnforceException("Error parsing online predictions file"); } }

Target:
public void parsingOnlineFile(final int configurationIndex, final String predictionFileName) throws PerfEnforceException { try (BufferedReader streamReader = new BufferedReader(new FileReader(predictionFileName))) { String currentLine = ""; double nextQueryPrediction = 0; while ((currentLine = streamReader.readLine()) != null) { nextQueryPrediction = Double.parseDouble((currentLine.split(",")[0]).split(":")[1]); } queryPredictions[configurationIndex] = nextQueryPrediction; } catch (Exception e) { throw new PerfEnforceException("Error parsing online predictions file"); } }
Source:
public void init() { get("/transformers/metacard", (req, res) -> GSON.toJson(metacardTransformers)); get( "/transformers/metacard/:id", (req, res) -> { String id = req.params(":id"); Map<String, String> descriptor = getTransformerDescriptor(metacardTransformers, id); if (descriptor == null) { res.status(404); return GSON.toJson(NOT_FOUND_RESPONSE); } return GSON.toJson(descriptor); }); get("/transformers/query", (req, res) -> GSON.toJson(queryResponseTransformers)); get( "/transformers/query/:id", (req, res) -> { String id = req.params(":id"); Map<String, String> descriptor = getTransformerDescriptor(queryResponseTransformers, id); if (descriptor == null) { res.status(404); return GSON.toJson(NOT_FOUND_RESPONSE); } return GSON.toJson(descriptor); }); }

Target:
public void init() { get( "/transformers/metacard", (req, res) -> { res.type("application/json"); return descriptors.getMetacardTransformers(); }, GSON::toJson); get( "/transformers/query", (req, res) -> { res.type("application/json"); return descriptors.getQueryResponseTransformers(); }, GSON::toJson); get( "/transformers/:type/:id", (req, res) -> { String id = req.params(":id"); String type = req.params(":type").toLowerCase(); Map<String, String> descriptor; res.type("application/json"); if (METACARD_TRANSFORMER.equals(type)) { descriptor = descriptors.getMetacardTransformer(id); } else if (QUERY_RESPONSE_TRANSFORMER.equals(type)) { descriptor = descriptors.getQueryResponseTransformer(id); } else { res.status(404); return GSON.toJson(TRANSFORMER_TYPE_NOT_FOUND_RESPONSE); } if (descriptor == null) { res.status(404); return GSON.toJson(TRANSFORMER_NOT_FOUND_RESPONSE); } return GSON.toJson(descriptor); }); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KafkaTuningConfig that = (KafkaTuningConfig) o; return maxRowsInMemory == that.maxRowsInMemory && maxRowsPerSegment == that.maxRowsPerSegment && maxBytesInMemory == this.maxBytesInMemory && maxPendingPersists == that.maxPendingPersists && reportParseExceptions == that.reportParseExceptions && handoffConditionTimeout == that.handoffConditionTimeout && resetOffsetAutomatically == that.resetOffsetAutomatically && Objects.equals(intermediatePersistPeriod, that.intermediatePersistPeriod) && Objects.equals(basePersistDirectory, that.basePersistDirectory) && Objects.equals(indexSpec, that.indexSpec) && Objects.equals(segmentWriteOutMediumFactory, that.segmentWriteOutMediumFactory) && Objects.equals(intermediateHandoffPeriod, that.intermediateHandoffPeriod); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KafkaTuningConfig that = (KafkaTuningConfig) o; return maxRowsInMemory == that.maxRowsInMemory && maxRowsPerSegment == that.maxRowsPerSegment && maxBytesInMemory == that.maxBytesInMemory && maxPendingPersists == that.maxPendingPersists && reportParseExceptions == that.reportParseExceptions && handoffConditionTimeout == that.handoffConditionTimeout && resetOffsetAutomatically == that.resetOffsetAutomatically && Objects.equals(intermediatePersistPeriod, that.intermediatePersistPeriod) && Objects.equals(basePersistDirectory, that.basePersistDirectory) && Objects.equals(indexSpec, that.indexSpec) && Objects.equals(segmentWriteOutMediumFactory, that.segmentWriteOutMediumFactory) && Objects.equals(intermediateHandoffPeriod, that.intermediateHandoffPeriod) && logParseExceptions == that.logParseExceptions && maxParseExceptions == that.maxParseExceptions && maxSavedParseExceptions == that.maxSavedParseExceptions; }
Source:
public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object structSelection = ((IStructuredSelection) selection).getFirstElement(); if (structSelection instanceof KernelMemoryUsageEntry) { KernelMemoryUsageEntry entry = (KernelMemoryUsageEntry) structSelection; fTreeViewerReference.setSelectedThread(entry.getTid()); ((KernelMemoryUsageViewer) getChartViewer()).setSelectedThread(entry.getTid()); ITmfTrace trace = fTreeViewerReference.getTrace(); if (trace == null) { return; } TmfTraceManager.getInstance().updateTraceContext(trace, builder -> builder.setData(KERNEL_MEMORY, checkNotNull(entry.getTid()))); } } }

Target:
public void selectionChanged(SelectionChangedEvent event) { KernelMemoryUsageTreeViewer treeViewer = fTreeViewerReference; KernelMemoryUsageViewer chartViewer = (KernelMemoryUsageViewer) getChartViewer(); if (treeViewer == null || chartViewer == null) { return; } ITmfTrace trace = treeViewer.getTrace(); if (trace == null) { return; } ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object structSelection = ((IStructuredSelection) selection).getFirstElement(); if (structSelection instanceof KernelMemoryUsageEntry) { KernelMemoryUsageEntry entry = (KernelMemoryUsageEntry) structSelection; String tid = entry.getTid(); if (tid == null) { return; } treeViewer.setSelectedThread(tid); chartViewer.setSelectedThread(tid); TmfTraceManager.getInstance().updateTraceContext(trace, builder -> builder.setData(KERNEL_MEMORY, tid)); } } }
Source:
private BigtableOptions( InetAddress clusterAdminHost, InetAddress tableAdminHost, InetAddress dataHost, int port, String projectId, String zone, String cluster, EventLoopGroup customEventLoopGroup, ChannelOptions channelOptions) { Preconditions.checkArgument( !Strings.isNullOrEmpty(projectId), "ProjectId must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(zone), "Zone must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(cluster), "Cluster must not be empty or null."); Preconditions.checkNotNull(channelOptions, "ChannelCoptions must not be empty or null."); Preconditions.checkArgument(!Strings.isNullOrEmpty(channelOptions.getUserAgent()), "UserAgent must not be empty or null"); this.tableAdminHost = Preconditions.checkNotNull(tableAdminHost); this.clusterAdminHost = Preconditions.checkNotNull(clusterAdminHost); this.dataHost = Preconditions.checkNotNull(dataHost); this.port = port; this.projectId = projectId; this.zone = zone; this.cluster = cluster; this.customEventLoopGroup = customEventLoopGroup; this.channelOptions = channelOptions; LOG.debug("Connection Configuration: project: %s, cluster: %s, data host %s, " + "table admin host %s, cluster admin host %s using transport %s.", projectId, cluster, dataHost, tableAdminHost, clusterAdminHost, TransportOptions.BigtableTransports.HTTP2_NETTY_TLS); }

Target:
private BigtableOptions( InetAddress clusterAdminHost, InetAddress tableAdminHost, InetAddress dataHost, int port, String projectId, String zone, String cluster, EventLoopGroup customEventLoopGroup, ChannelOptions channelOptions) { Preconditions.checkArgument( !Strings.isNullOrEmpty(projectId), "ProjectId must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(zone), "Zone must not be empty or null."); Preconditions.checkArgument( !Strings.isNullOrEmpty(cluster), "Cluster must not be empty or null."); Preconditions.checkNotNull(channelOptions, "ChannelCoptions must not be empty or null."); this.tableAdminHost = Preconditions.checkNotNull(tableAdminHost); this.clusterAdminHost = Preconditions.checkNotNull(clusterAdminHost); this.dataHost = Preconditions.checkNotNull(dataHost); this.port = port; this.projectId = projectId; this.zone = zone; this.cluster = cluster; this.customEventLoopGroup = customEventLoopGroup; this.channelOptions = channelOptions; LOG.debug("Connection Configuration: project: %s, cluster: %s, data host %s, " + "table admin host %s, cluster admin host %s using transport %s.", projectId, cluster, dataHost, tableAdminHost, clusterAdminHost, TransportOptions.BigtableTransports.HTTP2_NETTY_TLS); }
Source:
public void testParFragment() { SequenceParValid diagValid = new SequenceParValid(); SequenceDiagramExecutor executor = SequenceDiagramExecutor.create(); executor.setDiagram(diagValid).run(); Assert.assertEquals(0, executor.getErrors().size()); SequenceParErr diagErr = new SequenceParErr(); executor = SequenceDiagramExecutor.create(); executor.setDiagram(diagErr).run();; Assert.assertEquals(3, executor.getErrors().size()); }

Target:
public void testParFragment() { SequenceParValid diagValid = new SequenceParValid(); SequenceDiagramExecutor executor = SequenceDiagramExecutor.create(); executor.setDiagram(diagValid).run(); Assert.assertEquals(0, executor.getErrors().size()); SequenceParErr diagErr = new SequenceParErr(); executor = SequenceDiagramExecutor.create(); executor.setDiagram(diagErr).run(); Assert.assertEquals(3, executor.getErrors().size()); }
Source:
public int hashCode(){ return (int)id; }

Target:
public int hashCode(){ return Objects.hashCode(this.id); }
Source:
public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { tryBackParams.setDisks(getParent().mapDisks(action.getDisks())); } if (action.isSetLease()) { tryBackParams.setRestoreLease(action.getLease().isSetStorageDomain()); } if (action.isSetLease() && action.getLease().isSetStorageDomain()) { tryBackParams.setDstLeaseDomainId(asGuid(action.getLease().getStorageDomain().getId())); } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }

Target:
public Response previewSnapshot(Action action) { validateParameters(action, "snapshot.id"); TryBackToAllSnapshotsOfVmParameters tryBackParams = new TryBackToAllSnapshotsOfVmParameters(guid, asGuid(action.getSnapshot().getId())); if (action.isSetRestoreMemory()) { tryBackParams.setRestoreMemory(action.isRestoreMemory()); } if (action.isSetDisks()) { tryBackParams.setDisks(getParent().mapDisks(action.getDisks())); } if (action.isSetLease()) { tryBackParams.setRestoreLease(action.getLease().isSetStorageDomain()); if (action.getLease().isSetStorageDomain()) { tryBackParams.setDstLeaseDomainId(asGuid(action.getLease().getStorageDomain().getId())); } } Response response = doAction(ActionType.TryBackToAllSnapshotsOfVm, tryBackParams, action); return response; }
Source:
private int getColumnWidth(final Pattern52 pattern) { if (pattern.getBoundName() == null || pattern.getBoundName().trim().isEmpty()) { return 1; } else { return pattern.getChildColumns().size(); } }

Target:
private int getColumnWidth(final Pattern52 pattern) { if (StringUtils.isEmpty(pattern.getBoundName())) { return 1; } else { return pattern.getChildColumns().size(); } }
Source:
public void save(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException(ERROR_MESSAGE_NO_PATIENT_CLASS); } PatientData<String> lifeStatus = patient.getData(DATA_NAME); PatientData<Date> dates = patient.getData("dates"); Integer deathDateUnknown = 0; if (lifeStatus != null && lifeStatus.getValue().equals(DECEASED)) { deathDateUnknown = 1; } if (dates != null && dates.isNamed()) { Date deathDate = dates.get(PATIENT_DATEOFDEATH_FIELDNAME); if (deathDate != null) { deathDateUnknown = 0; } return; } data.setIntValue(PATIENT_UNKNOWN_DATEOFDEATH_FIELDNAME, deathDateUnknown); this.xcontext.get().getWiki().saveDocument(doc, "Updated life status from JSON", true, this.xcontext.get()); } catch (Exception e) { this.logger.error("Failed to save life status: [{}]", e.getMessage()); } }

Target:
public void save(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { throw new NullPointerException(ERROR_MESSAGE_NO_PATIENT_CLASS); } PatientData<String> lifeStatus = patient.getData(DATA_NAME); PatientData<Date> dates = patient.getData("dates"); Integer deathDateUnknown = 0; if (lifeStatus != null && DECEASED.equals(lifeStatus.getValue())) { deathDateUnknown = 1; } if (dates != null && dates.isNamed()) { Date deathDate = dates.get(PATIENT_DATEOFDEATH_FIELDNAME); if (deathDate != null) { deathDateUnknown = 0; } return; } data.setIntValue(PATIENT_UNKNOWN_DATEOFDEATH_FIELDNAME, deathDateUnknown); this.xcontext.get().getWiki().saveDocument(doc, "Updated life status from JSON", true, this.xcontext.get()); } catch (Exception e) { this.logger.error("Failed to save life status: [{}]", e.getMessage()); } }
Source:
private void onGetDiagramByPathSuccess(MarshallingResponse<ProjectDiagram> response, Path path, PlaceRequest place) { if (response.isSuccess()) { final Command doMigrate = () -> fromJBPMDesignerToStunner(response.getResult().get(), path, place); if (!response.getMessages().isEmpty()) { showResultSuccessful(response.getMessages(), doMigrate); } else { doMigrate.execute(); } } else { showResultWithErrors(response.getMessages()); } }

Target:
private void onGetDiagramByPathSuccess(MarshallingResponse<ProjectDiagram> response, Path path, PlaceRequest place) { if (response.isSuccess()) { final ProjectDiagram diagram = response.getResult().orElse(null); if (diagram == null) { errorPopup.showMessage(translationService.getValue(IntegrationClientConstants.MigrateToStunnerNoDiagramHasBeenReturned)); } else { final Command doMigrate = () -> fromJBPMDesignerToStunner(diagram, path, place); if (!response.getMessages().isEmpty()) { showResultSuccessful(response.getMessages(), doMigrate); } else { doMigrate.execute(); } } } else { showResultWithErrors(response.getMessages()); } }