auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <V> Optional<V> getOption(ParticleOption<V> option) { return (Optional) Optional.ofNullable(this.options.get(option)); }

Target:
public <V> Optional<V> getOption(ParticleOption<V> option) { return Optional.ofNullable((V) this.options.get(option)); }
Source:
public void setMode(String mode) { String capitalizedMode = mode.toUpperCase(); if (MODE_PREPEND.equals(capitalizedMode) || MODE_APPEND.equals(capitalizedMode) || MODE_OVERWRITE.equals(capitalizedMode)) { this.mode = capitalizedMode; } else { throw new IllegalArgumentException( "Binding mode should be either '" + MODE_PREPEND + "', '" + MODE_APPEND + "' or '" + MODE_OVERWRITE + "'. Instead found '" + mode + "'."); } }

Target:
public void setMode(String mode) { if (MODE_PREPEND.equals(mode) || MODE_APPEND.equals(mode) || MODE_OVERWRITE.equals(mode)) { this.mode = mode; } else { throw new IllegalArgumentException( "Binding mode should be either '" + MODE_PREPEND + "', '" + MODE_APPEND + "' or '" + MODE_OVERWRITE + "'. Instead found '" + mode + "'."); } }
Source:
public void delete(ClaudiaData claudiaData, NetworkInstance networkInstance, String region) throws InvalidEntityException, InfrastructureException { log.info("Destroying network " + networkInstance.getNetworkName() + " region " + region); try { networkInstance = load(networkInstance.getNetworkName(), claudiaData.getVdc(), region); } catch (EntityNotFoundException e) { log.error("Error to remove the network in BD " + e.getMessage()); throw new InvalidEntityException(networkInstance); } if (!canBeDeleted(claudiaData, networkInstance, region)) { log.info("The network cannot be deleted since it is using by another" + "blueprint"); return; } log.info("Deleting from DB"); deleteInDb(networkInstance, claudiaData.getVdc(), region); log.info("Deleting the public interface"); try { networkClient.deleteNetworkToPublicRouter(claudiaData, networkInstance, region); } catch (Exception e) { log.warn ("It is not possible to delete the public interface. " + "It is not exist: " + e.getMessage()); } log.info("Deleting the subnets"); Set<SubNetworkInstance> subNetAux = networkInstance.cloneSubNets(); for (SubNetworkInstance subNet : subNetAux) { subNetworkInstanceManager.delete(claudiaData, subNet, region); } log.info("Deleting the network"); networkClient.destroyNetwork(claudiaData, networkInstance, region); }

Target:
public void delete(ClaudiaData claudiaData, NetworkInstance networkInstance, String region) throws InvalidEntityException, InfrastructureException { log.info("Destroying network " + networkInstance.getNetworkName() + " region " + region); try { networkInstance = load(networkInstance.getNetworkName(), claudiaData.getVdc(), region); } catch (EntityNotFoundException e) { log.error("Error to remove the network in BD, since it is not exist in BD " + e.getMessage()); throw new InvalidEntityException(networkInstance); } if (!canBeDeleted(claudiaData, networkInstance, region)) { log.info("The network cannot be deleted since it is using by another" + "blueprint"); return; } log.info("Deleting from DB"); deleteInDb(networkInstance, claudiaData.getVdc(), region); log.info("Deleting the public interface"); try { networkClient.deleteNetworkToPublicRouter(claudiaData, networkInstance, region); } catch (Exception e) { log.warn ("It is not possible to delete the public interface. " + "It is not exist: " + e.getMessage()); } log.info("Deleting the subnets"); Set<SubNetworkInstance> subNetAux = networkInstance.cloneSubNets(); for (SubNetworkInstance subNet : subNetAux) { subNetworkInstanceManager.delete(claudiaData, subNet, region); } log.info("Deleting the network"); networkClient.destroyNetwork(claudiaData, networkInstance, region); }
Source:
public void checkCommentCodeFeature() { editor.selectTabByName("deployment.yaml"); editor.goToPosition(18, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor("# generation: 4"); editor.goToPosition(20, 1); editor.launchCommentCodeFeature(); editor.goToPosition(22, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor( "# generation: 4\n" + " labels:\n" + "# app: che\n" + " template: che\n" + "# name: che"); editor.goToPosition(18, 1); editor.launchCommentCodeFeature(); editor.goToPosition(20, 1); editor.launchCommentCodeFeature(); editor.goToPosition(22, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor( " generation: 4\n" + " labels:\n" + " app: che\n" + " template: che\n" + " name: che"); }

Target:
public void checkCommentCodeFeature() { editor.selectTabByName("deployment.yaml"); editor.goToPosition(18, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor("# generation: 4"); editor.goToPosition(20, 1); editor.launchCommentCodeFeature(); editor.goToPosition(22, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor(COMMENTED_CODE); editor.goToPosition(18, 1); editor.launchCommentCodeFeature(); editor.goToPosition(20, 1); editor.launchCommentCodeFeature(); editor.goToPosition(22, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor(UNCOMMENTED_CODE); }
Source:
public void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); maybeThrowIfCommitOffsetsNotOwned(offsets); log.debug("Committing offsets: {}", offsets); offsets.forEach(this::updateLastSeenEpochIfNewer); coordinator.commitOffsetsAsync(new HashMap<>(offsets), callback); } catch (CommitFailedException e) { log.error("Failed to commit offsets asynchronously because they do not belong to dynamically assigned partitions"); callback.onComplete(offsets, e); } finally { release(); } }

Target:
public void commitAsync(final Map<TopicPartition, OffsetAndMetadata> offsets, OffsetCommitCallback callback) { acquireAndEnsureOpen(); try { maybeThrowInvalidGroupIdException(); log.debug("Committing offsets: {}", offsets); offsets.forEach(this::updateLastSeenEpochIfNewer); coordinator.commitOffsetsAsync(new HashMap<>(offsets), callback); } finally { release(); } }
Source:
protected void tick(Block b) { BlockMenu inv = BlockStorage.getInventory(b); if (isProcessing(b)) { int timeleft = progress.get(b); if (timeleft > 0) { MachineHelper.updateProgressbar(inv, 22, timeleft, processing.get(b).getTicks(), getProgressBar()); if (ChargableBlock.getCharge(b) < getEnergyConsumption()) return; ChargableBlock.addCharge(b, -getEnergyConsumption()); progress.put(b, timeleft - 1); } else { inv.replaceExistingItem(22, new CustomItem(new ItemStack(Material.BLACK_STAINED_GLASS_PANE), " ")); inv.pushItem(SlimefunItems.BUCKET_OF_OIL, getOutputSlots()); progress.remove(b); processing.remove(b); } } else { for (int slot : getInputSlots()) { if (SlimefunManager.isItemSimilar(inv.getItemInSlot(slot), new ItemStack(Material.BUCKET), true)) { OreGenResource oil = OreGenSystem.getResource("Oil"); Chunk chunk = b.getChunk(); int supplies = OreGenSystem.getSupplies(oil, chunk, false); if(supplies > 0){ MachineRecipe r = new MachineRecipe(26, new ItemStack[0], new ItemStack[] {SlimefunItems.BUCKET_OF_OIL}); if (!inv.fits(SlimefunItems.BUCKET_OF_OIL, getOutputSlots())) { return; } inv.replaceExistingItem(slot, InvUtils.decreaseItem(inv.getItemInSlot(slot), 1)); processing.put(b, r); progress.put(b, r.getTicks()); OreGenSystem.setSupplies(oil, chunk, supplies - 1); break; }else{ ItemStack item = BlockStorage.getInventory(b).getItemInSlot(slot); ItemStack[] abucket = new ItemStack[1]; abucket[0]=item.clone(); BlockStorage.getInventory(b).replaceExistingItem(slot, null); pushItems(b, abucket); } } } } }

Target:
protected void tick(Block b) { BlockMenu inv = BlockStorage.getInventory(b); if (isProcessing(b)) { int timeleft = progress.get(b); if (timeleft > 0) { MachineHelper.updateProgressbar(inv, 22, timeleft, processing.get(b).getTicks(), getProgressBar()); if (ChargableBlock.getCharge(b) < getEnergyConsumption()) return; ChargableBlock.addCharge(b, -getEnergyConsumption()); progress.put(b, timeleft - 1); } else { inv.replaceExistingItem(22, new CustomItem(new ItemStack(Material.BLACK_STAINED_GLASS_PANE), " ")); inv.pushItem(SlimefunItems.BUCKET_OF_OIL, getOutputSlots()); progress.remove(b); processing.remove(b); } } else if (inv.fits(SlimefunItems.BUCKET_OF_OIL, getOutputSlots())) { for (int slot : getInputSlots()) { if (SlimefunManager.isItemSimilar(inv.getItemInSlot(slot), new ItemStack(Material.BUCKET), true)) { OreGenResource oil = OreGenSystem.getResource("Oil"); Chunk chunk = b.getChunk(); int supplies = OreGenSystem.getSupplies(oil, chunk, false); if (supplies > 0) { MachineRecipe r = new MachineRecipe(26, new ItemStack[0], new ItemStack[] {SlimefunItems.BUCKET_OF_OIL}); inv.replaceExistingItem(slot, InvUtils.decreaseItem(inv.getItemInSlot(slot), 1)); processing.put(b, r); progress.put(b, r.getTicks()); OreGenSystem.setSupplies(oil, chunk, supplies - 1); } else { ItemStack item = BlockStorage.getInventory(b).getItemInSlot(slot).clone(); BlockStorage.getInventory(b).replaceExistingItem(slot, null); pushItems(b, item); } break; } } } }
Source:
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); if( Defaults.APPLICATION_ID.equals( "" ) || Defaults.API_KEY.equals( "" ) || Defaults.VERSION.equals( "" ) || Defaults.CHANNEL_NAME.equals( "" ) ) { showAlert( this, "Missing application ID and api key arguments. Login to Backendless Console, select your app and get the ID and key from the Manage > App Settings screen. Copy/paste the values into the Backendless.initApp call" ); return; } final EditText nameField = (EditText) findViewById( R.id.nameField ); findViewById( R.id.startButton ).setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { String name = nameField.getText().toString(); if( name == null || name.equals( "" ) ) { Toast.makeText( MainActivity.this, "Please enter your name", Toast.LENGTH_SHORT ).show(); return; } Intent intent = new Intent( getBaseContext(), ChatActivity.class ); intent.putExtra( Defaults.NAME_TAG, name ); startActivity( intent ); } } ); }

Target:
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); if( Defaults.APPLICATION_ID.equals( "" ) || Defaults.API_KEY.equals( "" ) || Defaults.CHANNEL_NAME.equals( "" ) ) { showAlert( this, "Missing application ID and api key arguments. Login to Backendless Console, select your app and get the ID and key from the Manage > App Settings screen. Copy/paste the values into the Backendless.initApp call" ); return; } final EditText nameField = (EditText) findViewById( R.id.nameField ); findViewById( R.id.startButton ).setOnClickListener( new View.OnClickListener() { @Override public void onClick( View view ) { String name = nameField.getText().toString(); if( name == null || name.equals( "" ) ) { Toast.makeText( MainActivity.this, "Please enter your name", Toast.LENGTH_SHORT ).show(); return; } Intent intent = new Intent( getBaseContext(), ChatActivity.class ); intent.putExtra( Defaults.NAME_TAG, name ); startActivity( intent ); } } ); }
Source:
public List<Map> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException { return collectionDAO.getCollectionsWithBitstreamSizesTotal(context); }

Target:
public List<Map.Entry<Collection, Long>> getCollectionsWithBitstreamSizesTotal(Context context) throws SQLException { return collectionDAO.getCollectionsWithBitstreamSizesTotal(context); }
Source:
public RefreshPlan computePlan(CreatedOutput container) { RefreshPlan post = new RefreshPlan(signatureProvider); Collection<? extends Mapping> childMappings = container.getChildMappings(); pre.computeStatus(container, childMappings); post.addPreviousStatus(pre.getExistingOutputs()); Iterable<? extends Mapping> mappingsCreatingElements = Iterables.filter(childMappings, new Predicate<Mapping>() { @Override public boolean apply(Mapping input) { return input.getCreator().some(); } }); Iterable<Collection<MappingHiearchy>> transformedHiearchy = Iterables.transform(mappingsCreatingElements, toHierarchy); Iterable<MappingHiearchy> childHiearchies = Sets.newLinkedHashSet(Iterables.concat(transformedHiearchy)); for (MappingHiearchy nodeHiearch : childHiearchies) { Iterator<Mapping> it = nodeHiearch.fromMostSpecificToMostGeneral(); while (it.hasNext()) { Mapping cur = it.next(); if (cur.isEnabled() && cur.getCreator().some()) { Option<EvaluatedSemanticPartition> par = invalidator.hasFastResult(container.getDescriptor().getSourceElement(), cur.getSemanticPartition()); if (!par.some()) { par = Options.newSome(cur.getSemanticPartition().evaluate(container.getDescriptor().getSourceElement(), container)); } Collection<? extends OutputDescriptor> allCandidateDescriptors = cur.getCreator().get().computeDescriptors(container, par.get().elements()); post.appendOutputDescritorsKeepingTheMostSpecific(allCandidateDescriptors); } } } return post; }

Target:
public RefreshPlan computePlan(CreatedOutput container) { RefreshPlan post = new RefreshPlan(signatureProvider); Collection<? extends Mapping> childMappings = container.getChildMappings(); pre.computeStatus(container, childMappings); post.addPreviousStatus(pre.getExistingOutputs()); Iterable<? extends Mapping> mappingsCreatingElements = Iterables.filter(childMappings, new Predicate<Mapping>() { @Override public boolean apply(Mapping input) { return input.getCreator().some(); } }); Iterable<Collection<MappingHiearchy>> transformedHiearchy = Iterables.transform(mappingsCreatingElements, toHierarchy); Iterable<MappingHiearchy> childHiearchies = Sets.newLinkedHashSet(Iterables.concat(transformedHiearchy)); for (MappingHiearchy nodeHiearch : childHiearchies) { Iterator<Mapping> it = nodeHiearch.fromMostSpecificToMostGeneral(); while (it.hasNext()) { Mapping cur = it.next(); if (cur.isEnabled() && cur.getCreator().some()) { Option<EvaluatedSemanticPartition> par = invalidator.hasFastResult(container.getDescriptor().getSourceElement(), cur.getSemanticPartition(), container); if (!par.some()) { par = Options.newSome(cur.getSemanticPartition().evaluate(container.getDescriptor().getSourceElement(), container)); } Collection<? extends OutputDescriptor> allCandidateDescriptors = cur.getCreator().get().computeDescriptors(container, par.get().elements()); post.appendOutputDescritorsKeepingTheMostSpecific(allCandidateDescriptors); } } } return post; }
Source:
public void testGetSuggestions() { final JSONArray expectedSuggestions = mock(JSONArray.class); final List<JSONValue> suggestions = new ArrayList<>(); final List<String> variableSuggestions = buildVariableSuggestions(); when(this.variableSuggestions.getSuggestions()).thenReturn(variableSuggestions); buildKeywordSuggestions().forEach(suggestion -> { final JSONValue function = mock(JSONValue.class); suggestions.add(function); doReturn(function).when(factory).getKeywordSuggestion(suggestion); }); buildFunctionSuggestions().forEach(suggestion -> { final JSONValue function = mock(JSONValue.class); suggestions.add(function); doReturn(function).when(factory).getFunctionSuggestion(suggestion.get(0), suggestion.get(1)); }); variableSuggestions.forEach(suggestion -> { final JSONValue function = mock(JSONValue.class); suggestions.add(function); doReturn(function).when(factory).getVariableSuggestion(suggestion); }); doReturn(expectedSuggestions).when(factory).makeJSONArray(); final JSONArray actualSuggestions = factory.getSuggestions(this.variableSuggestions); suggestions.forEach(suggestion -> { verify(factory).push(expectedSuggestions, suggestion); }); assertEquals(expectedSuggestions, actualSuggestions); }

Target:
public void testGetSuggestions() { final JSONArray expectedSuggestions = mock(JSONArray.class); final List<JSONValue> suggestions = new ArrayList<>(); final List<String> variableSuggestions = buildVariableSuggestions(); when(this.variableSuggestions.getSuggestions()).thenReturn(variableSuggestions); buildKeywordSuggestions().forEach(suggestion -> { final JSONValue keyword = mock(JSONValue.class); suggestions.add(keyword); doReturn(keyword).when(factory).getKeywordSuggestion(suggestion); }); buildFunctionSuggestions().forEach(suggestion -> { final JSONValue function = mock(JSONValue.class); suggestions.add(function); doReturn(function).when(factory).getFunctionSuggestion(suggestion.get(0), suggestion.get(1)); }); variableSuggestions.forEach(suggestion -> { final JSONValue variable = mock(JSONValue.class); suggestions.add(variable); doReturn(variable).when(factory).getVariableSuggestion(suggestion); }); doReturn(expectedSuggestions).when(factory).makeJSONArray(); final JSONArray actualSuggestions = factory.getSuggestions(this.variableSuggestions); suggestions.forEach(suggestion -> { verify(factory).push(expectedSuggestions, suggestion); }); assertEquals(expectedSuggestions, actualSuggestions); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; MarkerQuorumPacket that = (MarkerQuorumPacket) o; return time == that.time; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MarkerQuorumPacket that = (MarkerQuorumPacket) o; return time == that.time; }
Source:
private String getSpecialFoldersList() { String builder = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; return builder; }

Target:
private String getSpecialFoldersList() { return "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; }
Source:
public void testAgentStatus() { Assert.assertNotNull( this.agent.agentStatus() ); }

Target:
public void testAgentStatus() throws Exception { Assert.assertNotNull( this.agent.agentStatus() ); this.agent.stop(); this.agent.getMessagingClient().getMessageProcessor().getMessageQueue().add(Mockito.mock(MsgNotifHeartbeat.class)); this.agent.getMessagingClient().getMessageProcessor().getMessageQueue().add(Mockito.mock(MsgNotifAutonomic.class)); this.agent.getMessagingClient().getMessageProcessor().getMessageQueue().add(Mockito.mock(MsgNotifLogs.class)); Assert.assertFalse( this.agent.agentStatus().startsWith( "There is no message" )); }
Source:
public static int getPrimaryColor(Context context) { if (primaryColor == -1) { String primaryColorStr = PreferenceManager.getDefaultSharedPreferences(context).getString("primary-color", COLOR_DEFAULT_STR); if (primaryColorStr.equals("#00000000") || primaryColorStr.equals(("#AAFFFFFF"))) { return 0xFFBDBDBD; } primaryColor = Color.parseColor(primaryColorStr); } return primaryColor; }

Target:
public static int getPrimaryColor(Context context) { if (primaryColor == -1) { String primaryColorStr = PreferenceManager.getDefaultSharedPreferences(context).getString("primary-color", COLOR_DEFAULT_STR); if (primaryColorStr.equals("#00000000") || primaryColorStr.equals(("#AAFFFFFF"))) { primaryColor = 0xFFBDBDBD; } else { primaryColor = Color.parseColor(primaryColorStr); } } return primaryColor; }
Source:
public Date getFirstPlayed() { @Nullable NBTTagCompound data = getData().isPresent() ? getData().get() : null; long time = 0L; if (data != null && data.hasKey("firstPlayed")) { time = data.getLong("firstPlayed"); } Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); return cal.getTime(); }

Target:
public Date getFirstPlayed() { Optional<NBTTagCompound> data = getData(); long time = (data.isPresent() && data.get().hasKey("firstPlayed")) ? data.get().getLong("firstPlayed") : 0L; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); return cal.getTime(); }
Source:
public String getVariableValue(String id) { TypedQuery<Variables> query = em.createNamedQuery("Variables.findById", Variables.class) .setParameter("id", id); try { Variables var = query.getSingleResult(); if (var != null) { return var.getValue(); } } catch (NoResultException e) { } return null; }

Target:
public String getVariableValue(String id) { TypedQuery<Variables> query = em.createNamedQuery("Variables.findById", Variables.class) .setParameter("id", id); try { Variables var = query.getSingleResult(); if (var != null) { return var.getValue(); } } catch (NoResultException e) { logger.log(Level.INFO, "Variable " + id + " not found in the database"); } return null; }
Source:
synchronized public void receiveMessage(Id groupId, Message message) { if (mCurrentNotifiableActivity == null || mCurrentGroup.getId().getId().equals(groupId.getId())) { List<Group> groups = YieldsApplication.getUser().getUserGroups(); for (Group group : groups) { if (group.getId().getId().equals(groupId.getId())) { group.addMessage(message); sendMessageNotification(group, message); } } } else { mCurrentGroup.addMessage(message); mCurrentNotifiableActivity.notifyChange(); } }

Target:
synchronized public void receiveMessage(Id groupId, Message message) { if (mCurrentNotifiableActivity == null || !mCurrentGroup.getId().getId().equals(groupId.getId())) { List<Group> groups = YieldsApplication.getUser().getUserGroups(); for (Group group : groups) { if (group.getId().getId().equals(groupId.getId())) { group.addMessage(message); sendMessageNotification(group, message); } } } else { mCurrentGroup.addMessage(message); mCurrentNotifiableActivity.notifyChange(); } }
Source:
private boolean hasMagicLinkSignupIntent() { if (mUri != null) { String parameter = SignupEpilogueActivity.MAGIC_SIGNUP_PARAMETER; String value = (mUri.getQueryParameterNames() != null && mUri.getQueryParameter(parameter) != null) ? mUri.getQueryParameter(parameter) : ""; return Intent.ACTION_VIEW.equals(mAction) && mUri.getQueryParameterNames().contains(parameter) && value.equalsIgnoreCase(SignupEpilogueActivity.MAGIC_SIGNUP_VALUE); } else { return false; } }

Target:
private boolean hasMagicLinkSignupIntent() { if (mUri != null) { String parameter = SignupEpilogueActivity.MAGIC_SIGNUP_PARAMETER; String value = (mUri.getQueryParameterNames() != null && mUri.getQueryParameter(parameter) != null) ? mUri.getQueryParameter(parameter) : ""; return Intent.ACTION_VIEW.equals(mAction) && value.equalsIgnoreCase(SignupEpilogueActivity.MAGIC_SIGNUP_VALUE); } else { return false; } }
Source:
public void onCompleted() { exchange.getIn().setBody(requestList); exchange.getIn().setHeaders(headers); consumer.process(exchange, doneSync -> { }); Object responseBody = exchange.getIn().getBody(); if (responseBody instanceof List) { List<Object> responseList = (List<Object>)responseBody; responseList.forEach((responseItem) -> { responseObserver.onNext(responseItem); }); } else { responseObserver.onNext(responseBody); } responseObserver.onCompleted(); }

Target:
public void onCompleted() { CountDownLatch latch = new CountDownLatch(1); Object responseBody = null; exchange.getIn().setBody(requestList); exchange.getIn().setHeaders(headers); consumer.process(exchange, doneSync -> { latch.countDown(); }); try { latch.await(); if (exchange.hasOut()) { responseBody = exchange.getOut().getBody(); } else { responseBody = exchange.getIn().getBody(); } if (responseBody instanceof List) { List<?> responseList = (List<?>)responseBody; responseList.forEach((responseItem) -> { responseObserver.onNext(responseItem); }); } else { responseObserver.onNext(responseBody); } responseObserver.onCompleted(); } catch (InterruptedException e) { responseObserver.onError(e); } }
Source:
private boolean fetchFromScheduledTaskQueue() { if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { return true; } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); for (Runnable scheduledTask; (scheduledTask = pollScheduledTask(nanoTime)) != null;) { if (!taskQueue.offer(scheduledTask)) { scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask); return false; } } return true; }

Target:
private boolean fetchFromScheduledTaskQueue() { if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { return true; } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); for (;;) { Runnable scheduledTask = pollScheduledTask(nanoTime); if (scheduledTask == null) { return true; } if (!taskQueue.offer(scheduledTask)) { scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask); return false; } } }
Source:
public static void register(AggregationImplModule module) { module.register( Signature.builder() .name(NAME) .kind(FunctionInfo.Type.AGGREGATE) .argumentTypes(parseTypeSignature("E")) .typeVariableConstraints(typeVariable("E")) .returnType(parseTypeSignature("array(E)")) .build(), args -> new ArrayAgg(args.get(0)) ); }

Target:
public static void register(AggregationImplModule module) { module.register( Signature.aggregate( NAME, parseTypeSignature("E"), parseTypeSignature("array(E)") ).withTypeVariableConstraints(typeVariable("E")), args -> new ArrayAgg(args.get(0)) ); }
Source:
public void testCreateTableUnsupportedPartitionType() { assertUpdate("" + "CREATE TABLE test_create_table_unsupported_partition_type " + "WITH (partitioned_by = ARRAY['a']) " + "AS " + "SELECT 123 x, ARRAY foo a"); }

Target:
public void testCreateTableUnsupportedPartitionType() { assertUpdate("" + "CREATE TABLE test_create_table_unsupported_partition_type " + "(foo bigint, bar ARRAY(varchar)) " + "WITH (partitioned_by = ARRAY['bar'])"); }
Source:
private void shareImage() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGalleryShare(pageTitle, galleryItem.getName()); new ImagePipelineBitmapGetter(galleryItem.getThumbUrl()){ @Override public void onSuccess(Bitmap bitmap) { ShareUtil.shareImage(parentActivity, bitmap, new java.io.File(galleryItem.getUrl()).getName(), pageTitle.getDisplayText(), imageTitle.getCanonicalUri()); } @Override public void onError(Throwable t) { FeedbackUtil.showError(getActivity(), t); } }.get(); }

Target:
private void shareImage() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGalleryShare(pageTitle, galleryItem.getName()); new ImagePipelineBitmapGetter(getActivity(), galleryItem.getThumbUrl()){ @Override public void onSuccess(Bitmap bitmap) { if (!isAdded()) { return; } ShareUtil.shareImage(parentActivity, bitmap, new java.io.File(galleryItem.getUrl()).getName(), pageTitle.getDisplayText(), imageTitle.getCanonicalUri()); } }.get(); }
Source:
public void getGroupObjectUnauthorizedTest() throws Exception { GroupService groupService = EPersonServiceFactory.getInstance().getGroupService(); Group adminGroup = null; try { context.turnOffAuthorisationSystem(); adminGroup = groupService.create(context); context.commit(); adminGroup = context.reloadEntity(adminGroup); getClient().perform( get("/api/eperson/groups/" + adminGroup.getID() + "/object") ).andExpect(status().isUnauthorized()); } finally { if (adminGroup != null) { GroupBuilder.deleteGroup(adminGroup.getID()); } } }

Target:
public void getGroupObjectUnauthorizedTest() throws Exception { context.turnOffAuthorisationSystem(); Community community = CommunityBuilder.createCommunity(context) .withName("Parent Community") .withAdminGroup(admin) .build(); Group adminGroup = community.getAdministrators(); context.restoreAuthSystemState(); getClient().perform( get("/api/eperson/groups/" + adminGroup.getID() + "/object") ).andExpect(status().isUnauthorized()); }
Source:
private HookResult runSyncHook(Project.NameKey project, File hook, List<String> args) throws TimeoutException { HookResult result = null; if (hook.exists()) { SyncHookTask syncHook = new SyncHookTask(project, hook, args); FutureTask<HookResult> task = new FutureTask<HookResult>(syncHook); syncHookThreadPool.execute(task); try { result = task.get(syncHookTimeout, TimeUnit.SECONDS); } catch (TimeoutException e) { task.cancel(true); log.error("Synchronous hook timed out " + hook.getAbsolutePath()); result = new HookResult(syncHook.getOutput(), "Synchronous hook timed out"); } catch (Exception e) { task.cancel(true); log.error("Error running hook " + hook.getAbsolutePath(), e); result = new HookResult(syncHook.getOutput(), "Error running hook: " + e); } } return result; }

Target:
private HookResult runSyncHook(Project.NameKey project, File hook, List<String> args) throws TimeoutException { if (!hook.exists()) { return null; } HookResult result = null; SyncHookTask syncHook = new SyncHookTask(project, hook, args); FutureTask<HookResult> task = new FutureTask<HookResult>(syncHook); syncHookThreadPool.execute(task); try { result = task.get(syncHookTimeout, TimeUnit.SECONDS); } catch (TimeoutException e) { task.cancel(true); syncHook.cancel(); log.error("Synchronous hook timed out " + hook.getAbsolutePath()); result = new HookResult(syncHook.getOutput(), "Synchronous hook timed out"); } catch (Exception e) { task.cancel(true); syncHook.cancel(); log.error("Error running hook " + hook.getAbsolutePath(), e); result = new HookResult(syncHook.getOutput(), "Error running hook: " + e); } return result; }
Source:
private Stream<String> getAgentMembers(final IdentifierConverter<Resource, FedoraResource> translator, final FedoraResource resource) { return resource.getTriples(translator, PROPERTIES).filter(memberTestFromTypes.apply(resource.getTypes())) .map(Triple::getObject) .map(object -> object.isURI() ? object.getURI() : object.getLiteralValue().toString()); }

Target:
private static Stream<String> getAgentMembers(final IdentifierConverter<Resource, FedoraResource> translator, final FedoraResource resource) { return resource.getTriples(translator, PROPERTIES).filter(memberTestFromTypes.apply(resource.getTypes())) .map(Triple::getObject).flatMap(WebACRolesProvider::nodeToStringStream); }
Source:
private void handleSubmitError(SubmitJob job) { if (form != null && !form.isDisposed()) { final IStatus status = job.getStatus(); String message = null; if (status.getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) { TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Comment_required, status); AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT); if (newCommentPart != null) { newCommentPart.setFocus(); } } else if (status.getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { if (TasksUiUtil.openEditRepositoryWizard(getTaskRepository()) == Window.OK) { submitEnabled = true; doSubmit(); return; } else { message = getMessageFromStatus(status); } } else { if (status.getCode() == RepositoryStatus.ERROR_IO) { message = ERROR_NOCONNECTIVITY; } else { message = getMessageFromStatus(status); if (message == null) { message = Messages.AbstractTaskEditorPage_Submit_failed; } } } if (message != null) { getTaskEditor().setMessage(message, IMessageProvider.ERROR, new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Submit_failed, status); } }); } } }

Target:
private void handleSubmitError(SubmitJob job) { if (form != null && !form.isDisposed()) { final IStatus status = job.getStatus(); String message = null; if (status.getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) { TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Comment_required, status); AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT); if (newCommentPart != null) { newCommentPart.setFocus(); } return; } else if (status.getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { if (TasksUiUtil.openEditRepositoryWizard(getTaskRepository()) == Window.OK) { submitEnabled = true; doSubmit(); return; } else { message = getMessageFromStatus(status); } } else if (status.getCode() == RepositoryStatus.ERROR_IO) { message = ERROR_NOCONNECTIVITY; } else { message = getMessageFromStatus(status); if (message == null) { message = Messages.AbstractTaskEditorPage_Submit_failed; } } getTaskEditor().setMessage(message, IMessageProvider.ERROR, new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Submit_failed, status); } }); } }
Source:
protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (!disConnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }

Target:
protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } List<StorageDomainStatic> storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (!disconnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }
Source:
protected void doSetUserClaimValue(String userName, String claimURI, String claimValue, String profileName) throws UserStoreException { try { String attributeName = getClaimAtrribute(claimURI, userName, null); Map<String, String> userStoreAttributeValueMap = new HashMap<>(); userStoreAttributeValueMap.put(attributeName, claimValue); processAttributesBeforeUpdate(userStoreAttributeValueMap); for (Map.Entry<String, String> entry : userStoreAttributeValueMap.entrySet()) { doSetUserAttribute(userName, entry.getKey(), entry.getValue(), profileName); } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new UserStoreException( "Error occurred while getting the claim attribute for claimURI: " + claimURI + " of the user: " + userName); } }

Target:
protected void doSetUserClaimValue(String userName, String claimURI, String claimValue, String profileName) throws UserStoreException { try { String attributeName = getClaimAtrribute(claimURI, userName, null); Map<String, String> userStoreAttributeValueMap = new HashMap<>(); userStoreAttributeValueMap.put(attributeName, claimValue); processAttributesBeforeUpdate(userName, userStoreAttributeValueMap, profileName); for (Map.Entry<String, String> entry : userStoreAttributeValueMap.entrySet()) { doSetUserAttribute(userName, entry.getKey(), entry.getValue(), profileName); } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new UserStoreException( "Error occurred while getting the claim attribute for claimURI: " + claimURI + " of the user: " + userName, e); } }
Source:
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { while (true) { try { return method.invoke(delegate(), args); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof NotCurrentLeaderException) { Thread.sleep(10); continue; } throw targetException; } } }

Target:
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable { while (true) { if (Thread.currentThread().isInterrupted()) { throw new SafeIllegalStateException("interrupted"); } try { return method.invoke(delegate(), args); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof NotCurrentLeaderException) { Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS); continue; } throw targetException; } } }
Source:
public boolean performNextOperation(int completedChildCount) { switch(getParameters().getImportPhase()) { case CREATE_DISKS: getParameters().setImportPhase(Phase.CONVERT); if (getParameters().getProxyHostId() == null) { getParameters().setProxyHostId(selectProxyHost()); } break; case CONVERT: if (EnumSet.of(OriginType.OVIRT).contains(getVm().getOrigin())) { return false; } getParameters().setImportPhase(Phase.POST_CONVERT); break; case POST_CONVERT: return false; default: } persistCommandIfNeeded(); executeNextOperation(); return true; }

Target:
public boolean performNextOperation(int completedChildCount) { switch(getParameters().getImportPhase()) { case CREATE_DISKS: getParameters().setImportPhase(Phase.CONVERT); if (getParameters().getProxyHostId() == null) { getParameters().setProxyHostId(selectProxyHost()); } break; case CONVERT: if (getVm().getOrigin() == OriginType.OVIRT) { return false; } getParameters().setImportPhase(Phase.POST_CONVERT); break; case POST_CONVERT: return false; default: } persistCommandIfNeeded(); executeNextOperation(); return true; }
Source:
public VoidResult call() throws NoSuchRefException, NoSuchProjectException, IOException, ConfigInvalidException, OrmConcurrencyException, InvalidNameException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); final MetaDataUpdate md; try { md = metaDataUpdateFactory.create(projectName); } catch (RepositoryNotFoundException notFound) { throw new NoSuchProjectException(projectName); } try { final ProjectConfig config = ProjectConfig.read(md, base); Set<String> toDelete = scanSectionNames(config); for (MergeStrategySection section : distinctMergeSections(sectionList)) { final String name = section.getName(); if (!projectControl.controlForRef(name).isOwner()) { throw new NoSuchRefException(section.getName()); } RefControl.validateRefPattern(name); config.replace(section); toDelete.remove(section.getName()); } for (String name : toDelete) { if (projectControl.controlForRef(name).isOwner()) { config.remove(config.getMergeStrategySection(name)); } } if (message != null && !message.isEmpty()) { if (!message.endsWith("\n")) { message += "\n"; } md.setMessage(message); } else { md.setMessage("Modify merge strategy\n"); } if (config.commit(md)) { projectCache.evict(config.getProject()); return VoidResult.INSTANCE; } else { throw new OrmConcurrencyException("Cannot update " + projectName); } } finally { md.close(); } }

Target:
public VoidResult call() throws NoSuchRefException, NoSuchProjectException, IOException, ConfigInvalidException, OrmConcurrencyException, InvalidNameException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); final MetaDataUpdate md; try { md = metaDataUpdateFactory.create(projectName); } catch (RepositoryNotFoundException notFound) { throw new NoSuchProjectException(projectName); } try { final ProjectConfig config = ProjectConfig.read(md, base); Set<String> toDelete = scanSectionNames(config); final Set<MergeStrategySection> mergeSections = new HashSet<MergeStrategySection>(sectionList); for (MergeStrategySection section : mergeSections) { final String name = section.getName(); if (!projectControl.isVisible() || !projectControl.controlForRef(name).isOwner()) { continue; } RefControl.validateRefPattern(name); config.replace(section); toDelete.remove(section.getName()); } for (String name : toDelete) { if (projectControl.controlForRef(name).isOwner()) { config.remove(config.getMergeStrategySection(name)); } } if (message != null && !message.isEmpty()) { if (!message.endsWith("\n")) { message += "\n"; } md.setMessage(message); } else { md.setMessage("Modify merge strategy\n"); } if (config.commit(md)) { projectCache.evict(config.getProject()); return VoidResult.INSTANCE; } else { throw new OrmConcurrencyException("Cannot update " + projectName); } } finally { md.close(); } }
Source:
public void testSavedBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO","foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); CopyArtifactPermissionProperty cpp=new CopyArtifactPermissionProperty("/"+p.getName()); other.addProperty(cpp); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, new SavedBuildSelector(), "*.txt", "", false, false, true)); FreeStyleBuild b = other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get(); rule.assertBuildStatusSuccess(b); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); b.keepLog(true); b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }

Target:
public void testSavedBuildSelector() throws Exception { FreeStyleProject other = createArtifactProject(), p = rule.createFreeStyleProject(); ParameterDefinition paramDef = new StringParameterDefinition("FOO", "foo"); ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef); other.addProperty(paramsDef); p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact(other.getName(), null, new SavedBuildSelector(), "*.txt", "", false, false, true)); FreeStyleBuild b = other.scheduleBuild2(0, new UserCause(), new ParametersAction(new StringParameterValue("FOO", "buildone"))).get(); rule.assertBuildStatusSuccess(b); rule.assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause())); b.keepLog(true); b = p.scheduleBuild2(0, new UserCause()).get(); rule.assertBuildStatusSuccess(b); assertFile(true, "foo.txt", b); assertFile(true, "buildone.txt", b); assertFile(false, "subdir/subfoo.txt", b); }
Source:
public void nextTuple() { try { if (initialized) { if (refreshSubscriptionTimer.isExpiredResetOnTrue()) { kafkaSpoutConfig.getSubscription().refreshAssignment(); } if (isCommitAllowed()) { commitOffsetsForAckedTuples(); } PollablePartitionInfo pollablePartitionInfo = getPollablePartitionInfo(); if (!pollablePartitionInfo.isPollAllowed()) { try { setWaitingToEmit(pollKafkaBroker(pollablePartitionInfo)); } catch (RetriableException e) { LOG.error("Failed to poll from kafka.", e); } } emitIfWaitingNotEmitted(); } else { LOG.debug("Spout not initialized. Not sending tuples until initialization completes"); } } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } }

Target:
public void nextTuple() { try { if (initialized) { if (refreshSubscriptionTimer.isExpiredResetOnTrue()) { kafkaSpoutConfig.getSubscription().refreshAssignment(); } if (shouldCommit()) { commitOffsetsForAckedTuples(); } PollablePartitionsInfo pollablePartitionsInfo = getPollablePartitionsInfo(); if (pollablePartitionsInfo.shouldPoll()) { try { setWaitingToEmit(pollKafkaBroker(pollablePartitionsInfo)); } catch (RetriableException e) { LOG.error("Failed to poll from kafka.", e); } } emitIfWaitingNotEmitted(); } else { LOG.debug("Spout not initialized. Not sending tuples until initialization completes"); } } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } }
Source:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { try { Map<String, String> output = Maps.newHashMap(); List<Journal> journals = Lists.newArrayListWithCapacity(conf.getJournalDirs().length); for (File journalDir : conf.getJournalDirs()) { journals.add(new Journal(journalDir, conf, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())))); } for (Journal journal : journals) { LogMark lastLogMark = journal.getLastLogMark().getCurMark(); LOG.debug("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn), Pos - " + lastLogMark.getLogFileOffset()); output.put("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn)", "Pos - " + lastLogMark.getLogFileOffset()); } String jsonResponse = JsonUtil.toJson(output); LOG.info("output body:" + jsonResponse); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } catch (Exception e) { e.printStackTrace(); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("ERROR handling request: " + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } }

Target:
public HttpServiceResponse handle(HttpServiceRequest request) throws Exception { HttpServiceResponse response = new HttpServiceResponse(); if (HttpServer.Method.GET == request.getMethod()) { try { Map<String, String> output = Maps.newHashMap(); List<Journal> journals = Lists.newArrayListWithCapacity(conf.getJournalDirs().length); for (File journalDir : conf.getJournalDirs()) { journals.add(new Journal(journalDir, conf, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())))); } for (Journal journal : journals) { LogMark lastLogMark = journal.getLastLogMark().getCurMark(); LOG.debug("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn), Pos - " + lastLogMark.getLogFileOffset()); output.put("LastLogMark: Journal Id - " + lastLogMark.getLogFileId() + "(" + Long.toHexString(lastLogMark.getLogFileId()) + ".txn)", "Pos - " + lastLogMark.getLogFileOffset()); } String jsonResponse = JsonUtil.toJson(output); LOG.debug("output body:" + jsonResponse); response.setBody(jsonResponse); response.setCode(HttpServer.StatusCode.OK); return response; } catch (Exception e) { LOG.error("Exception occurred while getting last log mark", e); response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("ERROR handling request: " + e.getMessage()); return response; } } else { response.setCode(HttpServer.StatusCode.NOT_FOUND); response.setBody("Not found method. Should be GET method"); return response; } }
Source:
private static BytecodeBlock generateCheckYieldBlock(Variable thisVariable, Variable index, FieldDefinition yieldSignal, FieldDefinition nextIndexOrPosition) { return new BytecodeBlock() .comment("if (yieldSignal.isSet()) return Optional.empty();") .append(new BytecodeBlock() .append(new IfStatement() .condition(thisVariable.getField(yieldSignal).invoke("isSet", boolean.class)) .ifTrue(new BytecodeBlock() .comment("nextIndexOrPosition = index + 1;") .append(thisVariable.setField(nextIndexOrPosition, add(index, constantInt(1)))) .comment("return Optional.empty();") .append(invokeStatic(Optional.class, "empty", Optional.class).ret())))); }

Target:
private static BytecodeBlock generateCheckYieldBlock(Variable thisVariable, Variable index, FieldDefinition yieldSignal, FieldDefinition nextIndexOrPosition) { return new BytecodeBlock() .comment("if (yieldSignal.isSet()) return Optional.empty();") .append(new IfStatement() .condition(thisVariable.getField(yieldSignal).invoke("isSet", boolean.class)) .ifTrue(new BytecodeBlock() .comment("nextIndexOrPosition = index + 1;") .append(thisVariable.setField(nextIndexOrPosition, add(index, constantInt(1)))) .comment("return Optional.empty();") .append(invokeStatic(Optional.class, "empty", Optional.class).ret()))); }